repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class FlowDiagnosticTests : FlowTestBase { [Fact] public void TestBug12350() { // We suppress the "local variable is only written" warning if the // variable is assigned a non-constant value. string program = @" class Program { static int X() { return 1; } static void M() { int i1 = 123; // 0219 int i2 = X(); // no warning int? i3 = 123; // 0219 int? i4 = null; // 0219 int? i5 = X(); // no warning int i6 = default(int); // 0219 int? i7 = default(int?); // 0219 int? i8 = new int?(); // 0219 int i9 = new int(); // 0219 } }"; CreateCompilation(program).VerifyDiagnostics( // (7,13): warning CS0219: The variable 'i1' is assigned but its value is never used // int i1 = 123; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1"), // (9,14): warning CS0219: The variable 'i3' is assigned but its value is never used // int? i3 = 123; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i3").WithArguments("i3"), // (10,14): warning CS0219: The variable 'i4' is assigned but its value is never used // int? i4 = null; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i4").WithArguments("i4"), // (12,13): warning CS0219: The variable 'i6' is assigned but its value is never used // int i6 = default(int); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i6").WithArguments("i6"), // (13,14): warning CS0219: The variable 'i7' is assigned but its value is never used // int? i7 = default(int?); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i7").WithArguments("i7"), // (14,14): warning CS0219: The variable 'i8' is assigned but its value is never used // int? i8 = new int?(); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i8").WithArguments("i8"), // (15,13): warning CS0219: The variable 'i9' is assigned but its value is never used // int i9 = new int(); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i9").WithArguments("i9")); } [Fact] public void Test1() { string program = @" namespace ConsoleApplication1 { class Program { public static void F(int z) { int x; if (z == 2) { int y = x; x = y; // use of unassigned local variable 'x' } else { int y = x; x = y; // diagnostic suppressed here } } } }"; CreateCompilation(program).VerifyDiagnostics( // (11,25): error CS0165: Use of unassigned local variable 'x' // int y = x; x = y; // use of unassigned local variable 'x' Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x") ); } [Fact] public void Test2() { //x is "assigned when true" after "false" //Therefore x is "assigned" before "z == 1" (5.3.3.24) //Therefore x is "assigned" after "z == 1" (5.3.3.20) //Therefore x is "assigned when true" after "(false && z == 1)" (5.3.3.24) //Since the condition of the ?: expression is the constant true, the state of x after the ?: expression is the same as the state of x after the consequence (5.3.3.28) //Since the state of x after the consequence is "assigned when true", the state of x after the ?: expression is "assigned when true" (5.3.3.28) //Since the state of x after the if's condition is "assigned when true", x is assigned in the then block (5.3.3.5) //Therefore, there should be no error. string program = @" namespace ConsoleApplication1 { class Program { void F(int z) { int x; if (true ? (false && z == 1) : true) x = x + 1; // Dev10 complains x not assigned. } } }"; var comp = CreateCompilation(program); var errs = this.FlowDiagnostics(comp); Assert.Equal(0, errs.Count()); } [Fact] public void Test3() { string program = @" class Program { int F(int z) { } }"; var comp = CreateCompilation(program); var errs = this.FlowDiagnostics(comp); Assert.Equal(1, errs.Count()); } [Fact] public void Test4() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" class Program { void F() { if (false) { int x; // warning: unreachable code x = x + 1; // no error: x assigned when unreachable } } }"; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(1, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [Fact] public void Test5() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" class A { static void F() { goto L2; goto L1; // unreachable code detected int x; L1: ; // Roslyn: extrs warning CS0162 -unreachable code x = x + 1; // no definite assignment problem in unreachable code L2: ; } } "; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(2, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [WorkItem(537918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537918")] [Fact] public void AssertForInvalidBreak() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" public class Test { public static int Main() { int ret = 1; break; // Assert here return (ret); } } "; var comp = CreateCompilation(program); comp.GetMethodBodyDiagnostics().Verify( // (7,9): error CS0139: No enclosing loop out of which to break or continue // break; // Assert here Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;")); } [WorkItem(538064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538064")] [Fact] public void IfFalse() { string program = @" using System; class Program { static void Main() { if (false) { } } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538067")] [Fact] public void WhileConstEqualsConst() { string program = @" using System; class Program { bool goo() { const bool b = true; while (b == b) { return b; } } static void Main() { } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538175")] [Fact] public void BreakWithoutTarget() { string program = @"public class Test { public static void Main() { if (true) break; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void OutCausesAssignment() { string program = @"class Program { void F(out int x) { G(out x); } void G(out int x) { x = 1; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void OutNotAssigned01() { string program = @"class Program { bool b; void F(out int x) { if (b) return; } }"; var comp = CreateCompilation(program); Assert.Equal(2, this.FlowDiagnostics(comp).Count()); } [WorkItem(539374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539374")] [Fact] public void OutAssignedAfterCall01() { string program = @"class Program { void F(out int x, int y) { x = y; } void G() { int x; F(out x, x); } }"; var comp = CreateCompilation(program); Assert.Equal(1, this.FlowDiagnostics(comp).Count()); } [WorkItem(538067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538067")] [Fact] public void WhileConstEqualsConst2() { string program = @" using System; class Program { bool goo() { const bool b = true; while (b == b) { return b; } return b; // Should detect this line as unreachable code. } static void Main() { } }"; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(1, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [WorkItem(538072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538072")] [Fact] public void UnusedLocal() { string program = @" using System; class Program { int x; int y; int z; static void Main() { int a; const bool b = true; } void goo() { y = 2; Console.WriteLine(z); } }"; var comp = CreateCompilation(program); int[] count = new int[4]; Dictionary<int, int> warnings = new Dictionary<int, int>(); foreach (var e in this.FlowDiagnostics(comp)) { count[(int)e.Severity]++; if (!warnings.ContainsKey(e.Code)) warnings[e.Code] = 0; warnings[e.Code] += 1; } Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); // See bug 3562 - field level flow analysis warnings CS0169, CS0414 and CS0649 are out of scope for M2. // TODO: Fix this test once CS0169, CS0414 and CS0649 are implemented. // Assert.Equal(5, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(2, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(1, warnings[168]); Assert.Equal(1, warnings[219]); // See bug 3562 - field level flow analysis warnings CS0169, CS0414 and CS0649 are out of scope for M2. // TODO: Fix this test once CS0169, CS0414 and CS0649 are implemented. // Assert.Equal(1, warnings[169]); // Assert.Equal(1, warnings[414]); // Assert.Equal(1, warnings[649]); } [WorkItem(538384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538384")] [Fact] public void UnusedLocalConstants() { string program = @" using System; class Program { static void Main() { const string CONST1 = ""hello""; // Should not report CS0219 Console.WriteLine(CONST1 != ""hello""); int i = 1; const long CONST2 = 1; const uint CONST3 = 1; // Should not report CS0219 while (CONST2 < CONST3 - i) { if (CONST3 < CONST3 - i) continue; } } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538385")] [Fact] public void UnusedLocalReferenceTypedVariables() { string program = @" using System; class Program { static void Main() { object o = 1; // Should not report CS0219 Test c = new Test(); // Should not report CS0219 c = new Program(); string s = string.Empty; // Should not report CS0219 s = null; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538386")] [Fact] public void UnusedLocalValueTypedVariables() { string program = @" using System; class Program { static void Main() { } public void Repro2(params int[] x) { int i = x[0]; // Should not report CS0219 byte b1 = 1; byte b11 = b1; // Should not report CS0219 } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void RefParameter01() { string program = @" class Program { public static void Main(string[] args) { int i; F(ref i); // use of unassigned local variable 'i' } static void F(ref int i) { } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void OutParameter01() { string program = @" class Program { public static void Main(string[] args) { int i; F(out i); int j = i; } static void F(out int i) { i = 1; } }"; var comp = CreateCompilation(program); Assert.Empty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void Goto01() { string program = @" using System; class Program { public void M(bool b) { if (b) goto label; int i; i = 3; i = i + 1; label: int j = i; // i not definitely assigned } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaParameters() { string program = @" using System; class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { Func fnc = (ref int arg, int arg2) => { arg = arg; }; } }"; var comp = CreateCompilation(program); Assert.Empty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaMightNotBeInvoked() { string program = @" class Program { delegate void Func(); static void Main(string[] args) { int i; Func query = () => { i = 12; }; int j = i; } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaMustAssignOutParameters() { string program = @" class Program { delegate void Func(out int x); static void Main(string[] args) { Func query = (out int x) => { }; } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact, WorkItem(528052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528052")] public void InnerVariablesAreNotDefinitelyAssignedInBeginningOfLambdaBody() { string program = @" using System; class Program { static void Main() { return; Action f = () => { int y = y; }; } }"; CreateCompilation(program).VerifyDiagnostics( // (9,9): warning CS0162: Unreachable code detected // Action f = () => { int y = y; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Action"), // (9,36): error CS0165: Use of unassigned local variable 'y' // Action f = () => { int y = y; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y") ); } [WorkItem(540139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540139")] [Fact] public void DelegateCreationReceiverIsRead() { string program = @" using System; class Program { static void Main() { Action a; Func<string> b = new Func<string>(a.ToString); } } "; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [WorkItem(540405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540405")] [Fact] public void ErrorInFieldInitializerLambda() { string program = @" using System; class Program { static Func<string> x = () => { string s; return s; }; static void Main() { } } "; CreateCompilation(program).VerifyDiagnostics( // (6,54): error CS0165: Use of unassigned local variable 's' // static Func<string> x = () => { string s; return s; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s") ); } [WorkItem(541389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541389")] [Fact] public void IterationWithEmptyBody() { string program = @" public class A { public static void Main(string[] args) { for (int i = 0; i < 10; i++) ; foreach (var v in args); int len = args.Length; while (len-- > 0); } }"; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(541389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541389")] [Fact] public void SelectionWithEmptyBody() { string program = @" public class A { public static void Main(string[] args) { int len = args.Length; if (len++ < 9) ; else ; } }"; CreateCompilation(program).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";")); } [WorkItem(542146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542146")] [Fact] public void FieldlikeEvent() { string program = @"public delegate void D(); public struct S { public event D Ev; public S(D d) { Ev = null; Ev += d; } }"; CreateCompilation(program).VerifyDiagnostics( // (4,20): warning CS0414: The field 'S.Ev' is assigned but its value is never used // public event D Ev; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Ev").WithArguments("S.Ev")); } [WorkItem(542187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542187")] [Fact] public void GotoFromTry() { string program = @"class Test { static void F(int x) { } static void Main() { int a; try { a = 1; goto L1; } finally { } L1: F(a); } }"; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(542154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542154")] [Fact] public void UnreachableThrow() { string program = @"public class C { static void Main() { return; throw Goo(); } static System.Exception Goo() { System.Console.WriteLine(""Hello""); return null; } } "; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(542585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542585")] [Fact] public void Bug9870() { string program = @" struct S<T> { T x; static void Goo() { x.x = 1; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'S<T>.x' // x.x = 1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x").WithArguments("S<T>.x") ); } [WorkItem(542597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542597")] [Fact] public void LambdaEntryPointIsReachable() { string program = @"class Program { static void Main(string[] args) { int i; return; System.Action a = () => { int j = i + j; }; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // unreachable statement // (7,23): warning CS0162: Unreachable code detected // System.Action a = () => Diagnostic(ErrorCode.WRN_UnreachableCode, "System"), // (9,25): error CS0165: Use of unassigned local variable 'j' // int j = i + j; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j") ); } [WorkItem(542597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542597")] [Fact] public void LambdaInUnimplementedPartial() { string program = @"using System; partial class C { static partial void Goo(Action a); static void Main() { Goo(() => { int x, y = x; }); } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (9,32): error CS0165: Use of unassigned local variable 'x' // Goo(() => { int x, y = x; }); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x") ); } [WorkItem(541887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541887")] [Fact] public void CascadedDiagnostics01() { string program = @" class Program { static void Main(string[] args) { var s = goo<,int>(123); } public static int goo<T>(int i) { return 1; } }"; var comp = CreateCompilation(program); var parseErrors = comp.SyntaxTrees[0].GetDiagnostics(); var errors = comp.GetDiagnostics(); Assert.Equal(parseErrors.Count(), errors.Count()); } [Fact] public void UnassignedInInitializer() { string program = @"class C { System.Action a = () => { int i; int j = i; }; }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (3,46): error CS0165: Use of unassigned local variable 'i' // System.Action a = () => { int i; int j = i; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i") ); } [WorkItem(543343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543343")] [Fact] public void ConstInSwitch() { string program = @"class Program { static void Main(string[] args) { switch (args.Length) { case 0: const int N = 3; break; case 1: int M = N; break; } } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (11,21): warning CS0219: The variable 'M' is assigned but its value is never used // int M = N; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "M").WithArguments("M") ); } #region "Struct" [Fact] public void CycleWithInitialization() { string program = @" public struct A { A a = new A(); // CS8036 public static void Main() { A a = new A(); } } "; CreateCompilation(program, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (4,7): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a").WithArguments("struct field initializers", "10.0").WithLocation(4, 7), // (4,7): error CS0523: Struct member 'A.a' of type 'A' causes a cycle in the struct layout // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "a").WithArguments("A.a", "A").WithLocation(4, 7), // (7,11): warning CS0219: The variable 'a' is assigned but its value is never used // A a = new A(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(7, 11), // (4,7): warning CS0414: The field 'A.a' is assigned but its value is never used // A a = new A(); // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("A.a").WithLocation(4, 7)); } [WorkItem(542356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542356")] [Fact] public void StaticMemberExplosion() { string program = @" struct A<T> { static A<A<T>> x; } struct B<T> { static A<B<T>> x; } struct C<T> { static D<T> x; } struct D<T> { static C<D<T>> x; } "; CreateCompilation(program) .VerifyDiagnostics( // (14,17): error CS0523: Struct member 'C<T>.x' of type 'D<T>' causes a cycle in the struct layout // static D<T> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("C<T>.x", "D<T>").WithLocation(14, 17), // (18,20): error CS0523: Struct member 'D<T>.x' of type 'C<D<T>>' causes a cycle in the struct layout // static C<D<T>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("D<T>.x", "C<D<T>>").WithLocation(18, 20), // (4,20): error CS0523: Struct member 'A<T>.x' of type 'A<A<T>>' causes a cycle in the struct layout // static A<A<T>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("A<T>.x", "A<A<T>>").WithLocation(4, 20), // (9,20): warning CS0169: The field 'B<T>.x' is never used // static A<B<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("B<T>.x").WithLocation(9, 20), // (4,20): warning CS0169: The field 'A<T>.x' is never used // static A<A<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("A<T>.x").WithLocation(4, 20), // (18,20): warning CS0169: The field 'D<T>.x' is never used // static C<D<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("D<T>.x").WithLocation(18, 20), // (14,17): warning CS0169: The field 'C<T>.x' is never used // static D<T> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C<T>.x").WithLocation(14, 17) ); } [Fact] public void StaticSequential() { string program = @" partial struct S { public static int x; } partial struct S { public static int y; }"; CreateCompilation(program) .VerifyDiagnostics( // (4,23): warning CS0649: Field 'S.x' is never assigned to, and will always have its default value 0 // public static int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S.x", "0"), // (9,23): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public static int y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [WorkItem(542567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542567")] [Fact] public void ImplicitFieldSequential() { string program = @"partial struct S1 { public int x; } partial struct S1 { public int y { get; set; } } partial struct S2 { public int x; } delegate void D(); partial struct S2 { public event D y; }"; CreateCompilation(program) .VerifyDiagnostics( // (1,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'S1'. To specify an ordering, all instance fields must be in the same declaration. // partial struct S1 Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "S1").WithArguments("S1"), // (11,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'S2'. To specify an ordering, all instance fields must be in the same declaration. // partial struct S2 Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "S2").WithArguments("S2"), // (3,16): warning CS0649: Field 'S1.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S1.x", "0"), // (13,16): warning CS0649: Field 'S2.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S2.x", "0"), // (19,20): warning CS0067: The event 'S2.y' is never used // public event D y; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "y").WithArguments("S2.y") ); } [Fact] public void StaticInitializer() { string program = @" public struct A { static System.Func<int> d = () => { int j; return j * 9000; }; public static void Main() { } } "; CreateCompilation(program) .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j") ); } [Fact] public void AllPiecesAssigned() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s; s.x = args.Length; s.y = args.Length; S t = s; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void OnePieceMissing() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s; s.x = args.Length; S t = s; } } "; CreateCompilation(program) .VerifyDiagnostics( // (12,15): error CS0165: Use of unassigned local variable 's' // S t = s; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s"), // (4,19): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [Fact] public void OnePieceOnOnePath() { string program = @" struct S { public int x, y; } class Program { public void F(S s) { S s2; if (s.x == 3) s2 = s; else s2.x = s.x; int x = s2.x; } } "; CreateCompilation(program) .VerifyDiagnostics( // (4,19): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [Fact] public void DefaultConstructor() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s = new S(); s.x = s.y = s.x; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void FieldAssignedInConstructor() { string program = @" struct S { int x, y; S(int x, int y) { this.x = x; this.y = y; } }"; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void FieldUnassignedInConstructor() { string program = @" struct S { int x, y; S(int x) { this.x = x; } }"; CreateCompilation(program) .VerifyDiagnostics( // (5,5): error CS0171: Field 'S.y' must be fully assigned before control is returned to the caller // S(int x) { this.x = x; } Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.y"), // (4,12): warning CS0169: The field 'S.y' is never used // int x, y; Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("S.y") ); } [WorkItem(543429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543429")] [Fact] public void ConstructorCannotComplete() { string program = @"using System; public struct S { int value; public S(int value) { throw new NotImplementedException(); } }"; CreateCompilation(program).VerifyDiagnostics( // (4,9): warning CS0169: The field 'S.value' is never used // int value; Diagnostic(ErrorCode.WRN_UnreferencedField, "value").WithArguments("S.value") ); } [Fact] public void AutoPropInitialization1() { string program = @" struct Program { public int X { get; private set; } public Program(int x) { } public static void Main(string[] args) { } }"; CreateCompilation(program) .VerifyDiagnostics( // (5,12): error CS0843: Backing field for automatically implemented property 'Program.X' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.X")); } [Fact] public void AutoPropInitialization2() { var text = @"struct S { public int P { get; set; } = 1; internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int i) {} }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int P { get; set; } = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "P").WithArguments("struct field initializers", "10.0").WithLocation(3, 16), // (5,20): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "R").WithArguments("struct field initializers", "10.0").WithLocation(5, 20)); comp = CreateCompilation(text); comp.VerifyDiagnostics(); } [Fact] public void AutoPropInitialization3() { var text = @"struct S { public int P { get; private set; } internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int p) { P = p; } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,20): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "R").WithArguments("struct field initializers", "10.0").WithLocation(5, 20)); comp = CreateCompilation(text); comp.VerifyDiagnostics(); } [Fact] public void AutoPropInitialization4() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; } S1 x2 { get; } public Program(int dummy) { x.i = 1; System.Console.WriteLine(x2.ii); } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (16,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i = 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(16, 9), // (16,9): error CS0170: Use of possibly unassigned field 'i' // x.i = 1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x.i").WithArguments("i").WithLocation(16, 9), // (17,34): error CS8079: Use of possibly unassigned auto-implemented property 'x2' // System.Console.WriteLine(x2.ii); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 34), // (14,12): error CS0843: Auto-implemented property 'Program.x' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x").WithLocation(14, 12), // (14,12): error CS0843: Auto-implemented property 'Program.x2' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x2").WithLocation(14, 12)); } [Fact] public void AutoPropInitialization5() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get; set;} public Program(int dummy) { x.i = 1; System.Console.WriteLine(x2.ii); } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (16,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i = 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(16, 9), // (16,9): error CS0170: Use of possibly unassigned field 'i' // x.i = 1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x.i").WithArguments("i").WithLocation(16, 9), // (17,34): error CS8079: Use of possibly unassigned auto-implemented property 'x2' // System.Console.WriteLine(x2.ii); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 34), // (14,12): error CS0843: Auto-implemented property 'Program.x' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x").WithLocation(14, 12), // (14,12): error CS0843: Auto-implemented property 'Program.x2' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x2").WithLocation(14, 12)); } [Fact] public void AutoPropInitialization6() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int dummy) { x = new S1(); x.i += 1; x2 = new S1(); x2.i += 1; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i += 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(17, 9), // (20,9): error CS1612: Cannot modify the return value of 'Program.x2' because it is not a variable // x2.i += 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x2").WithArguments("Program.x2").WithLocation(20, 9) ); } [Fact] public void AutoPropInitialization7() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int dummy) { this = default(Program); System.Action a = () => { this.x = new S1(); }; System.Action a2 = () => { this.x2 = new S1(); }; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (20,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // this.x = new S1(); Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(20, 13), // (25,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // this.x2 = new S1(); Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(25, 13), // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization7c() { var text = @" class Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program() { System.Action a = () => { this.x = new S1(); }; System.Action a2 = () => { this.x2 = new S1(); }; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (23,13): error CS0200: Property or indexer 'Program.x2' cannot be assigned to -- it is read only // this.x2 = new S1(); Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this.x2").WithArguments("Program.x2").WithLocation(23, 13), // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization8() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int arg) : this() { x2 = x; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization9() { var text = @" struct Program { struct S1 { } S1 x { get; set;} S1 x2 { get;} public Program(int arg) { x2 = x; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); // no errors since S1 is empty comp.VerifyDiagnostics( ); } [Fact] public void AutoPropInitialization10() { var text = @" struct Program { public struct S1 { public int x; } S1 x1 { get; set;} S1 x2 { get;} S1 x3; public Program(int arg) { Goo(out x1); Goo(ref x1); Goo(out x2); Goo(ref x2); Goo(out x3); Goo(ref x3); } public static void Goo(out S1 s) { s = default(S1); } public static void Goo1(ref S1 s) { s = default(S1); } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); // no errors since S1 is empty comp.VerifyDiagnostics( // (15,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(out x1); Diagnostic(ErrorCode.ERR_RefProperty, "x1").WithArguments("Program.x1").WithLocation(15, 17), // (16,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(ref x1); Diagnostic(ErrorCode.ERR_RefProperty, "x1").WithArguments("Program.x1").WithLocation(16, 17), // (17,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(out x2); Diagnostic(ErrorCode.ERR_RefProperty, "x2").WithArguments("Program.x2").WithLocation(17, 17), // (18,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(ref x2); Diagnostic(ErrorCode.ERR_RefProperty, "x2").WithArguments("Program.x2").WithLocation(18, 17), // (20,17): error CS1620: Argument 1 must be passed with the 'out' keyword // Goo(ref x3); Diagnostic(ErrorCode.ERR_BadArgRef, "x3").WithArguments("1", "out").WithLocation(20, 17), // (15,17): error CS8079: Use of automatically implemented property 'x1' whose backing field is possibly unassigned // Goo(out x1); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x1").WithArguments("x1").WithLocation(15, 17), // (16,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // Goo(ref x1); Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Goo").WithArguments("this").WithLocation(16, 9), // (17,17): error CS8079: Use of automatically implemented property 'x2' whose backing field is possibly unassigned // Goo(out x2); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 17), // (6,20): warning CS0649: Field 'Program.S1.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Program.S1.x", "0").WithLocation(6, 20) ); } [Fact] public void EmptyStructAlwaysAssigned() { string program = @" struct S { static S M() { S s; return s; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void DeeplyEmptyStructAlwaysAssigned() { string program = @" struct S { static S M() { S s; return s; } } struct T { S s1, s2, s3; static T M() { T t; return t; } }"; CreateCompilation(program) .VerifyDiagnostics( // (13,15): warning CS0169: The field 'T.s3' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s3").WithArguments("T.s3").WithLocation(13, 15), // (13,11): warning CS0169: The field 'T.s2' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s2").WithArguments("T.s2").WithLocation(13, 11), // (13,7): warning CS0169: The field 'T.s1' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s1").WithArguments("T.s1").WithLocation(13, 7) ); } [WorkItem(543466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543466")] [Fact] public void UnreferencedFieldWarningsMissingInEmit() { var comp = CreateCompilation(@" public class Class1 { int field1; }"); var bindingDiags = comp.GetDiagnostics().ToArray(); Assert.Equal(1, bindingDiags.Length); Assert.Equal(ErrorCode.WRN_UnreferencedField, (ErrorCode)bindingDiags[0].Code); var emitDiags = comp.Emit(new System.IO.MemoryStream()).Diagnostics.ToArray(); Assert.Equal(bindingDiags.Length, emitDiags.Length); Assert.Equal(bindingDiags[0], emitDiags[0]); } [Fact] public void DefiniteAssignGenericStruct() { string program = @" using System; struct C<T> { public int num; public int Goo1() { return this.num; } } class Test { static void Main(string[] args) { C<object> c; c.num = 1; bool verify = c.Goo1() == 1; Console.WriteLine(verify); } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [WorkItem(541268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541268")] [Fact] public void ChainToStructDefaultConstructor() { string program = @" using System; namespace Roslyn.Compilers.CSharp { class DecimalRewriter { private DecimalRewriter() { } private struct DecimalParts { public DecimalParts(decimal value) : this() { int[] bits = Decimal.GetBits(value); Low = bits[0]; } public int Low { get; private set; } } } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [WorkItem(541298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541298")] [WorkItem(541298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541298")] [Fact] public void SetStaticPropertyOnStruct() { string source = @" struct S { public static int p { get; internal set; } } class C { public static void Main() { S.p = 10; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPart() { string program = @" struct S { public int x; } class Program { public static void Main(string[] args) { S s = new S(); s.x = 12; } }"; CreateCompilation(program).VerifyDiagnostics(); } [Fact] public void ReferencingCycledStructures() { string program = @" public struct A { public static void Main() { S1 s1 = new S1(); S2 s2 = new S2(); s2.fld = new S3(); s2.fld.fld.fld.fld = new S2(); } } "; var c = CreateCompilation(program, new[] { TestReferences.SymbolsTests.CycledStructs }); c.VerifyDiagnostics( // (6,12): warning CS0219: The variable 's1' is assigned but its value is never used // S1 s1 = new S1(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s1").WithArguments("s1")); } [Fact] public void BigStruct() { string source = @" struct S<T> { T a, b, c, d, e, f, g, h; S(T t) { a = b = c = d = e = f = g = h = t; } static void M() { S<S<S<S<S<S<S<S<int>>>>>>>> x; x.a.a.a.a.a.a.a.a = 12; x.a.a.a.a.a.a.a.b = x.a.a.a.a.a.a.a.a; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(542901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542901")] public void DataFlowForStructFieldAssignment() { string program = @"struct S { public float X; public float Y; public float Z; void M() { if (3 < 3.4) { S s; if (s.X < 3) { s = GetS(); s.Z = 10f; } else { } } else { } } private static S GetS() { return new S(); } } "; CreateCompilation(program).VerifyDiagnostics( // (12,17): error CS0170: Use of possibly unassigned field 'X' // if (s.X < 3) Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.X").WithArguments("X"), // (3,18): warning CS0649: Field 'S.X' is never assigned to, and will always have its default value 0 // public float X; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("S.X", "0"), // (4,18): warning CS0649: Field 'S.Y' is never assigned to, and will always have its default value 0 // public float Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("S.Y", "0") ); } [Fact] [WorkItem(2470, "https://github.com/dotnet/roslyn/issues/2470")] public void NoFieldNeverAssignedWarning() { string program = @" using System.Threading.Tasks; internal struct TaskEvent<T> { private TaskCompletionSource<T> _tcs; public Task<T> Task { get { if (_tcs == null) _tcs = new TaskCompletionSource<T>(); return _tcs.Task; } } public void Invoke(T result) { if (_tcs != null) { TaskCompletionSource<T> localTcs = _tcs; _tcs = null; localTcs.SetResult(result); } } } public class OperationExecutor { private TaskEvent<float?> _nextValueEvent; // Field is never assigned warning // Start some async operation public Task<bool> StartOperation() { return null; } // Get progress or data during async operation public Task<float?> WaitNextValue() { return _nextValueEvent.Task; } // Called externally internal void OnNextValue(float? value) { _nextValueEvent.Invoke(value); } } "; CreateCompilationWithMscorlib45(program).VerifyEmitDiagnostics(); } #endregion [Fact, WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] public void FieldInAbstractClass_UnusedField() { var text = @" abstract class AbstractType { public int Kind; }"; CreateCompilation(text).VerifyDiagnostics( // (4,16): warning CS0649: Field 'AbstractType.Kind' is never assigned to, and will always have its default value 0 // public int Kind; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Kind").WithArguments("AbstractType.Kind", "0").WithLocation(4, 16)); } [Fact, WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] public void FieldInAbstractClass_FieldUsedInChildType() { var text = @" abstract class AbstractType { public int Kind; } class ChildType : AbstractType { public ChildType() { this.Kind = 1; } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] [WorkItem(545642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545642")] public void InitializerAndConstructorWithOutParameter() { string program = @"class Program { private int field = Goo(); static int Goo() { return 12; } public Program(out int x) { x = 13; } }"; CreateCompilation(program).VerifyDiagnostics(); } [Fact] [WorkItem(545875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545875")] public void TestSuppressUnreferencedVarAssgOnIntPtr() { var source = @" using System; public class Test { public static void Main() { IntPtr i1 = (IntPtr)0; IntPtr i2 = (IntPtr)10L; UIntPtr ui1 = (UIntPtr)0; UIntPtr ui2 = (UIntPtr)10L; IntPtr z = IntPtr.Zero; int ip1 = (int)z; long lp1 = (long)z; UIntPtr uz = UIntPtr.Zero; int ip2 = (int)uz; long lp2 = (long)uz; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(546183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546183")] public void TestUnassignedStructFieldsInPInvokePassByRefCase() { var source = @" using System; using System.Runtime.InteropServices; namespace ManagedDebuggingAssistants { internal class DebugMonitor { internal DebugMonitor() { SECURITY_ATTRIBUTES attributes = new SECURITY_ATTRIBUTES(); SECURITY_DESCRIPTOR descriptor = new SECURITY_DESCRIPTOR(); IntPtr pDescriptor = IntPtr.Zero; IntPtr pAttributes = IntPtr.Zero; attributes.nLength = Marshal.SizeOf(attributes); attributes.bInheritHandle = true; attributes.lpSecurityDescriptor = pDescriptor; if (!InitializeSecurityDescriptor(ref descriptor, 1 /*SECURITY_DESCRIPTOR_REVISION*/)) throw new ApplicationException(""InitializeSecurityDescriptor failed: "" + Marshal.GetLastWin32Error()); if (!SetSecurityDescriptorDacl(ref descriptor, true, IntPtr.Zero, false)) throw new ApplicationException(""SetSecurityDescriptorDacl failed: "" + Marshal.GetLastWin32Error()); Marshal.StructureToPtr(descriptor, pDescriptor, false); Marshal.StructureToPtr(attributes, pAttributes, false); } #region Interop definitions private struct SECURITY_DESCRIPTOR { internal byte Revision; internal byte Sbz1; internal short Control; internal IntPtr Owner; internal IntPtr Group; internal IntPtr Sacl; internal IntPtr Dacl; } private struct SECURITY_ATTRIBUTES { internal int nLength; internal IntPtr lpSecurityDescriptor; // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool bInheritHandle; #pragma warning restore 0414 } [DllImport(""advapi32.dll"", SetLastError = true)] private static extern bool InitializeSecurityDescriptor([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, int dwRevision); [DllImport(""advapi32.dll"", SetLastError = true)] private static extern bool SetSecurityDescriptorDacl([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, bool bDaclPresent, IntPtr pDacl, bool bDaclDefaulted); #endregion } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(546673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546673")] [Fact] public void TestBreakInsideNonLocalScopeBinder() { var source = @" public class C { public static void Main() { while (true) { unchecked { break; } } switch(0) { case 0: unchecked { break; } } while (true) { unsafe { break; } } switch(0) { case 0: unsafe { break; } } bool flag = false; while (!flag) { flag = true; unchecked { continue; } } flag = false; while (!flag) { flag = true; unsafe { continue; } } } }"; CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: ""); } [WorkItem(611904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611904")] [Fact] public void LabelAtTopLevelInsideLambda() { var source = @" class Program { delegate T SomeDelegate<T>(out bool f); static void Main(string[] args) { Test((out bool f) => { if (1.ToString() != null) goto l2; f = true; l1: if (1.ToString() != null) return 123; // <==== ERROR EXPECTED HERE f = true; if (1.ToString() != null) return 456; l2: goto l1; }); } static void Test<T>(SomeDelegate<T> f) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,17): error CS0177: The out parameter 'f' must be assigned to before control leaves the current method // return 123; // <==== ERROR EXPECTED HERE Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 123;").WithArguments("f") ); } [WorkItem(633927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633927")] [Fact] public void Xyzzy() { var source = @"class C { struct S { int x; S(dynamic y) { Goo(y, null); } } static void Goo(int y) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,13): error CS1501: No overload for method 'Goo' takes 2 arguments // Goo(y, null); Diagnostic(ErrorCode.ERR_BadArgCount, "Goo").WithArguments("Goo", "2"), // (6,9): error CS0171: Field 'C.S.x' must be fully assigned before control is returned to the caller // S(dynamic y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("C.S.x"), // (5,13): warning CS0169: The field 'C.S.x' is never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C.S.x") ); } [WorkItem(667368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667368")] [Fact] public void RegressionTest667368() { var source = @"using System.Collections.Generic; namespace ConsoleApplication1 { internal class Class1 { Dictionary<string, int> _dict = new Dictionary<string, int>(); public Class1() { } public int? GetCode(dynamic value) { int val; if (value != null && _dict.TryGetValue(value, out val)) return val; return null; } } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,24): error CS0165: Use of unassigned local variable 'val' // return val; Diagnostic(ErrorCode.ERR_UseDefViolation, "val").WithArguments("val") ); } [WorkItem(690921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690921")] [Fact] public void RegressionTest690921() { var source = @"using System.Collections.Generic; namespace ConsoleApplication1 { internal class Class1 { Dictionary<string, int> _dict = new Dictionary<string, int>(); public Class1() { } public static string GetOutBoxItemId(string itemName, string uniqueIdKey, string listUrl, Dictionary<string, dynamic> myList = null, bool useDefaultCredentials = false) { string uniqueId = null; dynamic myItemName; if (myList != null && myList.TryGetValue(""DisplayName"", out myItemName) && myItemName == itemName) { } return uniqueId; } public static void Main() { } } } "; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(715338, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715338")] [Fact] public void RegressionTest715338() { var source = @"using System; using System.Collections.Generic; static class Program { static void Add(this IList<int> source, string key, int value) { } static void View(Action<string, int> adder) { } static readonly IList<int> myInts = null; static void Main() { View(myInts.Add); } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(808567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808567")] [Fact] public void RegressionTest808567() { var source = @"class Base { public Base(out int x, System.Func<int> u) { x = 0; } } class Derived2 : Base { Derived2(out int p1) : base(out p1, ()=>p1) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (11,28): error CS1628: Cannot use ref or out parameter 'p1' inside an anonymous method, lambda expression, or query expression // : base(out p1, ()=>p1) Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "p1").WithArguments("p1"), // (11,20): error CS0269: Use of unassigned out parameter 'p1' // : base(out p1, ()=>p1) Diagnostic(ErrorCode.ERR_UseDefViolationOut, "p1").WithArguments("p1") ); } [WorkItem(949324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949324")] [Fact] public void RegressionTest949324() { var source = @"struct Derived { Derived(int x) { } Derived(long x) : this(p2) // error CS0188: The 'this' object cannot be used before all of its fields are assigned to { this = new Derived(); } private int x; }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (3,5): error CS0171: Field 'Derived.x' must be fully assigned before control is returned to the caller // Derived(int x) { } Diagnostic(ErrorCode.ERR_UnassignedThis, "Derived").WithArguments("Derived.x").WithLocation(3, 5), // (4,28): error CS0103: The name 'p2' does not exist in the current context // Derived(long x) : this(p2) // error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_NameNotInContext, "p2").WithArguments("p2").WithLocation(4, 28), // (8,17): warning CS0169: The field 'Derived.x' is never used // private int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("Derived.x").WithLocation(8, 17) ); } [WorkItem(612, "https://github.com/dotnet/roslyn/issues/612")] [Fact] public void CascadedUnreachableCode() { var source = @"class Program { public static void Main() { string k; switch (1) { case 1: } string s = k; } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS8070: Control cannot fall out of switch from final case label ('case 1:') // case 1: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 1:").WithArguments("case 1:").WithLocation(8, 9), // (10,20): error CS0165: Use of unassigned local variable 'k' // string s = k; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(10, 20) ); } [WorkItem(9581, "https://github.com/dotnet/roslyn/issues/9581")] [Fact] public void UsingSelfAssignment() { var source = @"class Program { static void Main() { using (System.IDisposable x = x) { } } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,39): error CS0165: Use of unassigned local variable 'x' // using (System.IDisposable x = x) Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(5, 39) ); } [Fact] public void UsingAssignment() { var source = @"class Program { static void Main() { using (System.IDisposable x = null) { System.Console.WriteLine(x.ToString()); } using (System.IDisposable x = null, y = x) { System.Console.WriteLine(y.ToString()); } } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void RangeDefiniteAssignmentOrder() { CreateCompilationWithIndexAndRange(@" class C { void M() { int x; var r = (x=0)..(x+1); int y; r = (y+1)..(y=0); } }").VerifyDiagnostics( // (9,14): error CS0165: Use of unassigned local variable 'y' // r = (y+1)..(y=0); Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(9, 14)); } [Fact] public void FieldAssignedInLambdaOnly() { var source = @"using System; struct S { private object F; private object G; public S(object x, object y) { Action a = () => { F = x; }; G = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS0171: Field 'S.F' must be fully assigned before control is returned to the caller // public S(object x, object y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.F").WithLocation(6, 12), // (8,28): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { F = x; }; Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "F").WithLocation(8, 28)); } [Fact] public void FieldAssignedInLocalFunctionOnly() { var source = @"struct S { private object F; private object G; public S(object x, object y) { void f() { F = x; } G = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,12): error CS0171: Field 'S.F' must be fully assigned before control is returned to the caller // public S(object x, object y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.F").WithLocation(5, 12), // (7,14): warning CS8321: The local function 'f' is declared but never used // void f() { F = x; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(7, 14), // (7,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void f() { F = x; } Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "F").WithLocation(7, 20)); } [Fact] [WorkItem(1243877, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1243877")] public void WorkItem1243877() { string program = @" static class C { static void Main() { Test(out var x, x); } static void Test(out Empty x, object y) => throw null; } struct Empty { } "; CreateCompilation(program).VerifyDiagnostics( // (6,25): error CS8196: Reference to an implicitly-typed out variable 'x' is not permitted in the same argument list. // Test(out var x, x); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x").WithArguments("x").WithLocation(6, 25) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class FlowDiagnosticTests : FlowTestBase { [Fact] public void TestBug12350() { // We suppress the "local variable is only written" warning if the // variable is assigned a non-constant value. string program = @" class Program { static int X() { return 1; } static void M() { int i1 = 123; // 0219 int i2 = X(); // no warning int? i3 = 123; // 0219 int? i4 = null; // 0219 int? i5 = X(); // no warning int i6 = default(int); // 0219 int? i7 = default(int?); // 0219 int? i8 = new int?(); // 0219 int i9 = new int(); // 0219 } }"; CreateCompilation(program).VerifyDiagnostics( // (7,13): warning CS0219: The variable 'i1' is assigned but its value is never used // int i1 = 123; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1"), // (9,14): warning CS0219: The variable 'i3' is assigned but its value is never used // int? i3 = 123; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i3").WithArguments("i3"), // (10,14): warning CS0219: The variable 'i4' is assigned but its value is never used // int? i4 = null; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i4").WithArguments("i4"), // (12,13): warning CS0219: The variable 'i6' is assigned but its value is never used // int i6 = default(int); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i6").WithArguments("i6"), // (13,14): warning CS0219: The variable 'i7' is assigned but its value is never used // int? i7 = default(int?); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i7").WithArguments("i7"), // (14,14): warning CS0219: The variable 'i8' is assigned but its value is never used // int? i8 = new int?(); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i8").WithArguments("i8"), // (15,13): warning CS0219: The variable 'i9' is assigned but its value is never used // int i9 = new int(); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i9").WithArguments("i9")); } [Fact] public void Test1() { string program = @" namespace ConsoleApplication1 { class Program { public static void F(int z) { int x; if (z == 2) { int y = x; x = y; // use of unassigned local variable 'x' } else { int y = x; x = y; // diagnostic suppressed here } } } }"; CreateCompilation(program).VerifyDiagnostics( // (11,25): error CS0165: Use of unassigned local variable 'x' // int y = x; x = y; // use of unassigned local variable 'x' Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x") ); } [Fact] public void Test2() { //x is "assigned when true" after "false" //Therefore x is "assigned" before "z == 1" (5.3.3.24) //Therefore x is "assigned" after "z == 1" (5.3.3.20) //Therefore x is "assigned when true" after "(false && z == 1)" (5.3.3.24) //Since the condition of the ?: expression is the constant true, the state of x after the ?: expression is the same as the state of x after the consequence (5.3.3.28) //Since the state of x after the consequence is "assigned when true", the state of x after the ?: expression is "assigned when true" (5.3.3.28) //Since the state of x after the if's condition is "assigned when true", x is assigned in the then block (5.3.3.5) //Therefore, there should be no error. string program = @" namespace ConsoleApplication1 { class Program { void F(int z) { int x; if (true ? (false && z == 1) : true) x = x + 1; // Dev10 complains x not assigned. } } }"; var comp = CreateCompilation(program); var errs = this.FlowDiagnostics(comp); Assert.Equal(0, errs.Count()); } [Fact] public void Test3() { string program = @" class Program { int F(int z) { } }"; var comp = CreateCompilation(program); var errs = this.FlowDiagnostics(comp); Assert.Equal(1, errs.Count()); } [Fact] public void Test4() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" class Program { void F() { if (false) { int x; // warning: unreachable code x = x + 1; // no error: x assigned when unreachable } } }"; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(1, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [Fact] public void Test5() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" class A { static void F() { goto L2; goto L1; // unreachable code detected int x; L1: ; // Roslyn: extrs warning CS0162 -unreachable code x = x + 1; // no definite assignment problem in unreachable code L2: ; } } "; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(2, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [WorkItem(537918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537918")] [Fact] public void AssertForInvalidBreak() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" public class Test { public static int Main() { int ret = 1; break; // Assert here return (ret); } } "; var comp = CreateCompilation(program); comp.GetMethodBodyDiagnostics().Verify( // (7,9): error CS0139: No enclosing loop out of which to break or continue // break; // Assert here Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;")); } [WorkItem(538064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538064")] [Fact] public void IfFalse() { string program = @" using System; class Program { static void Main() { if (false) { } } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538067")] [Fact] public void WhileConstEqualsConst() { string program = @" using System; class Program { bool goo() { const bool b = true; while (b == b) { return b; } } static void Main() { } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538175")] [Fact] public void BreakWithoutTarget() { string program = @"public class Test { public static void Main() { if (true) break; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void OutCausesAssignment() { string program = @"class Program { void F(out int x) { G(out x); } void G(out int x) { x = 1; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void OutNotAssigned01() { string program = @"class Program { bool b; void F(out int x) { if (b) return; } }"; var comp = CreateCompilation(program); Assert.Equal(2, this.FlowDiagnostics(comp).Count()); } [WorkItem(539374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539374")] [Fact] public void OutAssignedAfterCall01() { string program = @"class Program { void F(out int x, int y) { x = y; } void G() { int x; F(out x, x); } }"; var comp = CreateCompilation(program); Assert.Equal(1, this.FlowDiagnostics(comp).Count()); } [WorkItem(538067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538067")] [Fact] public void WhileConstEqualsConst2() { string program = @" using System; class Program { bool goo() { const bool b = true; while (b == b) { return b; } return b; // Should detect this line as unreachable code. } static void Main() { } }"; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(1, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [WorkItem(538072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538072")] [Fact] public void UnusedLocal() { string program = @" using System; class Program { int x; int y; int z; static void Main() { int a; const bool b = true; } void goo() { y = 2; Console.WriteLine(z); } }"; var comp = CreateCompilation(program); int[] count = new int[4]; Dictionary<int, int> warnings = new Dictionary<int, int>(); foreach (var e in this.FlowDiagnostics(comp)) { count[(int)e.Severity]++; if (!warnings.ContainsKey(e.Code)) warnings[e.Code] = 0; warnings[e.Code] += 1; } Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); // See bug 3562 - field level flow analysis warnings CS0169, CS0414 and CS0649 are out of scope for M2. // TODO: Fix this test once CS0169, CS0414 and CS0649 are implemented. // Assert.Equal(5, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(2, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(1, warnings[168]); Assert.Equal(1, warnings[219]); // See bug 3562 - field level flow analysis warnings CS0169, CS0414 and CS0649 are out of scope for M2. // TODO: Fix this test once CS0169, CS0414 and CS0649 are implemented. // Assert.Equal(1, warnings[169]); // Assert.Equal(1, warnings[414]); // Assert.Equal(1, warnings[649]); } [WorkItem(538384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538384")] [Fact] public void UnusedLocalConstants() { string program = @" using System; class Program { static void Main() { const string CONST1 = ""hello""; // Should not report CS0219 Console.WriteLine(CONST1 != ""hello""); int i = 1; const long CONST2 = 1; const uint CONST3 = 1; // Should not report CS0219 while (CONST2 < CONST3 - i) { if (CONST3 < CONST3 - i) continue; } } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538385")] [Fact] public void UnusedLocalReferenceTypedVariables() { string program = @" using System; class Program { static void Main() { object o = 1; // Should not report CS0219 Test c = new Test(); // Should not report CS0219 c = new Program(); string s = string.Empty; // Should not report CS0219 s = null; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538386")] [Fact] public void UnusedLocalValueTypedVariables() { string program = @" using System; class Program { static void Main() { } public void Repro2(params int[] x) { int i = x[0]; // Should not report CS0219 byte b1 = 1; byte b11 = b1; // Should not report CS0219 } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void RefParameter01() { string program = @" class Program { public static void Main(string[] args) { int i; F(ref i); // use of unassigned local variable 'i' } static void F(ref int i) { } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void OutParameter01() { string program = @" class Program { public static void Main(string[] args) { int i; F(out i); int j = i; } static void F(out int i) { i = 1; } }"; var comp = CreateCompilation(program); Assert.Empty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void Goto01() { string program = @" using System; class Program { public void M(bool b) { if (b) goto label; int i; i = 3; i = i + 1; label: int j = i; // i not definitely assigned } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaParameters() { string program = @" using System; class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { Func fnc = (ref int arg, int arg2) => { arg = arg; }; } }"; var comp = CreateCompilation(program); Assert.Empty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaMightNotBeInvoked() { string program = @" class Program { delegate void Func(); static void Main(string[] args) { int i; Func query = () => { i = 12; }; int j = i; } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaMustAssignOutParameters() { string program = @" class Program { delegate void Func(out int x); static void Main(string[] args) { Func query = (out int x) => { }; } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact, WorkItem(528052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528052")] public void InnerVariablesAreNotDefinitelyAssignedInBeginningOfLambdaBody() { string program = @" using System; class Program { static void Main() { return; Action f = () => { int y = y; }; } }"; CreateCompilation(program).VerifyDiagnostics( // (9,9): warning CS0162: Unreachable code detected // Action f = () => { int y = y; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Action"), // (9,36): error CS0165: Use of unassigned local variable 'y' // Action f = () => { int y = y; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y") ); } [WorkItem(540139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540139")] [Fact] public void DelegateCreationReceiverIsRead() { string program = @" using System; class Program { static void Main() { Action a; Func<string> b = new Func<string>(a.ToString); } } "; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [WorkItem(540405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540405")] [Fact] public void ErrorInFieldInitializerLambda() { string program = @" using System; class Program { static Func<string> x = () => { string s; return s; }; static void Main() { } } "; CreateCompilation(program).VerifyDiagnostics( // (6,54): error CS0165: Use of unassigned local variable 's' // static Func<string> x = () => { string s; return s; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s") ); } [WorkItem(541389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541389")] [Fact] public void IterationWithEmptyBody() { string program = @" public class A { public static void Main(string[] args) { for (int i = 0; i < 10; i++) ; foreach (var v in args); int len = args.Length; while (len-- > 0); } }"; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(541389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541389")] [Fact] public void SelectionWithEmptyBody() { string program = @" public class A { public static void Main(string[] args) { int len = args.Length; if (len++ < 9) ; else ; } }"; CreateCompilation(program).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";")); } [WorkItem(542146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542146")] [Fact] public void FieldlikeEvent() { string program = @"public delegate void D(); public struct S { public event D Ev; public S(D d) { Ev = null; Ev += d; } }"; CreateCompilation(program).VerifyDiagnostics( // (4,20): warning CS0414: The field 'S.Ev' is assigned but its value is never used // public event D Ev; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Ev").WithArguments("S.Ev")); } [WorkItem(542187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542187")] [Fact] public void GotoFromTry() { string program = @"class Test { static void F(int x) { } static void Main() { int a; try { a = 1; goto L1; } finally { } L1: F(a); } }"; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(542154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542154")] [Fact] public void UnreachableThrow() { string program = @"public class C { static void Main() { return; throw Goo(); } static System.Exception Goo() { System.Console.WriteLine(""Hello""); return null; } } "; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(542585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542585")] [Fact] public void Bug9870() { string program = @" struct S<T> { T x; static void Goo() { x.x = 1; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'S<T>.x' // x.x = 1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x").WithArguments("S<T>.x") ); } [WorkItem(542597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542597")] [Fact] public void LambdaEntryPointIsReachable() { string program = @"class Program { static void Main(string[] args) { int i; return; System.Action a = () => { int j = i + j; }; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // unreachable statement // (7,23): warning CS0162: Unreachable code detected // System.Action a = () => Diagnostic(ErrorCode.WRN_UnreachableCode, "System"), // (9,25): error CS0165: Use of unassigned local variable 'j' // int j = i + j; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j") ); } [WorkItem(542597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542597")] [Fact] public void LambdaInUnimplementedPartial() { string program = @"using System; partial class C { static partial void Goo(Action a); static void Main() { Goo(() => { int x, y = x; }); } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (9,32): error CS0165: Use of unassigned local variable 'x' // Goo(() => { int x, y = x; }); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x") ); } [WorkItem(541887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541887")] [Fact] public void CascadedDiagnostics01() { string program = @" class Program { static void Main(string[] args) { var s = goo<,int>(123); } public static int goo<T>(int i) { return 1; } }"; var comp = CreateCompilation(program); var parseErrors = comp.SyntaxTrees[0].GetDiagnostics(); var errors = comp.GetDiagnostics(); Assert.Equal(parseErrors.Count(), errors.Count()); } [Fact] public void UnassignedInInitializer() { string program = @"class C { System.Action a = () => { int i; int j = i; }; }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (3,46): error CS0165: Use of unassigned local variable 'i' // System.Action a = () => { int i; int j = i; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i") ); } [WorkItem(543343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543343")] [Fact] public void ConstInSwitch() { string program = @"class Program { static void Main(string[] args) { switch (args.Length) { case 0: const int N = 3; break; case 1: int M = N; break; } } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (11,21): warning CS0219: The variable 'M' is assigned but its value is never used // int M = N; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "M").WithArguments("M") ); } #region "Struct" [Fact] public void CycleWithInitialization() { string program = @" public struct A { A a = new A(); // CS8036 public static void Main() { A a = new A(); } } "; CreateCompilation(program, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (4,7): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a").WithArguments("struct field initializers", "10.0").WithLocation(4, 7), // (4,7): error CS0523: Struct member 'A.a' of type 'A' causes a cycle in the struct layout // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "a").WithArguments("A.a", "A").WithLocation(4, 7), // (7,11): warning CS0219: The variable 'a' is assigned but its value is never used // A a = new A(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(7, 11), // (4,7): warning CS0414: The field 'A.a' is assigned but its value is never used // A a = new A(); // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("A.a").WithLocation(4, 7)); } [WorkItem(542356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542356")] [Fact] public void StaticMemberExplosion() { string program = @" struct A<T> { static A<A<T>> x; } struct B<T> { static A<B<T>> x; } struct C<T> { static D<T> x; } struct D<T> { static C<D<T>> x; } "; CreateCompilation(program) .VerifyDiagnostics( // (14,17): error CS0523: Struct member 'C<T>.x' of type 'D<T>' causes a cycle in the struct layout // static D<T> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("C<T>.x", "D<T>").WithLocation(14, 17), // (18,20): error CS0523: Struct member 'D<T>.x' of type 'C<D<T>>' causes a cycle in the struct layout // static C<D<T>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("D<T>.x", "C<D<T>>").WithLocation(18, 20), // (4,20): error CS0523: Struct member 'A<T>.x' of type 'A<A<T>>' causes a cycle in the struct layout // static A<A<T>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("A<T>.x", "A<A<T>>").WithLocation(4, 20), // (9,20): warning CS0169: The field 'B<T>.x' is never used // static A<B<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("B<T>.x").WithLocation(9, 20), // (4,20): warning CS0169: The field 'A<T>.x' is never used // static A<A<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("A<T>.x").WithLocation(4, 20), // (18,20): warning CS0169: The field 'D<T>.x' is never used // static C<D<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("D<T>.x").WithLocation(18, 20), // (14,17): warning CS0169: The field 'C<T>.x' is never used // static D<T> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C<T>.x").WithLocation(14, 17) ); } [Fact] public void StaticSequential() { string program = @" partial struct S { public static int x; } partial struct S { public static int y; }"; CreateCompilation(program) .VerifyDiagnostics( // (4,23): warning CS0649: Field 'S.x' is never assigned to, and will always have its default value 0 // public static int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S.x", "0"), // (9,23): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public static int y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [WorkItem(542567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542567")] [Fact] public void ImplicitFieldSequential() { string program = @"partial struct S1 { public int x; } partial struct S1 { public int y { get; set; } } partial struct S2 { public int x; } delegate void D(); partial struct S2 { public event D y; }"; CreateCompilation(program) .VerifyDiagnostics( // (1,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'S1'. To specify an ordering, all instance fields must be in the same declaration. // partial struct S1 Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "S1").WithArguments("S1"), // (11,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'S2'. To specify an ordering, all instance fields must be in the same declaration. // partial struct S2 Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "S2").WithArguments("S2"), // (3,16): warning CS0649: Field 'S1.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S1.x", "0"), // (13,16): warning CS0649: Field 'S2.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S2.x", "0"), // (19,20): warning CS0067: The event 'S2.y' is never used // public event D y; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "y").WithArguments("S2.y") ); } [Fact] public void StaticInitializer() { string program = @" public struct A { static System.Func<int> d = () => { int j; return j * 9000; }; public static void Main() { } } "; CreateCompilation(program) .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j") ); } [Fact] public void AllPiecesAssigned() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s; s.x = args.Length; s.y = args.Length; S t = s; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void OnePieceMissing() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s; s.x = args.Length; S t = s; } } "; CreateCompilation(program) .VerifyDiagnostics( // (12,15): error CS0165: Use of unassigned local variable 's' // S t = s; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s"), // (4,19): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [Fact] public void OnePieceOnOnePath() { string program = @" struct S { public int x, y; } class Program { public void F(S s) { S s2; if (s.x == 3) s2 = s; else s2.x = s.x; int x = s2.x; } } "; CreateCompilation(program) .VerifyDiagnostics( // (4,19): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [Fact] public void DefaultConstructor() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s = new S(); s.x = s.y = s.x; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void FieldAssignedInConstructor() { string program = @" struct S { int x, y; S(int x, int y) { this.x = x; this.y = y; } }"; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void FieldUnassignedInConstructor() { string program = @" struct S { int x, y; S(int x) { this.x = x; } }"; CreateCompilation(program) .VerifyDiagnostics( // (5,5): error CS0171: Field 'S.y' must be fully assigned before control is returned to the caller // S(int x) { this.x = x; } Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.y"), // (4,12): warning CS0169: The field 'S.y' is never used // int x, y; Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("S.y") ); } [WorkItem(543429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543429")] [Fact] public void ConstructorCannotComplete() { string program = @"using System; public struct S { int value; public S(int value) { throw new NotImplementedException(); } }"; CreateCompilation(program).VerifyDiagnostics( // (4,9): warning CS0169: The field 'S.value' is never used // int value; Diagnostic(ErrorCode.WRN_UnreferencedField, "value").WithArguments("S.value") ); } [Fact] public void AutoPropInitialization1() { string program = @" struct Program { public int X { get; private set; } public Program(int x) { } public static void Main(string[] args) { } }"; CreateCompilation(program) .VerifyDiagnostics( // (5,12): error CS0843: Backing field for automatically implemented property 'Program.X' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.X")); } [Fact] public void AutoPropInitialization2() { var text = @"struct S { public int P { get; set; } = 1; internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int i) {} }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int P { get; set; } = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "P").WithArguments("struct field initializers", "10.0").WithLocation(3, 16), // (5,20): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "R").WithArguments("struct field initializers", "10.0").WithLocation(5, 20)); comp = CreateCompilation(text); comp.VerifyDiagnostics(); } [Fact] public void AutoPropInitialization3() { var text = @"struct S { public int P { get; private set; } internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int p) { P = p; } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,20): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "R").WithArguments("struct field initializers", "10.0").WithLocation(5, 20)); comp = CreateCompilation(text); comp.VerifyDiagnostics(); } [Fact] public void AutoPropInitialization4() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; } S1 x2 { get; } public Program(int dummy) { x.i = 1; System.Console.WriteLine(x2.ii); } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (16,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i = 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(16, 9), // (16,9): error CS0170: Use of possibly unassigned field 'i' // x.i = 1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x.i").WithArguments("i").WithLocation(16, 9), // (17,34): error CS8079: Use of possibly unassigned auto-implemented property 'x2' // System.Console.WriteLine(x2.ii); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 34), // (14,12): error CS0843: Auto-implemented property 'Program.x' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x").WithLocation(14, 12), // (14,12): error CS0843: Auto-implemented property 'Program.x2' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x2").WithLocation(14, 12)); } [Fact] public void AutoPropInitialization5() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get; set;} public Program(int dummy) { x.i = 1; System.Console.WriteLine(x2.ii); } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (16,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i = 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(16, 9), // (16,9): error CS0170: Use of possibly unassigned field 'i' // x.i = 1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x.i").WithArguments("i").WithLocation(16, 9), // (17,34): error CS8079: Use of possibly unassigned auto-implemented property 'x2' // System.Console.WriteLine(x2.ii); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 34), // (14,12): error CS0843: Auto-implemented property 'Program.x' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x").WithLocation(14, 12), // (14,12): error CS0843: Auto-implemented property 'Program.x2' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x2").WithLocation(14, 12)); } [Fact] public void AutoPropInitialization6() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int dummy) { x = new S1(); x.i += 1; x2 = new S1(); x2.i += 1; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i += 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(17, 9), // (20,9): error CS1612: Cannot modify the return value of 'Program.x2' because it is not a variable // x2.i += 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x2").WithArguments("Program.x2").WithLocation(20, 9) ); } [Fact] public void AutoPropInitialization7() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int dummy) { this = default(Program); System.Action a = () => { this.x = new S1(); }; System.Action a2 = () => { this.x2 = new S1(); }; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (20,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // this.x = new S1(); Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(20, 13), // (25,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // this.x2 = new S1(); Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(25, 13), // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization7c() { var text = @" class Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program() { System.Action a = () => { this.x = new S1(); }; System.Action a2 = () => { this.x2 = new S1(); }; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (23,13): error CS0200: Property or indexer 'Program.x2' cannot be assigned to -- it is read only // this.x2 = new S1(); Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this.x2").WithArguments("Program.x2").WithLocation(23, 13), // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization8() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int arg) : this() { x2 = x; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization9() { var text = @" struct Program { struct S1 { } S1 x { get; set;} S1 x2 { get;} public Program(int arg) { x2 = x; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); // no errors since S1 is empty comp.VerifyDiagnostics( ); } [Fact] public void AutoPropInitialization10() { var text = @" struct Program { public struct S1 { public int x; } S1 x1 { get; set;} S1 x2 { get;} S1 x3; public Program(int arg) { Goo(out x1); Goo(ref x1); Goo(out x2); Goo(ref x2); Goo(out x3); Goo(ref x3); } public static void Goo(out S1 s) { s = default(S1); } public static void Goo1(ref S1 s) { s = default(S1); } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); // no errors since S1 is empty comp.VerifyDiagnostics( // (15,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(out x1); Diagnostic(ErrorCode.ERR_RefProperty, "x1").WithArguments("Program.x1").WithLocation(15, 17), // (16,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(ref x1); Diagnostic(ErrorCode.ERR_RefProperty, "x1").WithArguments("Program.x1").WithLocation(16, 17), // (17,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(out x2); Diagnostic(ErrorCode.ERR_RefProperty, "x2").WithArguments("Program.x2").WithLocation(17, 17), // (18,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(ref x2); Diagnostic(ErrorCode.ERR_RefProperty, "x2").WithArguments("Program.x2").WithLocation(18, 17), // (20,17): error CS1620: Argument 1 must be passed with the 'out' keyword // Goo(ref x3); Diagnostic(ErrorCode.ERR_BadArgRef, "x3").WithArguments("1", "out").WithLocation(20, 17), // (15,17): error CS8079: Use of automatically implemented property 'x1' whose backing field is possibly unassigned // Goo(out x1); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x1").WithArguments("x1").WithLocation(15, 17), // (16,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // Goo(ref x1); Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Goo").WithArguments("this").WithLocation(16, 9), // (17,17): error CS8079: Use of automatically implemented property 'x2' whose backing field is possibly unassigned // Goo(out x2); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 17), // (6,20): warning CS0649: Field 'Program.S1.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Program.S1.x", "0").WithLocation(6, 20) ); } [Fact] public void EmptyStructAlwaysAssigned() { string program = @" struct S { static S M() { S s; return s; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void DeeplyEmptyStructAlwaysAssigned() { string program = @" struct S { static S M() { S s; return s; } } struct T { S s1, s2, s3; static T M() { T t; return t; } }"; CreateCompilation(program) .VerifyDiagnostics( // (13,15): warning CS0169: The field 'T.s3' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s3").WithArguments("T.s3").WithLocation(13, 15), // (13,11): warning CS0169: The field 'T.s2' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s2").WithArguments("T.s2").WithLocation(13, 11), // (13,7): warning CS0169: The field 'T.s1' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s1").WithArguments("T.s1").WithLocation(13, 7) ); } [WorkItem(543466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543466")] [Fact] public void UnreferencedFieldWarningsMissingInEmit() { var comp = CreateCompilation(@" public class Class1 { int field1; }"); var bindingDiags = comp.GetDiagnostics().ToArray(); Assert.Equal(1, bindingDiags.Length); Assert.Equal(ErrorCode.WRN_UnreferencedField, (ErrorCode)bindingDiags[0].Code); var emitDiags = comp.Emit(new System.IO.MemoryStream()).Diagnostics.ToArray(); Assert.Equal(bindingDiags.Length, emitDiags.Length); Assert.Equal(bindingDiags[0], emitDiags[0]); } [Fact] public void DefiniteAssignGenericStruct() { string program = @" using System; struct C<T> { public int num; public int Goo1() { return this.num; } } class Test { static void Main(string[] args) { C<object> c; c.num = 1; bool verify = c.Goo1() == 1; Console.WriteLine(verify); } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [WorkItem(541268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541268")] [Fact] public void ChainToStructDefaultConstructor() { string program = @" using System; namespace Roslyn.Compilers.CSharp { class DecimalRewriter { private DecimalRewriter() { } private struct DecimalParts { public DecimalParts(decimal value) : this() { int[] bits = Decimal.GetBits(value); Low = bits[0]; } public int Low { get; private set; } } } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [WorkItem(541298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541298")] [WorkItem(541298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541298")] [Fact] public void SetStaticPropertyOnStruct() { string source = @" struct S { public static int p { get; internal set; } } class C { public static void Main() { S.p = 10; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPart() { string program = @" struct S { public int x; } class Program { public static void Main(string[] args) { S s = new S(); s.x = 12; } }"; CreateCompilation(program).VerifyDiagnostics(); } [Fact] public void ReferencingCycledStructures() { string program = @" public struct A { public static void Main() { S1 s1 = new S1(); S2 s2 = new S2(); s2.fld = new S3(); s2.fld.fld.fld.fld = new S2(); } } "; var c = CreateCompilation(program, new[] { TestReferences.SymbolsTests.CycledStructs }); c.VerifyDiagnostics( // (6,12): warning CS0219: The variable 's1' is assigned but its value is never used // S1 s1 = new S1(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s1").WithArguments("s1")); } [Fact] public void BigStruct() { string source = @" struct S<T> { T a, b, c, d, e, f, g, h; S(T t) { a = b = c = d = e = f = g = h = t; } static void M() { S<S<S<S<S<S<S<S<int>>>>>>>> x; x.a.a.a.a.a.a.a.a = 12; x.a.a.a.a.a.a.a.b = x.a.a.a.a.a.a.a.a; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(542901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542901")] public void DataFlowForStructFieldAssignment() { string program = @"struct S { public float X; public float Y; public float Z; void M() { if (3 < 3.4) { S s; if (s.X < 3) { s = GetS(); s.Z = 10f; } else { } } else { } } private static S GetS() { return new S(); } } "; CreateCompilation(program).VerifyDiagnostics( // (12,17): error CS0170: Use of possibly unassigned field 'X' // if (s.X < 3) Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.X").WithArguments("X"), // (3,18): warning CS0649: Field 'S.X' is never assigned to, and will always have its default value 0 // public float X; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("S.X", "0"), // (4,18): warning CS0649: Field 'S.Y' is never assigned to, and will always have its default value 0 // public float Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("S.Y", "0") ); } [Fact] [WorkItem(2470, "https://github.com/dotnet/roslyn/issues/2470")] public void NoFieldNeverAssignedWarning() { string program = @" using System.Threading.Tasks; internal struct TaskEvent<T> { private TaskCompletionSource<T> _tcs; public Task<T> Task { get { if (_tcs == null) _tcs = new TaskCompletionSource<T>(); return _tcs.Task; } } public void Invoke(T result) { if (_tcs != null) { TaskCompletionSource<T> localTcs = _tcs; _tcs = null; localTcs.SetResult(result); } } } public class OperationExecutor { private TaskEvent<float?> _nextValueEvent; // Field is never assigned warning // Start some async operation public Task<bool> StartOperation() { return null; } // Get progress or data during async operation public Task<float?> WaitNextValue() { return _nextValueEvent.Task; } // Called externally internal void OnNextValue(float? value) { _nextValueEvent.Invoke(value); } } "; CreateCompilationWithMscorlib45(program).VerifyEmitDiagnostics(); } #endregion [Fact, WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] public void FieldInAbstractClass_UnusedField() { var text = @" abstract class AbstractType { public int Kind; }"; CreateCompilation(text).VerifyDiagnostics( // (4,16): warning CS0649: Field 'AbstractType.Kind' is never assigned to, and will always have its default value 0 // public int Kind; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Kind").WithArguments("AbstractType.Kind", "0").WithLocation(4, 16)); } [Fact, WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] public void FieldInAbstractClass_FieldUsedInChildType() { var text = @" abstract class AbstractType { public int Kind; } class ChildType : AbstractType { public ChildType() { this.Kind = 1; } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] [WorkItem(545642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545642")] public void InitializerAndConstructorWithOutParameter() { string program = @"class Program { private int field = Goo(); static int Goo() { return 12; } public Program(out int x) { x = 13; } }"; CreateCompilation(program).VerifyDiagnostics(); } [Fact] [WorkItem(545875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545875")] public void TestSuppressUnreferencedVarAssgOnIntPtr() { var source = @" using System; public class Test { public static void Main() { IntPtr i1 = (IntPtr)0; IntPtr i2 = (IntPtr)10L; UIntPtr ui1 = (UIntPtr)0; UIntPtr ui2 = (UIntPtr)10L; IntPtr z = IntPtr.Zero; int ip1 = (int)z; long lp1 = (long)z; UIntPtr uz = UIntPtr.Zero; int ip2 = (int)uz; long lp2 = (long)uz; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(546183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546183")] public void TestUnassignedStructFieldsInPInvokePassByRefCase() { var source = @" using System; using System.Runtime.InteropServices; namespace ManagedDebuggingAssistants { internal class DebugMonitor { internal DebugMonitor() { SECURITY_ATTRIBUTES attributes = new SECURITY_ATTRIBUTES(); SECURITY_DESCRIPTOR descriptor = new SECURITY_DESCRIPTOR(); IntPtr pDescriptor = IntPtr.Zero; IntPtr pAttributes = IntPtr.Zero; attributes.nLength = Marshal.SizeOf(attributes); attributes.bInheritHandle = true; attributes.lpSecurityDescriptor = pDescriptor; if (!InitializeSecurityDescriptor(ref descriptor, 1 /*SECURITY_DESCRIPTOR_REVISION*/)) throw new ApplicationException(""InitializeSecurityDescriptor failed: "" + Marshal.GetLastWin32Error()); if (!SetSecurityDescriptorDacl(ref descriptor, true, IntPtr.Zero, false)) throw new ApplicationException(""SetSecurityDescriptorDacl failed: "" + Marshal.GetLastWin32Error()); Marshal.StructureToPtr(descriptor, pDescriptor, false); Marshal.StructureToPtr(attributes, pAttributes, false); } #region Interop definitions private struct SECURITY_DESCRIPTOR { internal byte Revision; internal byte Sbz1; internal short Control; internal IntPtr Owner; internal IntPtr Group; internal IntPtr Sacl; internal IntPtr Dacl; } private struct SECURITY_ATTRIBUTES { internal int nLength; internal IntPtr lpSecurityDescriptor; // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool bInheritHandle; #pragma warning restore 0414 } [DllImport(""advapi32.dll"", SetLastError = true)] private static extern bool InitializeSecurityDescriptor([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, int dwRevision); [DllImport(""advapi32.dll"", SetLastError = true)] private static extern bool SetSecurityDescriptorDacl([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, bool bDaclPresent, IntPtr pDacl, bool bDaclDefaulted); #endregion } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(546673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546673")] [Fact] public void TestBreakInsideNonLocalScopeBinder() { var source = @" public class C { public static void Main() { while (true) { unchecked { break; } } switch(0) { case 0: unchecked { break; } } while (true) { unsafe { break; } } switch(0) { case 0: unsafe { break; } } bool flag = false; while (!flag) { flag = true; unchecked { continue; } } flag = false; while (!flag) { flag = true; unsafe { continue; } } } }"; CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: ""); } [WorkItem(611904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611904")] [Fact] public void LabelAtTopLevelInsideLambda() { var source = @" class Program { delegate T SomeDelegate<T>(out bool f); static void Main(string[] args) { Test((out bool f) => { if (1.ToString() != null) goto l2; f = true; l1: if (1.ToString() != null) return 123; // <==== ERROR EXPECTED HERE f = true; if (1.ToString() != null) return 456; l2: goto l1; }); } static void Test<T>(SomeDelegate<T> f) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,17): error CS0177: The out parameter 'f' must be assigned to before control leaves the current method // return 123; // <==== ERROR EXPECTED HERE Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 123;").WithArguments("f") ); } [WorkItem(633927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633927")] [Fact] public void Xyzzy() { var source = @"class C { struct S { int x; S(dynamic y) { Goo(y, null); } } static void Goo(int y) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,13): error CS1501: No overload for method 'Goo' takes 2 arguments // Goo(y, null); Diagnostic(ErrorCode.ERR_BadArgCount, "Goo").WithArguments("Goo", "2"), // (6,9): error CS0171: Field 'C.S.x' must be fully assigned before control is returned to the caller // S(dynamic y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("C.S.x"), // (5,13): warning CS0169: The field 'C.S.x' is never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C.S.x") ); } [WorkItem(667368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667368")] [Fact] public void RegressionTest667368() { var source = @"using System.Collections.Generic; namespace ConsoleApplication1 { internal class Class1 { Dictionary<string, int> _dict = new Dictionary<string, int>(); public Class1() { } public int? GetCode(dynamic value) { int val; if (value != null && _dict.TryGetValue(value, out val)) return val; return null; } } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,24): error CS0165: Use of unassigned local variable 'val' // return val; Diagnostic(ErrorCode.ERR_UseDefViolation, "val").WithArguments("val") ); } [WorkItem(690921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690921")] [Fact] public void RegressionTest690921() { var source = @"using System.Collections.Generic; namespace ConsoleApplication1 { internal class Class1 { Dictionary<string, int> _dict = new Dictionary<string, int>(); public Class1() { } public static string GetOutBoxItemId(string itemName, string uniqueIdKey, string listUrl, Dictionary<string, dynamic> myList = null, bool useDefaultCredentials = false) { string uniqueId = null; dynamic myItemName; if (myList != null && myList.TryGetValue(""DisplayName"", out myItemName) && myItemName == itemName) { } return uniqueId; } public static void Main() { } } } "; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(715338, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715338")] [Fact] public void RegressionTest715338() { var source = @"using System; using System.Collections.Generic; static class Program { static void Add(this IList<int> source, string key, int value) { } static void View(Action<string, int> adder) { } static readonly IList<int> myInts = null; static void Main() { View(myInts.Add); } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(808567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808567")] [Fact] public void RegressionTest808567() { var source = @"class Base { public Base(out int x, System.Func<int> u) { x = 0; } } class Derived2 : Base { Derived2(out int p1) : base(out p1, ()=>p1) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (11,28): error CS1628: Cannot use ref or out parameter 'p1' inside an anonymous method, lambda expression, or query expression // : base(out p1, ()=>p1) Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "p1").WithArguments("p1"), // (11,20): error CS0269: Use of unassigned out parameter 'p1' // : base(out p1, ()=>p1) Diagnostic(ErrorCode.ERR_UseDefViolationOut, "p1").WithArguments("p1") ); } [WorkItem(949324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949324")] [Fact] public void RegressionTest949324() { var source = @"struct Derived { Derived(int x) { } Derived(long x) : this(p2) // error CS0188: The 'this' object cannot be used before all of its fields are assigned to { this = new Derived(); } private int x; }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (3,5): error CS0171: Field 'Derived.x' must be fully assigned before control is returned to the caller // Derived(int x) { } Diagnostic(ErrorCode.ERR_UnassignedThis, "Derived").WithArguments("Derived.x").WithLocation(3, 5), // (4,28): error CS0103: The name 'p2' does not exist in the current context // Derived(long x) : this(p2) // error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_NameNotInContext, "p2").WithArguments("p2").WithLocation(4, 28), // (8,17): warning CS0169: The field 'Derived.x' is never used // private int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("Derived.x").WithLocation(8, 17) ); } [WorkItem(612, "https://github.com/dotnet/roslyn/issues/612")] [Fact] public void CascadedUnreachableCode() { var source = @"class Program { public static void Main() { string k; switch (1) { case 1: } string s = k; } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS8070: Control cannot fall out of switch from final case label ('case 1:') // case 1: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 1:").WithArguments("case 1:").WithLocation(8, 9), // (10,20): error CS0165: Use of unassigned local variable 'k' // string s = k; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(10, 20) ); } [WorkItem(9581, "https://github.com/dotnet/roslyn/issues/9581")] [Fact] public void UsingSelfAssignment() { var source = @"class Program { static void Main() { using (System.IDisposable x = x) { } } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,39): error CS0165: Use of unassigned local variable 'x' // using (System.IDisposable x = x) Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(5, 39) ); } [Fact] public void UsingAssignment() { var source = @"class Program { static void Main() { using (System.IDisposable x = null) { System.Console.WriteLine(x.ToString()); } using (System.IDisposable x = null, y = x) { System.Console.WriteLine(y.ToString()); } } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void RangeDefiniteAssignmentOrder() { CreateCompilationWithIndexAndRange(@" class C { void M() { int x; var r = (x=0)..(x+1); int y; r = (y+1)..(y=0); } }").VerifyDiagnostics( // (9,14): error CS0165: Use of unassigned local variable 'y' // r = (y+1)..(y=0); Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(9, 14)); } [Fact] public void FieldAssignedInLambdaOnly() { var source = @"using System; struct S { private object F; private object G; public S(object x, object y) { Action a = () => { F = x; }; G = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS0171: Field 'S.F' must be fully assigned before control is returned to the caller // public S(object x, object y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.F").WithLocation(6, 12), // (8,28): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { F = x; }; Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "F").WithLocation(8, 28)); } [Fact] public void FieldAssignedInLocalFunctionOnly() { var source = @"struct S { private object F; private object G; public S(object x, object y) { void f() { F = x; } G = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,12): error CS0171: Field 'S.F' must be fully assigned before control is returned to the caller // public S(object x, object y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.F").WithLocation(5, 12), // (7,14): warning CS8321: The local function 'f' is declared but never used // void f() { F = x; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(7, 14), // (7,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void f() { F = x; } Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "F").WithLocation(7, 20)); } [Fact] [WorkItem(1243877, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1243877")] public void WorkItem1243877() { string program = @" static class C { static void Main() { Test(out var x, x); } static void Test(out Empty x, object y) => throw null; } struct Empty { } "; CreateCompilation(program).VerifyDiagnostics( // (6,25): error CS8196: Reference to an implicitly-typed out variable 'x' is not permitted in the same argument list. // Test(out var x, x); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x").WithArguments("x").WithLocation(6, 25) ); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CodeAnalysisResources.resx"> <body> <trans-unit id="A_language_name_cannot_be_specified_for_this_option"> <source>A language name cannot be specified for this option.</source> <target state="translated">Non è possibile specificare un nome di linguaggio per questa opzione.</target> <note /> </trans-unit> <trans-unit id="A_language_name_must_be_specified_for_this_option"> <source>A language name must be specified for this option.</source> <target state="translated">È necessario specificare un nome di linguaggio per questa opzione.</target> <note /> </trans-unit> <trans-unit id="AssemblyReferencesNetFramework"> <source>The assembly containing type '{0}' references .NET Framework, which is not supported.</source> <target state="translated">L'assembly che contiene il tipo '{0}' fa riferimento a .NET Framework, che non è supportato.</target> <note /> </trans-unit> <trans-unit id="ChangesMustBeWithinBoundsOfSourceText"> <source>Changes must be within bounds of SourceText</source> <target state="translated">Le modifiche devono rientrare nei limiti di SourceText</target> <note /> </trans-unit> <trans-unit id="ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging"> <source>Changing the version of an assembly reference is not allowed during debugging: '{0}' changed version to '{1}'.</source> <target state="translated">La modifica della versione di un riferimento ad assembly durante il debug non è consentita: '{0}' ha modificato la versione in '{1}'.</target> <note /> </trans-unit> <trans-unit id="CompilerAnalyzerThrowsDescription"> <source>Analyzer '{0}' threw the following exception: '{1}'.</source> <target state="translated">L'analizzatore '{0}' ha generato l'eccezione seguente: '{1}'.</target> <note /> </trans-unit> <trans-unit id="DisableAnalyzerDiagnosticsMessage"> <source>Suppress the following diagnostics to disable this analyzer: {0}</source> <target state="translated">Per disabilitare questo analizzatore, eliminare la diagnostica seguente: {0}</target> <note>{0}: Comma-separated list of diagnostic IDs</note> </trans-unit> <trans-unit id="HintNameInvalidChar"> <source>The hintName '{0}' contains an invalid character '{1}' at position {2}.</source> <target state="translated">L'elemento hintName '{0}' contiene un carattere non valido '{1}' alla posizione {2}.</target> <note>{0}: the provided hintname. {1}: the invalid character, {2} the position it occurred at</note> </trans-unit> <trans-unit id="HintNameUniquePerGenerator"> <source>The hintName '{0}' of the added source file must be unique within a generator.</source> <target state="translated">L'elemento hintName '{0}' del file di origine aggiunto deve essere univoco all'interno di un generatore.</target> <note>{0}: the provided hintname</note> </trans-unit> <trans-unit id="InvalidAdditionalFile"> <source>Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'.</source> <target state="translated">Il file aggiuntivo non appartiene all'oggetto 'CompilationWithAnalyzers' sottostante.</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticSuppressionReported"> <source>Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor.</source> <target state="translated">L'ID diagnostica '{0}' eliminato non corrisponde all'ID eliminabile '{1}' per il descrittore di eliminazione specificato.</target> <note /> </trans-unit> <trans-unit id="InvalidOperationBlockForAnalysisContext"> <source>Given operation block does not belong to the current analysis context.</source> <target state="translated">Il blocco operazioni specificato non appartiene al contesto di analisi corrente.</target> <note /> </trans-unit> <trans-unit id="IsSymbolAccessibleBadWithin"> <source>Parameter '{0}' must be an 'INamedTypeSymbol' or an 'IAssemblySymbol'.</source> <target state="translated">Il parametro '{0}' deve essere un elemento 'INamedTypeSymbol' o 'IAssemblySymbol'.</target> <note /> </trans-unit> <trans-unit id="IsSymbolAccessibleWrongAssembly"> <source>Parameter '{0}' must be a symbol from this compilation or some referenced assembly.</source> <target state="translated">Il parametro '{0}' deve essere un simbolo di questa compilazione oppure un qualsiasi assembly cui viene fatto riferimento.</target> <note /> </trans-unit> <trans-unit id="ModuleHasInvalidAttributes"> <source>Module has invalid attributes.</source> <target state="translated">Il modulo contiene attributi non validi.</target> <note /> </trans-unit> <trans-unit id="NonReportedDiagnosticCannotBeSuppressed"> <source>Non-reported diagnostic with ID '{0}' cannot be suppressed.</source> <target state="translated">Non è possibile eliminare la diagnostica non restituita con ID '{0}'.</target> <note /> </trans-unit> <trans-unit id="NotARootOperation"> <source>Given operation has a non-null parent.</source> <target state="translated">L'operazione specificata contiene un elemento padre non Null.</target> <note /> </trans-unit> <trans-unit id="OperationHasNullSemanticModel"> <source>Given operation has a null semantic model.</source> <target state="translated">L'operazione specificata contiene un modello semantico Null.</target> <note /> </trans-unit> <trans-unit id="OperationMustNotBeControlFlowGraphPart"> <source>The provided operation must not be part of a Control Flow Graph.</source> <target state="translated">L'operazione specificata non deve essere inclusa in un grafico del flusso di controllo.</target> <note /> </trans-unit> <trans-unit id="OutputKindNotSupported"> <source>Output kind not supported.</source> <target state="translated">Il tipo di output non è supportato.</target> <note /> </trans-unit> <trans-unit id="PathReturnedByResolveMetadataFileMustBeAbsolute"> <source>Path returned by {0}.ResolveMetadataFile must be absolute: '{1}'</source> <target state="translated">Il percorso restituito da {0}.ResolveMetadataFile deve essere assoluto: '{1}'</target> <note /> </trans-unit> <trans-unit id="AssemblyMustHaveAtLeastOneModule"> <source>Assembly must have at least one module.</source> <target state="translated">L'assembly deve contenere almeno un modulo.</target> <note /> </trans-unit> <trans-unit id="ModuleCopyCannotBeUsedToCreateAssemblyMetadata"> <source>Module copy can't be used to create an assembly metadata.</source> <target state="translated">Non è possibile usare la copia del modulo per creare i metadati di un assembly.</target> <note /> </trans-unit> <trans-unit id="Single_type_per_generator_0"> <source>Only a single {0} can be registered per generator.</source> <target state="translated">È possibile registrare solo un tipo {0} per generatore.</target> <note>{0}: type name</note> </trans-unit> <trans-unit id="SourceTextRequiresEncoding"> <source>The SourceText with hintName '{0}' must have an explicit encoding set.</source> <target state="translated">L'elemento SourceText con hintName '{0}' deve avere una codifica esplicita impostata.</target> <note>'SourceText' is not localizable. {0}: the provided hintname</note> </trans-unit> <trans-unit id="SupportedDiagnosticsHasNullDescriptor"> <source>Analyzer '{0}' contains a null descriptor in its 'SupportedDiagnostics'.</source> <target state="translated">L'analizzatore '{0}' contiene un descrittore Null nel relativo elemento 'SupportedDiagnostics'.</target> <note /> </trans-unit> <trans-unit id="SupportedSuppressionsHasNullDescriptor"> <source>Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'.</source> <target state="translated">L'analizzatore '{0}' contiene un descrittore Null nel relativo elemento 'SupportedSuppressions'.</target> <note /> </trans-unit> <trans-unit id="SuppressionDiagnosticDescriptorMessage"> <source>Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'</source> <target state="translated">La diagnostica '{0}: {1}' è stata eliminata a livello di codice da un elemento DiagnosticSuppressor con ID eliminazione '{2}' e giustificazione '{3}'</target> <note /> </trans-unit> <trans-unit id="SuppressionDiagnosticDescriptorTitle"> <source>Programmatic suppression of an analyzer diagnostic</source> <target state="translated">Eliminazione a livello di codice di una diagnostica dell'analizzatore</target> <note /> </trans-unit> <trans-unit id="SuppressionIdCantBeNullOrWhitespace"> <source>A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</source> <target state="translated">L'ID di un elemento SuppressionDescriptor non deve essere Null, né una stringa vuota o una stringa composta solo da spazi vuoti.</target> <note /> </trans-unit> <trans-unit id="TupleElementNullableAnnotationCountMismatch"> <source>If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple.</source> <target state="translated">Se si specificano annotazioni nullable di elementi di tupla, il numero delle annotazioni deve corrispondere alla cardinalità della tupla.</target> <note /> </trans-unit> <trans-unit id="UnableToDetermineSpecificCauseOfFailure"> <source>Unable to determine specific cause of the failure.</source> <target state="translated">Non è possibile determinare la causa specifica dell'errore.</target> <note /> </trans-unit> <trans-unit id="Unresolved"> <source>Unresolved: </source> <target state="translated">Non risolto: </target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>assembly</source> <target state="translated">assembly</target> <note /> </trans-unit> <trans-unit id="Class1"> <source>class</source> <target state="translated">classe</target> <note /> </trans-unit> <trans-unit id="Constructor"> <source>constructor</source> <target state="translated">costruttore</target> <note /> </trans-unit> <trans-unit id="Delegate1"> <source>delegate</source> <target state="translated">delegato</target> <note /> </trans-unit> <trans-unit id="Enum1"> <source>enum</source> <target state="translated">enumerazione</target> <note /> </trans-unit> <trans-unit id="Event1"> <source>event</source> <target state="translated">evento</target> <note /> </trans-unit> <trans-unit id="Field"> <source>field</source> <target state="translated">campo</target> <note /> </trans-unit> <trans-unit id="TypeParameter"> <source>type parameter</source> <target state="translated">parametro di tipo</target> <note /> </trans-unit> <trans-unit id="Interface1"> <source>interface</source> <target state="translated">interfaccia</target> <note /> </trans-unit> <trans-unit id="Method"> <source>method</source> <target state="translated">metodo</target> <note /> </trans-unit> <trans-unit id="Module"> <source>module</source> <target state="translated">modulo</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>parameter</source> <target state="translated">parametro</target> <note /> </trans-unit> <trans-unit id="Property"> <source>property, indexer</source> <target state="translated">proprietà, indicizzatore</target> <note /> </trans-unit> <trans-unit id="Return1"> <source>return</source> <target state="translated">valore restituito</target> <note /> </trans-unit> <trans-unit id="Struct1"> <source>struct</source> <target state="translated">struct</target> <note /> </trans-unit> <trans-unit id="CannotCreateReferenceToSubmission"> <source>Can't create a reference to a submission.</source> <target state="translated">Non è possibile creare un riferimento a un invio.</target> <note /> </trans-unit> <trans-unit id="CannotCreateReferenceToModule"> <source>Can't create a reference to a module.</source> <target state="translated">Non è possibile creare un riferimento a un modulo.</target> <note /> </trans-unit> <trans-unit id="InMemoryAssembly"> <source>&lt;in-memory assembly&gt;</source> <target state="translated">&lt;assembly in memoria&gt;</target> <note /> </trans-unit> <trans-unit id="InMemoryModule"> <source>&lt;in-memory module&gt;</source> <target state="translated">&lt;modulo in memoria&gt;</target> <note /> </trans-unit> <trans-unit id="SizeHasToBePositive"> <source>Size has to be positive.</source> <target state="translated">Il valore delle dimensioni deve essere positivo.</target> <note /> </trans-unit> <trans-unit id="AssemblyFileNotFound"> <source>Assembly file not found</source> <target state="translated">Il file di assembly non è stato trovato</target> <note /> </trans-unit> <trans-unit id="CannotEmbedInteropTypesFromModule"> <source>Can't embed interop types from module.</source> <target state="translated">Non è possibile incorporare tipi di interoperabilità dal modulo.</target> <note /> </trans-unit> <trans-unit id="CannotAliasModule"> <source>Can't alias a module.</source> <target state="translated">Non è possibile creare l'alias di un modulo.</target> <note /> </trans-unit> <trans-unit id="InvalidAlias"> <source>Invalid alias.</source> <target state="translated">L'alias non è valido.</target> <note /> </trans-unit> <trans-unit id="GetMetadataMustReturnInstance"> <source>{0}.GetMetadata() must return an instance of {1}.</source> <target state="translated">{0}.GetMetadata() deve restituire un'istanza di {1}.</target> <note /> </trans-unit> <trans-unit id="UnsupportedSuppressionReported"> <source>Reported suppression with ID '{0}' is not supported by the suppressor.</source> <target state="translated">L'eliminazione restituita con ID '{0}' non è supportata dall'elemento di eliminazione.</target> <note /> </trans-unit> <trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"> <source>Value too large to be represented as a 30 bit unsigned integer.</source> <target state="translated">Il valore è troppo grande per essere rappresentato come intero senza segno a 30 bit.</target> <note /> </trans-unit> <trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized"> <source>Arrays with more than one dimension cannot be serialized.</source> <target state="translated">Non è possibile serializzare le matrice con più di una dimensione.</target> <note /> </trans-unit> <trans-unit id="InvalidAssemblyName"> <source>Invalid assembly name: '{0}'</source> <target state="translated">Il nome dell'assembly '{0}' non è valido</target> <note /> </trans-unit> <trans-unit id="AbsolutePathExpected"> <source>Absolute path expected.</source> <target state="translated">È previsto il percorso assoluto.</target> <note /> </trans-unit> <trans-unit id="EmptyKeyInPathMap"> <source>A key in the pathMap is empty.</source> <target state="translated">Una chiave in pathMap è vuota.</target> <note /> </trans-unit> <trans-unit id="NullValueInPathMap"> <source>A value in the pathMap is null.</source> <target state="translated">Un valore in pathMap è Null.</target> <note /> </trans-unit> <trans-unit id="CompilationOptionsMustNotHaveErrors"> <source>Compilation options must not have errors.</source> <target state="translated">Le opzioni di compilazione non devono contenere errori.</target> <note /> </trans-unit> <trans-unit id="ReturnTypeCannotBeValuePointerbyRefOrOpen"> <source>Return type can't be a value type, pointer, by-ref or open generic type</source> <target state="translated">Il tipo restituito non può essere un tipo valore, un puntatore, un tipo generico open o by-ref</target> <note /> </trans-unit> <trans-unit id="ReturnTypeCannotBeVoidByRefOrOpen"> <source>Return type can't be void, by-ref or open generic type</source> <target state="translated">Il tipo restituito non può essere nullo, un tipo generico open o by-ref</target> <note /> </trans-unit> <trans-unit id="TypeMustBeSameAsHostObjectTypeOfPreviousSubmission"> <source>Type must be same as host object type of previous submission.</source> <target state="translated">Il tipo deve essere uguale al tipo di oggetto host dell'invio precedente.</target> <note /> </trans-unit> <trans-unit id="PreviousSubmissionHasErrors"> <source>Previous submission has errors.</source> <target state="translated">L'invio precedente contiene errori.</target> <note /> </trans-unit> <trans-unit id="InvalidOutputKindForSubmission"> <source>Invalid output kind for submission. DynamicallyLinkedLibrary expected.</source> <target state="translated">Il tipo di output per l'invio non è valido. È previsto DynamicallyLinkedLibrary.</target> <note /> </trans-unit> <trans-unit id="InvalidCompilationOptions"> <source>Invalid compilation options -- submission can't be signed.</source> <target state="translated">Opzioni di compilazione non valide. Non è possibile firmare l'invio.</target> <note /> </trans-unit> <trans-unit id="ResourceStreamProviderShouldReturnNonNullStream"> <source>Resource stream provider should return non-null stream.</source> <target state="translated">Il provider di flusso della risorsa deve restituire un flusso non Null.</target> <note /> </trans-unit> <trans-unit id="ReferenceResolverShouldReturnReadableNonNullStream"> <source>Reference resolver should return readable non-null stream.</source> <target state="translated">Il resolver di riferimenti deve restituire un flusso non Null leggibile.</target> <note /> </trans-unit> <trans-unit id="EmptyOrInvalidResourceName"> <source>Empty or invalid resource name</source> <target state="translated">Nome di risorsa vuoto o non valido</target> <note /> </trans-unit> <trans-unit id="EmptyOrInvalidFileName"> <source>Empty or invalid file name</source> <target state="translated">Nome di file vuoto o non valido</target> <note /> </trans-unit> <trans-unit id="ResourceDataProviderShouldReturnNonNullStream"> <source>Resource data provider should return non-null stream</source> <target state="translated">Il provider di dati della risorsa deve restituire un flusso non Null</target> <note /> </trans-unit> <trans-unit id="FileNotFound"> <source>File not found.</source> <target state="translated">Il file non è stato trovato.</target> <note /> </trans-unit> <trans-unit id="PathReturnedByResolveStrongNameKeyFileMustBeAbsolute"> <source>Path returned by {0}.ResolveStrongNameKeyFile must be absolute: '{1}'</source> <target state="translated">Il percorso restituito da {0}.ResolveStrongNameKeyFile deve essere assoluto: '{1}'</target> <note /> </trans-unit> <trans-unit id="TypeMustBeASubclassOfSyntaxAnnotation"> <source>type must be a subclass of SyntaxAnnotation.</source> <target state="translated">il tipo deve essere una sottoclasse di SyntaxAnnotation.</target> <note /> </trans-unit> <trans-unit id="InvalidModuleName"> <source>Invalid module name specified in metadata module '{0}': '{1}'</source> <target state="translated">È stato specificato un nome di modulo non valido nel modulo dei metadati '{0}': '{1}'</target> <note /> </trans-unit> <trans-unit id="FileSizeExceedsMaximumAllowed"> <source>File size exceeds maximum allowed size of a valid metadata file.</source> <target state="translated">Le dimensioni del file superano quelle massime consentite per un file di metadati valido.</target> <note /> </trans-unit> <trans-unit id="NameCannotBeNull"> <source>Name cannot be null.</source> <target state="translated">Il nome non può essere Null.</target> <note /> </trans-unit> <trans-unit id="NameCannotBeEmpty"> <source>Name cannot be empty.</source> <target state="translated">Il nome non può essere vuoto.</target> <note /> </trans-unit> <trans-unit id="NameCannotStartWithWhitespace"> <source>Name cannot start with whitespace.</source> <target state="translated">Il nome non può iniziare con uno spazio vuoto.</target> <note /> </trans-unit> <trans-unit id="NameContainsInvalidCharacter"> <source>Name contains invalid characters.</source> <target state="translated">Il nome contiene caratteri non validi.</target> <note /> </trans-unit> <trans-unit id="SpanDoesNotIncludeStartOfLine"> <source>The span does not include the start of a line.</source> <target state="translated">L'elemento span non include l'inizio di una riga.</target> <note /> </trans-unit> <trans-unit id="SpanDoesNotIncludeEndOfLine"> <source>The span does not include the end of a line.</source> <target state="translated">L'elemento span non include la fine di una riga.</target> <note /> </trans-unit> <trans-unit id="StartMustNotBeNegative"> <source>'start' must not be negative</source> <target state="translated">'start' non deve essere negativo</target> <note /> </trans-unit> <trans-unit id="EndMustNotBeLessThanStart"> <source>'end' must not be less than 'start'</source> <target state="translated">'il valore di 'end' deve essere minore di quello di 'start'</target> <note /> </trans-unit> <trans-unit id="InvalidContentType"> <source>Invalid content type</source> <target state="translated">Il tipo di contenuto non è valido</target> <note /> </trans-unit> <trans-unit id="ExpectedNonEmptyPublicKey"> <source>Expected non-empty public key</source> <target state="translated">È prevista una chiave pubblica non vuota</target> <note /> </trans-unit> <trans-unit id="InvalidSizeOfPublicKeyToken"> <source>Invalid size of public key token.</source> <target state="translated">La dimensione del token di chiave pubblica non è valida.</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyName"> <source>Invalid characters in assembly name</source> <target state="translated">Caratteri non validi nel nome dell'assembly</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyCultureName"> <source>Invalid characters in assembly culture name</source> <target state="translated">Caratteri non validi nel nome delle impostazioni cultura dell'assembly</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportReadAndSeek"> <source>Stream must support read and seek operations.</source> <target state="translated">Il flusso deve supportare operazioni di lettura e ricerca.</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportRead"> <source>Stream must be readable.</source> <target state="translated">Il flusso deve essere leggibile.</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportWrite"> <source>Stream must be writable.</source> <target state="translated">Il flusso deve essere scrivibile.</target> <note /> </trans-unit> <trans-unit id="PdbStreamUnexpectedWhenEmbedding"> <source>PDB stream should not be given when embedding PDB into the PE stream.</source> <target state="translated">È consigliabile non specificare il flusso PDB quando si incorpora PDB nel flusso PE.</target> <note /> </trans-unit> <trans-unit id="PdbStreamUnexpectedWhenEmittingMetadataOnly"> <source>PDB stream should not be given when emitting metadata only.</source> <target state="translated">È consigliabile non specificare il flusso PDB quando si creano solo metadati.</target> <note /> </trans-unit> <trans-unit id="MetadataPeStreamUnexpectedWhenEmittingMetadataOnly"> <source>Metadata PE stream should not be given when emitting metadata only.</source> <target state="translated">È consigliabile non specificare il flusso PE dei metadati quando si creano solo metadati.</target> <note /> </trans-unit> <trans-unit id="IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream"> <source>Including private members should not be used when emitting to the secondary assembly output.</source> <target state="translated">È consigliabile non usare membri privati di inclusione quando si crea l'output secondario dell'assembly.</target> <note /> </trans-unit> <trans-unit id="MustIncludePrivateMembersUnlessRefAssembly"> <source>Must include private members unless emitting a ref assembly.</source> <target state="translated">Deve includere membri privati a meno che non si stia creando un assembly di riferimento.</target> <note /> </trans-unit> <trans-unit id="EmbeddingPdbUnexpectedWhenEmittingMetadata"> <source>Embedding PDB is not allowed when emitting metadata.</source> <target state="translated">L'incorporamento di PDB non è consentito quando si creano metadati.</target> <note /> </trans-unit> <trans-unit id="CannotTargetNetModuleWhenEmittingRefAssembly"> <source>Cannot target net module when emitting ref assembly.</source> <target state="translated">Non è possibile impostare come destinazione il modulo quando si crea l'assembly di riferimento.</target> <note /> </trans-unit> <trans-unit id="InvalidHash"> <source>Invalid hash.</source> <target state="translated">Hash non valido.</target> <note /> </trans-unit> <trans-unit id="UnsupportedHashAlgorithm"> <source>Unsupported hash algorithm.</source> <target state="translated">L'algoritmo hash non è supportato.</target> <note /> </trans-unit> <trans-unit id="InconsistentLanguageVersions"> <source>Inconsistent language versions</source> <target state="translated">Versioni incoerenti del linguaggio</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidRelocation"> <source>Win32 resources, assumed to be in COFF object format, have one or more invalid relocation header values.</source> <target state="translated">Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno uno o più valori di intestazione di rilocazione non validi.</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidSectionSize"> <source>Win32 resources, assumed to be in COFF object format, have an invalid section size.</source> <target state="translated">Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno una dimensione di sezione non valida.</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidSymbol"> <source>Win32 resources, assumed to be in COFF object format, have one or more invalid symbol values.</source> <target state="translated">Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno uno o più valori di simbolo non validi.</target> <note /> </trans-unit> <trans-unit id="CoffResourceMissingSection"> <source>Win32 resources, assumed to be in COFF object format, are missing one or both of sections '.rsrc$01' and '.rsrc$02'</source> <target state="translated">Nelle risorse Win32, che dovrebbero essere nel formato oggetto COFF, mancano una o entrambe le sezioni '.rsrc$01' e '.rsrc$02'</target> <note /> </trans-unit> <trans-unit id="IconStreamUnexpectedFormat"> <source>Icon stream is not in the expected format.</source> <target state="translated">Il formato del flusso dell'icona non è corretto.</target> <note /> </trans-unit> <trans-unit id="InvalidCultureName"> <source>Invalid culture name: '{0}'</source> <target state="translated">Il nome delle impostazioni cultura '{0}' non è valido</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidGlobalSectionName"> <source>Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}'</source> <target state="translated">Il nome della sezione '{0}' di configurazione dell'analizzatore globale non è valido perché non è un percorso assoluto. La sezione verrà ignorata. La sezione è stata dichiarata nel file: '{1}'</target> <note>{0}: invalid section name, {1} path to global config</note> </trans-unit> <trans-unit id="WRN_InvalidGlobalSectionName_Title"> <source>Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored.</source> <target state="translated">Il nome della sezione di configurazione dell'analizzatore globale non è valido perché non è un percorso assoluto. La sezione verrà ignorata.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSeverityInAnalyzerConfig"> <source>The diagnostic '{0}' was given an invalid severity '{1}' in the analyzer config file at '{2}'.</source> <target state="translated">Alla diagnostica ' {0}' è stato assegnato un livello di gravità non valido '{1}' nel file di configurazione dell'analizzatore alla posizione '{2}'.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSeverityInAnalyzerConfig_Title"> <source>Invalid severity in analyzer config file.</source> <target state="translated">Gravità non valida nel file di configurazione dell'analizzatore.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleGlobalAnalyzerKeys"> <source>Multiple global analyzer config files set the same key '{0}' in section '{1}'. It has been unset. Key was set by the following files: '{2}'</source> <target state="translated">Più file di configurazione dell'analizzatore globale impostano la stessa chiave '{0}' nella sezione '{1}'. L'impostazione è stata annullata. La chiave è stata impostata dai file seguenti: '{2}'</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleGlobalAnalyzerKeys_Title"> <source>Multiple global analyzer config files set the same key. It has been unset.</source> <target state="translated">Più file di configurazione dell'analizzatore globale impostano la stessa chiave. L'impostazione è stata annullata.</target> <note /> </trans-unit> <trans-unit id="WinRTIdentityCantBeRetargetable"> <source>WindowsRuntime identity can't be retargetable</source> <target state="translated">Non è possibile ridefinire la destinazione dell'identità WindowsRuntime</target> <note /> </trans-unit> <trans-unit id="PEImageNotAvailable"> <source>PE image not available.</source> <target state="translated">L'immagine PE non è disponibile.</target> <note /> </trans-unit> <trans-unit id="AssemblySigningNotSupported"> <source>Assembly signing not supported.</source> <target state="translated">La firma dell'assembly non è supportata.</target> <note /> </trans-unit> <trans-unit id="XmlReferencesNotSupported"> <source>References to XML documents are not supported.</source> <target state="translated">I riferimenti ai documenti XML non sono supportati.</target> <note /> </trans-unit> <trans-unit id="FailedToResolveRuleSetName"> <source>Could not locate the rule set file '{0}'.</source> <target state="translated">Non è stato possibile individuare il file del set di regole '{0}'.</target> <note /> </trans-unit> <trans-unit id="InvalidRuleSetInclude"> <source>An error occurred while loading the included rule set file {0} - {1}</source> <target state="translated">Si è verificato un errore durante il caricamento del file del set di regole incluso {0} - {1}</target> <note /> </trans-unit> <trans-unit id="CompilerAnalyzerFailure"> <source>Analyzer Failure</source> <target state="translated">Errore dell'analizzatore</target> <note>{0}: Analyzer name {1}: Type name {2}: Localized exception message {3}: Localized detail message</note> </trans-unit> <trans-unit id="CompilerAnalyzerThrows"> <source>Analyzer '{0}' threw an exception of type '{1}' with message '{2}'. {3}</source> <target state="translated">L'analizzatore '{0}' ha generato un'eccezione di tipo '{1}'. Messaggio: '{2}'. {3}</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverFailure"> <source>Analyzer Driver Failure</source> <target state="translated">Errore del driver dell'analizzatore</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverThrows"> <source>Analyzer driver threw an exception of type '{0}' with message '{1}'.</source> <target state="translated">Il driver dell'analizzatore ha generato un'eccezione di tipo '{0}'. Messaggio: '{1}'.</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverThrowsDescription"> <source>Analyzer driver threw the following exception: '{0}'.</source> <target state="translated">Il driver dell'analizzatore ha generato l'eccezione seguente: '{0}'.</target> <note /> </trans-unit> <trans-unit id="PEImageDoesntContainManagedMetadata"> <source>PE image doesn't contain managed metadata.</source> <target state="translated">L'immagine PE non contiene metadati gestiti.</target> <note /> </trans-unit> <trans-unit id="ChangesMustNotOverlap"> <source>The changes must not overlap.</source> <target state="translated">Le modifiche devono essere ordinate e non sovrapposte.</target> <note /> </trans-unit> <trans-unit id="DiagnosticIdCantBeNullOrWhitespace"> <source>A DiagnosticDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</source> <target state="translated">L'ID di un elemento DiagnosticDescriptor non deve essere Null, né una stringa vuota o una stringa composta solo da spazi vuoti.</target> <note /> </trans-unit> <trans-unit id="RuleSetHasDuplicateRules"> <source>The rule set file has duplicate rules for '{0}' with differing actions '{1}' and '{2}'.</source> <target state="translated">Il file del set di regole contiene regole duplicate per '{0}' con azioni '{1}' e '{2}' diverse.</target> <note /> </trans-unit> <trans-unit id="CantCreateModuleReferenceToAssembly"> <source>Can't create a module reference to an assembly.</source> <target state="translated">Non è possibile creare un riferimento del modulo a un assembly.</target> <note /> </trans-unit> <trans-unit id="CantCreateReferenceToDynamicAssembly"> <source>Can't create a metadata reference to a dynamic assembly.</source> <target state="translated">Non è possibile creare un riferimento dei metadati a un assembly dinamico.</target> <note /> </trans-unit> <trans-unit id="CantCreateReferenceToAssemblyWithoutLocation"> <source>Can't create a metadata reference to an assembly without location.</source> <target state="translated">Non è possibile creare un riferimento dei metadati a un assembly senza percorso.</target> <note /> </trans-unit> <trans-unit id="ArgumentCannotBeEmpty"> <source>Argument cannot be empty.</source> <target state="translated">L'argomento non può essere vuoto.</target> <note /> </trans-unit> <trans-unit id="ArgumentElementCannotBeNull"> <source>Argument cannot have a null element.</source> <target state="translated">L'argomento non può contenere un elemento Null.</target> <note /> </trans-unit> <trans-unit id="UnsupportedDiagnosticReported"> <source>Reported diagnostic with ID '{0}' is not supported by the analyzer.</source> <target state="translated">La diagnostica restituita con ID '{0}' non è supportata dall'analizzatore.</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticIdReported"> <source>Reported diagnostic has an ID '{0}', which is not a valid identifier.</source> <target state="translated">L'ID della diagnostica restituita è '{0}', che non è un identificatore valido.</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticLocationReported"> <source>Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed.</source> <target state="translated">Il percorso di origine della diagnostica restituita '{0}' è incluso nel file '{1}', che non fa parte della compilazione da analizzare.</target> <note /> </trans-unit> <trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder"> <source>The type '{0}' is not understood by the serialization binder.</source> <target state="translated">Il tipo '{0}' non è riconosciuto dal binder di serializzazioni.</target> <note /> </trans-unit> <trans-unit id="Cannot_deserialize_type_0"> <source>Cannot deserialize type '{0}'.</source> <target state="translated">Non è possibile deserializzare il tipo '{0}'.</target> <note /> </trans-unit> <trans-unit id="Cannot_serialize_type_0"> <source>Cannot serialize type '{0}'.</source> <target state="translated">Non è possibile serializzare il tipo '{0}'.</target> <note /> </trans-unit> <trans-unit id="InvalidNodeToTrack"> <source>Node to track is not a descendant of the root.</source> <target state="translated">Il nodo da tracciare non è un discendente della radice.</target> <note /> </trans-unit> <trans-unit id="NodeOrTokenOutOfSequence"> <source>A node or token is out of sequence.</source> <target state="translated">Un nodo o token è fuori sequenza.</target> <note /> </trans-unit> <trans-unit id="UnexpectedTypeOfNodeInList"> <source>A node in the list is not of the expected type.</source> <target state="translated">Un nodo nell'elenco non è del tipo previsto.</target> <note /> </trans-unit> <trans-unit id="MissingListItem"> <source>The item specified is not the element of a list.</source> <target state="translated">L'elemento specificato non è l'elemento di un elenco.</target> <note /> </trans-unit> <trans-unit id="InvalidPublicKey"> <source>Invalid public key.</source> <target state="translated">Chiave pubblica non valida.</target> <note /> </trans-unit> <trans-unit id="InvalidPublicKeyToken"> <source>Invalid public key token.</source> <target state="translated">Token di chiave pubblica non valido.</target> <note /> </trans-unit> <trans-unit id="InvalidDataAtOffset"> <source>Invalid data at offset {0}: {1}{2}*{3}{4}</source> <target state="translated">Dati non validi in corrispondenza dell'offset {0}: {1}{2}*{3}{4}</target> <note /> </trans-unit> <trans-unit id="SymWriterNotDeterministic"> <source>Windows PDB writer doesn't support deterministic compilation: '{0}'</source> <target state="translated">Il writer PDB di Windows non supporta la compilazione deterministica: '{0}'</target> <note /> </trans-unit> <trans-unit id="SymWriterOlderVersionThanRequired"> <source>The version of Windows PDB writer is older than required: '{0}'</source> <target state="translated">La versione del writer PDB di Windows è meno recente di quella richiesta: '{0}'</target> <note /> </trans-unit> <trans-unit id="SymWriterDoesNotSupportSourceLink"> <source>Windows PDB writer doesn't support SourceLink feature: '{0}'</source> <target state="translated">Il writer PDB di Windows non supporta la funzionalità SourceLink: '{0}'</target> <note /> </trans-unit> <trans-unit id="RuleSetBadAttributeValue"> <source>The attribute {0} has an invalid value of {1}.</source> <target state="translated">Il valore {1} dell'attributo {0} non è valido.</target> <note /> </trans-unit> <trans-unit id="RuleSetMissingAttribute"> <source>The element {0} is missing an attribute named {1}.</source> <target state="translated">Nell'elemento {0} manca un attributo denominato {1}.</target> <note /> </trans-unit> <trans-unit id="KeepAliveIsNotAnInteger"> <source>Argument to '/keepalive' option is not a 32-bit integer.</source> <target state="translated">L'argomento dell'opzione '/keepalive' non è un intero a 32 bit.</target> <note /> </trans-unit> <trans-unit id="KeepAliveIsTooSmall"> <source>Arguments to '/keepalive' option below -1 are invalid.</source> <target state="translated">Gli argomenti dell'opzione '/keepalive' il cui valore è inferiore a -1 non sono validi.</target> <note /> </trans-unit> <trans-unit id="KeepAliveWithoutShared"> <source>'/keepalive' option is only valid with '/shared' option.</source> <target state="translated">'L'opzione '/keepalive' è valida solo con l'opzione '/shared'.</target> <note /> </trans-unit> <trans-unit id="MismatchedVersion"> <source>Roslyn compiler server reports different protocol version than build task.</source> <target state="translated">Il server del compilatore Roslyn restituisce una versione del protocollo diversa da quella dell'attività di compilazione.</target> <note /> </trans-unit> <trans-unit id="MissingKeepAlive"> <source>Missing argument for '/keepalive' option.</source> <target state="translated">Manca l'argomento per l'opzione '/keepalive'.</target> <note /> </trans-unit> <trans-unit id="AnalyzerTotalExecutionTime"> <source>Total analyzer execution time: {0} seconds.</source> <target state="translated">Tempo totale di esecuzione dell'analizzatore: {0} secondi.</target> <note /> </trans-unit> <trans-unit id="MultithreadedAnalyzerExecutionNote"> <source>NOTE: Elapsed time may be less than analyzer execution time because analyzers can run concurrently.</source> <target state="translated">NOTE: il tempo trascorso può essere inferiore al tempo di esecuzione dell'analizzatore perché non è possibile eseguire gli analizzatori simultaneamente.</target> <note /> </trans-unit> <trans-unit id="AnalyzerExecutionTimeColumnHeader"> <source>Time (s)</source> <target state="translated">Tempo (s)</target> <note /> </trans-unit> <trans-unit id="AnalyzerNameColumnHeader"> <source>Analyzer</source> <target state="translated">Analizzatore</target> <note /> </trans-unit> <trans-unit id="NoAnalyzersFound"> <source>No analyzers found</source> <target state="translated">Non sono stati trovati analizzatori</target> <note /> </trans-unit> <trans-unit id="DuplicateAnalyzerInstances"> <source>Argument contains duplicate analyzer instances.</source> <target state="translated">L'argomento contiene istanze duplicate dell'analizzatore.</target> <note /> </trans-unit> <trans-unit id="UnsupportedAnalyzerInstance"> <source>Argument contains an analyzer instance that does not belong to the 'Analyzers' for this CompilationWithAnalyzers instance.</source> <target state="translated">L'argomento contiene un'istanza dell'analizzatore che non appartiene all'elemento 'Analyzers' per questa istanza di CompilationWithAnalyzers.</target> <note /> </trans-unit> <trans-unit id="InvalidTree"> <source>Syntax tree doesn't belong to the underlying 'Compilation'.</source> <target state="translated">L'albero sintattico non appartiene all'elemento 'Compilation' sottostante.</target> <note /> </trans-unit> <trans-unit id="ResourceStreamEndedUnexpectedly"> <source>Resource stream ended at {0} bytes, expected {1} bytes.</source> <target state="translated">Il flusso della risorsa è terminato a {0} byte, mentre era previsto a {1} byte.</target> <note /> </trans-unit> <trans-unit id="SharedArgumentMissing"> <source>Value for argument '/shared:' must not be empty</source> <target state="translated">Il valore dell'argomento '/shared:' non deve essere vuoto</target> <note /> </trans-unit> <trans-unit id="ExceptionContext"> <source>Exception occurred with following context: {0}</source> <target state="translated">Si è verificata un'eccezione con il contesto seguente: {0}</target> <note /> </trans-unit> <trans-unit id="AnonymousTypeMemberAndNamesCountMismatch2"> <source>{0} and {1} must have the same length.</source> <target state="translated">{0} e {1} devono avere la stessa lunghezza.</target> <note /> </trans-unit> <trans-unit id="AnonymousTypeArgumentCountMismatch2"> <source>{0} must either be 'default' or have the same length as {1}.</source> <target state="translated">{0} deve essere 'default' o avere la stessa lunghezza di {1}.</target> <note /> </trans-unit> <trans-unit id="InconsistentSyntaxTreeFeature"> <source>Inconsistent syntax tree features</source> <target state="translated">Funzionalità incoerenti dell'albero della sintassi</target> <note /> </trans-unit> <trans-unit id="ReferenceOfTypeIsInvalid1"> <source>Reference of type '{0}' is not valid for this compilation.</source> <target state="translated">Il riferimento di tipo '{0}' non è valido per questa compilazione.</target> <note /> </trans-unit> <trans-unit id="MetadataRefNotFoundToRemove1"> <source>MetadataReference '{0}' not found to remove.</source> <target state="translated">Non è stato trovato nessun elemento MetadataReference '{0}' da rimuovere.</target> <note /> </trans-unit> <trans-unit id="TupleElementNameCountMismatch"> <source>If tuple element names are specified, the number of element names must match the cardinality of the tuple.</source> <target state="translated">Se si specificano nomi di elementi di tupla, il numero dei nomi di elementi deve corrispondere alla cardinalità della tupla.</target> <note /> </trans-unit> <trans-unit id="TupleElementNameEmpty"> <source>Tuple element name cannot be an empty string.</source> <target state="translated">Il nome di elemento di tupla non può essere una stringa vuota.</target> <note /> </trans-unit> <trans-unit id="TupleElementLocationCountMismatch"> <source>If tuple element locations are specified, the number of locations must match the cardinality of the tuple.</source> <target state="translated">Se si specificano percorsi di elementi di tupla, il numero dei percorsi deve corrispondere alla cardinalità della tupla.</target> <note /> </trans-unit> <trans-unit id="TuplesNeedAtLeastTwoElements"> <source>Tuples must have at least two elements.</source> <target state="translated">Le tuple devono contenere almeno due elementi.</target> <note /> </trans-unit> <trans-unit id="CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion"> <source>The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers.</source> <target state="translated">La compilazione fa riferimento a più assembly le cui versioni differiscono solo nei numeri di revisione e/o di build generati automaticamente.</target> <note /> </trans-unit> <trans-unit id="TupleUnderlyingTypeMustBeTupleCompatible"> <source>The underlying type for a tuple must be tuple-compatible.</source> <target state="translated">Il tipo sottostante di una tupla deve essere compatibile con la tupla.</target> <note /> </trans-unit> <trans-unit id="UnrecognizedResourceFileFormat"> <source>Unrecognized resource file format.</source> <target state="translated">Il formato del file di risorse non è riconosciuto.</target> <note /> </trans-unit> <trans-unit id="SourceTextCannotBeEmbedded"> <source>SourceText cannot be embedded. Provide encoding or canBeEmbedded=true at construction.</source> <target state="translated">Non è possibile incorporare SourceText. Specificare la codifica oppure canBeEmbedded=true in fase di costruzione.</target> <note /> </trans-unit> <trans-unit id="StreamIsTooLong"> <source>Stream is too long.</source> <target state="translated">Il flusso è troppo lungo.</target> <note /> </trans-unit> <trans-unit id="EmbeddedTextsRequirePdb"> <source>Embedded texts are only supported when emitting a PDB.</source> <target state="translated">I testi incorporati sono supportati solo quando si crea un file PDB.</target> <note /> </trans-unit> <trans-unit id="TheStreamCannotBeWrittenTo"> <source>The stream cannot be written to.</source> <target state="translated">Non è possibile scrivere nel flusso.</target> <note /> </trans-unit> <trans-unit id="ElementIsExpected"> <source>element is expected</source> <target state="translated">è previsto un elemento</target> <note /> </trans-unit> <trans-unit id="SeparatorIsExpected"> <source>separator is expected</source> <target state="translated">è previsto il separatore</target> <note /> </trans-unit> <trans-unit id="TheStreamCannotBeReadFrom"> <source>The stream cannot be read from.</source> <target state="translated">Non è possibile leggere dal flusso.</target> <note /> </trans-unit> <trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values"> <source>Deserialization reader for '{0}' read incorrect number of values.</source> <target state="translated">Il numero di valori letto dal lettore di deserializzazioni per '{0}' non è corretto.</target> <note /> </trans-unit> <trans-unit id="Stream_contains_invalid_data"> <source>Stream contains invalid data</source> <target state="translated">Il flusso contiene dati non validi</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticSpanReported"> <source>Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file.</source> <target state="translated">Il percorso di origine '{1}' della diagnostica restituita '{0}' è incluso nel file '{2}', che non è presente nel file specificato.</target> <note /> </trans-unit> <trans-unit id="ExceptionEnablingMulticoreJit"> <source>Warning: Could not enable multicore JIT due to exception: {0}.</source> <target state="translated">Avviso: non è stato possibile abilitare JIT multicore a causa dell'eccezione {0}.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CodeAnalysisResources.resx"> <body> <trans-unit id="A_language_name_cannot_be_specified_for_this_option"> <source>A language name cannot be specified for this option.</source> <target state="translated">Non è possibile specificare un nome di linguaggio per questa opzione.</target> <note /> </trans-unit> <trans-unit id="A_language_name_must_be_specified_for_this_option"> <source>A language name must be specified for this option.</source> <target state="translated">È necessario specificare un nome di linguaggio per questa opzione.</target> <note /> </trans-unit> <trans-unit id="AssemblyReferencesNetFramework"> <source>The assembly containing type '{0}' references .NET Framework, which is not supported.</source> <target state="translated">L'assembly che contiene il tipo '{0}' fa riferimento a .NET Framework, che non è supportato.</target> <note /> </trans-unit> <trans-unit id="ChangesMustBeWithinBoundsOfSourceText"> <source>Changes must be within bounds of SourceText</source> <target state="translated">Le modifiche devono rientrare nei limiti di SourceText</target> <note /> </trans-unit> <trans-unit id="ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging"> <source>Changing the version of an assembly reference is not allowed during debugging: '{0}' changed version to '{1}'.</source> <target state="translated">La modifica della versione di un riferimento ad assembly durante il debug non è consentita: '{0}' ha modificato la versione in '{1}'.</target> <note /> </trans-unit> <trans-unit id="CompilerAnalyzerThrowsDescription"> <source>Analyzer '{0}' threw the following exception: '{1}'.</source> <target state="translated">L'analizzatore '{0}' ha generato l'eccezione seguente: '{1}'.</target> <note /> </trans-unit> <trans-unit id="DisableAnalyzerDiagnosticsMessage"> <source>Suppress the following diagnostics to disable this analyzer: {0}</source> <target state="translated">Per disabilitare questo analizzatore, eliminare la diagnostica seguente: {0}</target> <note>{0}: Comma-separated list of diagnostic IDs</note> </trans-unit> <trans-unit id="HintNameInvalidChar"> <source>The hintName '{0}' contains an invalid character '{1}' at position {2}.</source> <target state="translated">L'elemento hintName '{0}' contiene un carattere non valido '{1}' alla posizione {2}.</target> <note>{0}: the provided hintname. {1}: the invalid character, {2} the position it occurred at</note> </trans-unit> <trans-unit id="HintNameUniquePerGenerator"> <source>The hintName '{0}' of the added source file must be unique within a generator.</source> <target state="translated">L'elemento hintName '{0}' del file di origine aggiunto deve essere univoco all'interno di un generatore.</target> <note>{0}: the provided hintname</note> </trans-unit> <trans-unit id="InvalidAdditionalFile"> <source>Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'.</source> <target state="translated">Il file aggiuntivo non appartiene all'oggetto 'CompilationWithAnalyzers' sottostante.</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticSuppressionReported"> <source>Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor.</source> <target state="translated">L'ID diagnostica '{0}' eliminato non corrisponde all'ID eliminabile '{1}' per il descrittore di eliminazione specificato.</target> <note /> </trans-unit> <trans-unit id="InvalidOperationBlockForAnalysisContext"> <source>Given operation block does not belong to the current analysis context.</source> <target state="translated">Il blocco operazioni specificato non appartiene al contesto di analisi corrente.</target> <note /> </trans-unit> <trans-unit id="IsSymbolAccessibleBadWithin"> <source>Parameter '{0}' must be an 'INamedTypeSymbol' or an 'IAssemblySymbol'.</source> <target state="translated">Il parametro '{0}' deve essere un elemento 'INamedTypeSymbol' o 'IAssemblySymbol'.</target> <note /> </trans-unit> <trans-unit id="IsSymbolAccessibleWrongAssembly"> <source>Parameter '{0}' must be a symbol from this compilation or some referenced assembly.</source> <target state="translated">Il parametro '{0}' deve essere un simbolo di questa compilazione oppure un qualsiasi assembly cui viene fatto riferimento.</target> <note /> </trans-unit> <trans-unit id="ModuleHasInvalidAttributes"> <source>Module has invalid attributes.</source> <target state="translated">Il modulo contiene attributi non validi.</target> <note /> </trans-unit> <trans-unit id="NonReportedDiagnosticCannotBeSuppressed"> <source>Non-reported diagnostic with ID '{0}' cannot be suppressed.</source> <target state="translated">Non è possibile eliminare la diagnostica non restituita con ID '{0}'.</target> <note /> </trans-unit> <trans-unit id="NotARootOperation"> <source>Given operation has a non-null parent.</source> <target state="translated">L'operazione specificata contiene un elemento padre non Null.</target> <note /> </trans-unit> <trans-unit id="OperationHasNullSemanticModel"> <source>Given operation has a null semantic model.</source> <target state="translated">L'operazione specificata contiene un modello semantico Null.</target> <note /> </trans-unit> <trans-unit id="OperationMustNotBeControlFlowGraphPart"> <source>The provided operation must not be part of a Control Flow Graph.</source> <target state="translated">L'operazione specificata non deve essere inclusa in un grafico del flusso di controllo.</target> <note /> </trans-unit> <trans-unit id="OutputKindNotSupported"> <source>Output kind not supported.</source> <target state="translated">Il tipo di output non è supportato.</target> <note /> </trans-unit> <trans-unit id="PathReturnedByResolveMetadataFileMustBeAbsolute"> <source>Path returned by {0}.ResolveMetadataFile must be absolute: '{1}'</source> <target state="translated">Il percorso restituito da {0}.ResolveMetadataFile deve essere assoluto: '{1}'</target> <note /> </trans-unit> <trans-unit id="AssemblyMustHaveAtLeastOneModule"> <source>Assembly must have at least one module.</source> <target state="translated">L'assembly deve contenere almeno un modulo.</target> <note /> </trans-unit> <trans-unit id="ModuleCopyCannotBeUsedToCreateAssemblyMetadata"> <source>Module copy can't be used to create an assembly metadata.</source> <target state="translated">Non è possibile usare la copia del modulo per creare i metadati di un assembly.</target> <note /> </trans-unit> <trans-unit id="Single_type_per_generator_0"> <source>Only a single {0} can be registered per generator.</source> <target state="translated">È possibile registrare solo un tipo {0} per generatore.</target> <note>{0}: type name</note> </trans-unit> <trans-unit id="SourceTextRequiresEncoding"> <source>The SourceText with hintName '{0}' must have an explicit encoding set.</source> <target state="translated">L'elemento SourceText con hintName '{0}' deve avere una codifica esplicita impostata.</target> <note>'SourceText' is not localizable. {0}: the provided hintname</note> </trans-unit> <trans-unit id="SupportedDiagnosticsHasNullDescriptor"> <source>Analyzer '{0}' contains a null descriptor in its 'SupportedDiagnostics'.</source> <target state="translated">L'analizzatore '{0}' contiene un descrittore Null nel relativo elemento 'SupportedDiagnostics'.</target> <note /> </trans-unit> <trans-unit id="SupportedSuppressionsHasNullDescriptor"> <source>Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'.</source> <target state="translated">L'analizzatore '{0}' contiene un descrittore Null nel relativo elemento 'SupportedSuppressions'.</target> <note /> </trans-unit> <trans-unit id="SuppressionDiagnosticDescriptorMessage"> <source>Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'</source> <target state="translated">La diagnostica '{0}: {1}' è stata eliminata a livello di codice da un elemento DiagnosticSuppressor con ID eliminazione '{2}' e giustificazione '{3}'</target> <note /> </trans-unit> <trans-unit id="SuppressionDiagnosticDescriptorTitle"> <source>Programmatic suppression of an analyzer diagnostic</source> <target state="translated">Eliminazione a livello di codice di una diagnostica dell'analizzatore</target> <note /> </trans-unit> <trans-unit id="SuppressionIdCantBeNullOrWhitespace"> <source>A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</source> <target state="translated">L'ID di un elemento SuppressionDescriptor non deve essere Null, né una stringa vuota o una stringa composta solo da spazi vuoti.</target> <note /> </trans-unit> <trans-unit id="TupleElementNullableAnnotationCountMismatch"> <source>If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple.</source> <target state="translated">Se si specificano annotazioni nullable di elementi di tupla, il numero delle annotazioni deve corrispondere alla cardinalità della tupla.</target> <note /> </trans-unit> <trans-unit id="UnableToDetermineSpecificCauseOfFailure"> <source>Unable to determine specific cause of the failure.</source> <target state="translated">Non è possibile determinare la causa specifica dell'errore.</target> <note /> </trans-unit> <trans-unit id="Unresolved"> <source>Unresolved: </source> <target state="translated">Non risolto: </target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>assembly</source> <target state="translated">assembly</target> <note /> </trans-unit> <trans-unit id="Class1"> <source>class</source> <target state="translated">classe</target> <note /> </trans-unit> <trans-unit id="Constructor"> <source>constructor</source> <target state="translated">costruttore</target> <note /> </trans-unit> <trans-unit id="Delegate1"> <source>delegate</source> <target state="translated">delegato</target> <note /> </trans-unit> <trans-unit id="Enum1"> <source>enum</source> <target state="translated">enumerazione</target> <note /> </trans-unit> <trans-unit id="Event1"> <source>event</source> <target state="translated">evento</target> <note /> </trans-unit> <trans-unit id="Field"> <source>field</source> <target state="translated">campo</target> <note /> </trans-unit> <trans-unit id="TypeParameter"> <source>type parameter</source> <target state="translated">parametro di tipo</target> <note /> </trans-unit> <trans-unit id="Interface1"> <source>interface</source> <target state="translated">interfaccia</target> <note /> </trans-unit> <trans-unit id="Method"> <source>method</source> <target state="translated">metodo</target> <note /> </trans-unit> <trans-unit id="Module"> <source>module</source> <target state="translated">modulo</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>parameter</source> <target state="translated">parametro</target> <note /> </trans-unit> <trans-unit id="Property"> <source>property, indexer</source> <target state="translated">proprietà, indicizzatore</target> <note /> </trans-unit> <trans-unit id="Return1"> <source>return</source> <target state="translated">valore restituito</target> <note /> </trans-unit> <trans-unit id="Struct1"> <source>struct</source> <target state="translated">struct</target> <note /> </trans-unit> <trans-unit id="CannotCreateReferenceToSubmission"> <source>Can't create a reference to a submission.</source> <target state="translated">Non è possibile creare un riferimento a un invio.</target> <note /> </trans-unit> <trans-unit id="CannotCreateReferenceToModule"> <source>Can't create a reference to a module.</source> <target state="translated">Non è possibile creare un riferimento a un modulo.</target> <note /> </trans-unit> <trans-unit id="InMemoryAssembly"> <source>&lt;in-memory assembly&gt;</source> <target state="translated">&lt;assembly in memoria&gt;</target> <note /> </trans-unit> <trans-unit id="InMemoryModule"> <source>&lt;in-memory module&gt;</source> <target state="translated">&lt;modulo in memoria&gt;</target> <note /> </trans-unit> <trans-unit id="SizeHasToBePositive"> <source>Size has to be positive.</source> <target state="translated">Il valore delle dimensioni deve essere positivo.</target> <note /> </trans-unit> <trans-unit id="AssemblyFileNotFound"> <source>Assembly file not found</source> <target state="translated">Il file di assembly non è stato trovato</target> <note /> </trans-unit> <trans-unit id="CannotEmbedInteropTypesFromModule"> <source>Can't embed interop types from module.</source> <target state="translated">Non è possibile incorporare tipi di interoperabilità dal modulo.</target> <note /> </trans-unit> <trans-unit id="CannotAliasModule"> <source>Can't alias a module.</source> <target state="translated">Non è possibile creare l'alias di un modulo.</target> <note /> </trans-unit> <trans-unit id="InvalidAlias"> <source>Invalid alias.</source> <target state="translated">L'alias non è valido.</target> <note /> </trans-unit> <trans-unit id="GetMetadataMustReturnInstance"> <source>{0}.GetMetadata() must return an instance of {1}.</source> <target state="translated">{0}.GetMetadata() deve restituire un'istanza di {1}.</target> <note /> </trans-unit> <trans-unit id="UnsupportedSuppressionReported"> <source>Reported suppression with ID '{0}' is not supported by the suppressor.</source> <target state="translated">L'eliminazione restituita con ID '{0}' non è supportata dall'elemento di eliminazione.</target> <note /> </trans-unit> <trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"> <source>Value too large to be represented as a 30 bit unsigned integer.</source> <target state="translated">Il valore è troppo grande per essere rappresentato come intero senza segno a 30 bit.</target> <note /> </trans-unit> <trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized"> <source>Arrays with more than one dimension cannot be serialized.</source> <target state="translated">Non è possibile serializzare le matrice con più di una dimensione.</target> <note /> </trans-unit> <trans-unit id="InvalidAssemblyName"> <source>Invalid assembly name: '{0}'</source> <target state="translated">Il nome dell'assembly '{0}' non è valido</target> <note /> </trans-unit> <trans-unit id="AbsolutePathExpected"> <source>Absolute path expected.</source> <target state="translated">È previsto il percorso assoluto.</target> <note /> </trans-unit> <trans-unit id="EmptyKeyInPathMap"> <source>A key in the pathMap is empty.</source> <target state="translated">Una chiave in pathMap è vuota.</target> <note /> </trans-unit> <trans-unit id="NullValueInPathMap"> <source>A value in the pathMap is null.</source> <target state="translated">Un valore in pathMap è Null.</target> <note /> </trans-unit> <trans-unit id="CompilationOptionsMustNotHaveErrors"> <source>Compilation options must not have errors.</source> <target state="translated">Le opzioni di compilazione non devono contenere errori.</target> <note /> </trans-unit> <trans-unit id="ReturnTypeCannotBeValuePointerbyRefOrOpen"> <source>Return type can't be a value type, pointer, by-ref or open generic type</source> <target state="translated">Il tipo restituito non può essere un tipo valore, un puntatore, un tipo generico open o by-ref</target> <note /> </trans-unit> <trans-unit id="ReturnTypeCannotBeVoidByRefOrOpen"> <source>Return type can't be void, by-ref or open generic type</source> <target state="translated">Il tipo restituito non può essere nullo, un tipo generico open o by-ref</target> <note /> </trans-unit> <trans-unit id="TypeMustBeSameAsHostObjectTypeOfPreviousSubmission"> <source>Type must be same as host object type of previous submission.</source> <target state="translated">Il tipo deve essere uguale al tipo di oggetto host dell'invio precedente.</target> <note /> </trans-unit> <trans-unit id="PreviousSubmissionHasErrors"> <source>Previous submission has errors.</source> <target state="translated">L'invio precedente contiene errori.</target> <note /> </trans-unit> <trans-unit id="InvalidOutputKindForSubmission"> <source>Invalid output kind for submission. DynamicallyLinkedLibrary expected.</source> <target state="translated">Il tipo di output per l'invio non è valido. È previsto DynamicallyLinkedLibrary.</target> <note /> </trans-unit> <trans-unit id="InvalidCompilationOptions"> <source>Invalid compilation options -- submission can't be signed.</source> <target state="translated">Opzioni di compilazione non valide. Non è possibile firmare l'invio.</target> <note /> </trans-unit> <trans-unit id="ResourceStreamProviderShouldReturnNonNullStream"> <source>Resource stream provider should return non-null stream.</source> <target state="translated">Il provider di flusso della risorsa deve restituire un flusso non Null.</target> <note /> </trans-unit> <trans-unit id="ReferenceResolverShouldReturnReadableNonNullStream"> <source>Reference resolver should return readable non-null stream.</source> <target state="translated">Il resolver di riferimenti deve restituire un flusso non Null leggibile.</target> <note /> </trans-unit> <trans-unit id="EmptyOrInvalidResourceName"> <source>Empty or invalid resource name</source> <target state="translated">Nome di risorsa vuoto o non valido</target> <note /> </trans-unit> <trans-unit id="EmptyOrInvalidFileName"> <source>Empty or invalid file name</source> <target state="translated">Nome di file vuoto o non valido</target> <note /> </trans-unit> <trans-unit id="ResourceDataProviderShouldReturnNonNullStream"> <source>Resource data provider should return non-null stream</source> <target state="translated">Il provider di dati della risorsa deve restituire un flusso non Null</target> <note /> </trans-unit> <trans-unit id="FileNotFound"> <source>File not found.</source> <target state="translated">Il file non è stato trovato.</target> <note /> </trans-unit> <trans-unit id="PathReturnedByResolveStrongNameKeyFileMustBeAbsolute"> <source>Path returned by {0}.ResolveStrongNameKeyFile must be absolute: '{1}'</source> <target state="translated">Il percorso restituito da {0}.ResolveStrongNameKeyFile deve essere assoluto: '{1}'</target> <note /> </trans-unit> <trans-unit id="TypeMustBeASubclassOfSyntaxAnnotation"> <source>type must be a subclass of SyntaxAnnotation.</source> <target state="translated">il tipo deve essere una sottoclasse di SyntaxAnnotation.</target> <note /> </trans-unit> <trans-unit id="InvalidModuleName"> <source>Invalid module name specified in metadata module '{0}': '{1}'</source> <target state="translated">È stato specificato un nome di modulo non valido nel modulo dei metadati '{0}': '{1}'</target> <note /> </trans-unit> <trans-unit id="FileSizeExceedsMaximumAllowed"> <source>File size exceeds maximum allowed size of a valid metadata file.</source> <target state="translated">Le dimensioni del file superano quelle massime consentite per un file di metadati valido.</target> <note /> </trans-unit> <trans-unit id="NameCannotBeNull"> <source>Name cannot be null.</source> <target state="translated">Il nome non può essere Null.</target> <note /> </trans-unit> <trans-unit id="NameCannotBeEmpty"> <source>Name cannot be empty.</source> <target state="translated">Il nome non può essere vuoto.</target> <note /> </trans-unit> <trans-unit id="NameCannotStartWithWhitespace"> <source>Name cannot start with whitespace.</source> <target state="translated">Il nome non può iniziare con uno spazio vuoto.</target> <note /> </trans-unit> <trans-unit id="NameContainsInvalidCharacter"> <source>Name contains invalid characters.</source> <target state="translated">Il nome contiene caratteri non validi.</target> <note /> </trans-unit> <trans-unit id="SpanDoesNotIncludeStartOfLine"> <source>The span does not include the start of a line.</source> <target state="translated">L'elemento span non include l'inizio di una riga.</target> <note /> </trans-unit> <trans-unit id="SpanDoesNotIncludeEndOfLine"> <source>The span does not include the end of a line.</source> <target state="translated">L'elemento span non include la fine di una riga.</target> <note /> </trans-unit> <trans-unit id="StartMustNotBeNegative"> <source>'start' must not be negative</source> <target state="translated">'start' non deve essere negativo</target> <note /> </trans-unit> <trans-unit id="EndMustNotBeLessThanStart"> <source>'end' must not be less than 'start'</source> <target state="translated">'il valore di 'end' deve essere minore di quello di 'start'</target> <note /> </trans-unit> <trans-unit id="InvalidContentType"> <source>Invalid content type</source> <target state="translated">Il tipo di contenuto non è valido</target> <note /> </trans-unit> <trans-unit id="ExpectedNonEmptyPublicKey"> <source>Expected non-empty public key</source> <target state="translated">È prevista una chiave pubblica non vuota</target> <note /> </trans-unit> <trans-unit id="InvalidSizeOfPublicKeyToken"> <source>Invalid size of public key token.</source> <target state="translated">La dimensione del token di chiave pubblica non è valida.</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyName"> <source>Invalid characters in assembly name</source> <target state="translated">Caratteri non validi nel nome dell'assembly</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyCultureName"> <source>Invalid characters in assembly culture name</source> <target state="translated">Caratteri non validi nel nome delle impostazioni cultura dell'assembly</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportReadAndSeek"> <source>Stream must support read and seek operations.</source> <target state="translated">Il flusso deve supportare operazioni di lettura e ricerca.</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportRead"> <source>Stream must be readable.</source> <target state="translated">Il flusso deve essere leggibile.</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportWrite"> <source>Stream must be writable.</source> <target state="translated">Il flusso deve essere scrivibile.</target> <note /> </trans-unit> <trans-unit id="PdbStreamUnexpectedWhenEmbedding"> <source>PDB stream should not be given when embedding PDB into the PE stream.</source> <target state="translated">È consigliabile non specificare il flusso PDB quando si incorpora PDB nel flusso PE.</target> <note /> </trans-unit> <trans-unit id="PdbStreamUnexpectedWhenEmittingMetadataOnly"> <source>PDB stream should not be given when emitting metadata only.</source> <target state="translated">È consigliabile non specificare il flusso PDB quando si creano solo metadati.</target> <note /> </trans-unit> <trans-unit id="MetadataPeStreamUnexpectedWhenEmittingMetadataOnly"> <source>Metadata PE stream should not be given when emitting metadata only.</source> <target state="translated">È consigliabile non specificare il flusso PE dei metadati quando si creano solo metadati.</target> <note /> </trans-unit> <trans-unit id="IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream"> <source>Including private members should not be used when emitting to the secondary assembly output.</source> <target state="translated">È consigliabile non usare membri privati di inclusione quando si crea l'output secondario dell'assembly.</target> <note /> </trans-unit> <trans-unit id="MustIncludePrivateMembersUnlessRefAssembly"> <source>Must include private members unless emitting a ref assembly.</source> <target state="translated">Deve includere membri privati a meno che non si stia creando un assembly di riferimento.</target> <note /> </trans-unit> <trans-unit id="EmbeddingPdbUnexpectedWhenEmittingMetadata"> <source>Embedding PDB is not allowed when emitting metadata.</source> <target state="translated">L'incorporamento di PDB non è consentito quando si creano metadati.</target> <note /> </trans-unit> <trans-unit id="CannotTargetNetModuleWhenEmittingRefAssembly"> <source>Cannot target net module when emitting ref assembly.</source> <target state="translated">Non è possibile impostare come destinazione il modulo quando si crea l'assembly di riferimento.</target> <note /> </trans-unit> <trans-unit id="InvalidHash"> <source>Invalid hash.</source> <target state="translated">Hash non valido.</target> <note /> </trans-unit> <trans-unit id="UnsupportedHashAlgorithm"> <source>Unsupported hash algorithm.</source> <target state="translated">L'algoritmo hash non è supportato.</target> <note /> </trans-unit> <trans-unit id="InconsistentLanguageVersions"> <source>Inconsistent language versions</source> <target state="translated">Versioni incoerenti del linguaggio</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidRelocation"> <source>Win32 resources, assumed to be in COFF object format, have one or more invalid relocation header values.</source> <target state="translated">Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno uno o più valori di intestazione di rilocazione non validi.</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidSectionSize"> <source>Win32 resources, assumed to be in COFF object format, have an invalid section size.</source> <target state="translated">Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno una dimensione di sezione non valida.</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidSymbol"> <source>Win32 resources, assumed to be in COFF object format, have one or more invalid symbol values.</source> <target state="translated">Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno uno o più valori di simbolo non validi.</target> <note /> </trans-unit> <trans-unit id="CoffResourceMissingSection"> <source>Win32 resources, assumed to be in COFF object format, are missing one or both of sections '.rsrc$01' and '.rsrc$02'</source> <target state="translated">Nelle risorse Win32, che dovrebbero essere nel formato oggetto COFF, mancano una o entrambe le sezioni '.rsrc$01' e '.rsrc$02'</target> <note /> </trans-unit> <trans-unit id="IconStreamUnexpectedFormat"> <source>Icon stream is not in the expected format.</source> <target state="translated">Il formato del flusso dell'icona non è corretto.</target> <note /> </trans-unit> <trans-unit id="InvalidCultureName"> <source>Invalid culture name: '{0}'</source> <target state="translated">Il nome delle impostazioni cultura '{0}' non è valido</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidGlobalSectionName"> <source>Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}'</source> <target state="translated">Il nome della sezione '{0}' di configurazione dell'analizzatore globale non è valido perché non è un percorso assoluto. La sezione verrà ignorata. La sezione è stata dichiarata nel file: '{1}'</target> <note>{0}: invalid section name, {1} path to global config</note> </trans-unit> <trans-unit id="WRN_InvalidGlobalSectionName_Title"> <source>Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored.</source> <target state="translated">Il nome della sezione di configurazione dell'analizzatore globale non è valido perché non è un percorso assoluto. La sezione verrà ignorata.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSeverityInAnalyzerConfig"> <source>The diagnostic '{0}' was given an invalid severity '{1}' in the analyzer config file at '{2}'.</source> <target state="translated">Alla diagnostica ' {0}' è stato assegnato un livello di gravità non valido '{1}' nel file di configurazione dell'analizzatore alla posizione '{2}'.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSeverityInAnalyzerConfig_Title"> <source>Invalid severity in analyzer config file.</source> <target state="translated">Gravità non valida nel file di configurazione dell'analizzatore.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleGlobalAnalyzerKeys"> <source>Multiple global analyzer config files set the same key '{0}' in section '{1}'. It has been unset. Key was set by the following files: '{2}'</source> <target state="translated">Più file di configurazione dell'analizzatore globale impostano la stessa chiave '{0}' nella sezione '{1}'. L'impostazione è stata annullata. La chiave è stata impostata dai file seguenti: '{2}'</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleGlobalAnalyzerKeys_Title"> <source>Multiple global analyzer config files set the same key. It has been unset.</source> <target state="translated">Più file di configurazione dell'analizzatore globale impostano la stessa chiave. L'impostazione è stata annullata.</target> <note /> </trans-unit> <trans-unit id="WinRTIdentityCantBeRetargetable"> <source>WindowsRuntime identity can't be retargetable</source> <target state="translated">Non è possibile ridefinire la destinazione dell'identità WindowsRuntime</target> <note /> </trans-unit> <trans-unit id="PEImageNotAvailable"> <source>PE image not available.</source> <target state="translated">L'immagine PE non è disponibile.</target> <note /> </trans-unit> <trans-unit id="AssemblySigningNotSupported"> <source>Assembly signing not supported.</source> <target state="translated">La firma dell'assembly non è supportata.</target> <note /> </trans-unit> <trans-unit id="XmlReferencesNotSupported"> <source>References to XML documents are not supported.</source> <target state="translated">I riferimenti ai documenti XML non sono supportati.</target> <note /> </trans-unit> <trans-unit id="FailedToResolveRuleSetName"> <source>Could not locate the rule set file '{0}'.</source> <target state="translated">Non è stato possibile individuare il file del set di regole '{0}'.</target> <note /> </trans-unit> <trans-unit id="InvalidRuleSetInclude"> <source>An error occurred while loading the included rule set file {0} - {1}</source> <target state="translated">Si è verificato un errore durante il caricamento del file del set di regole incluso {0} - {1}</target> <note /> </trans-unit> <trans-unit id="CompilerAnalyzerFailure"> <source>Analyzer Failure</source> <target state="translated">Errore dell'analizzatore</target> <note>{0}: Analyzer name {1}: Type name {2}: Localized exception message {3}: Localized detail message</note> </trans-unit> <trans-unit id="CompilerAnalyzerThrows"> <source>Analyzer '{0}' threw an exception of type '{1}' with message '{2}'. {3}</source> <target state="translated">L'analizzatore '{0}' ha generato un'eccezione di tipo '{1}'. Messaggio: '{2}'. {3}</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverFailure"> <source>Analyzer Driver Failure</source> <target state="translated">Errore del driver dell'analizzatore</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverThrows"> <source>Analyzer driver threw an exception of type '{0}' with message '{1}'.</source> <target state="translated">Il driver dell'analizzatore ha generato un'eccezione di tipo '{0}'. Messaggio: '{1}'.</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverThrowsDescription"> <source>Analyzer driver threw the following exception: '{0}'.</source> <target state="translated">Il driver dell'analizzatore ha generato l'eccezione seguente: '{0}'.</target> <note /> </trans-unit> <trans-unit id="PEImageDoesntContainManagedMetadata"> <source>PE image doesn't contain managed metadata.</source> <target state="translated">L'immagine PE non contiene metadati gestiti.</target> <note /> </trans-unit> <trans-unit id="ChangesMustNotOverlap"> <source>The changes must not overlap.</source> <target state="translated">Le modifiche devono essere ordinate e non sovrapposte.</target> <note /> </trans-unit> <trans-unit id="DiagnosticIdCantBeNullOrWhitespace"> <source>A DiagnosticDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</source> <target state="translated">L'ID di un elemento DiagnosticDescriptor non deve essere Null, né una stringa vuota o una stringa composta solo da spazi vuoti.</target> <note /> </trans-unit> <trans-unit id="RuleSetHasDuplicateRules"> <source>The rule set file has duplicate rules for '{0}' with differing actions '{1}' and '{2}'.</source> <target state="translated">Il file del set di regole contiene regole duplicate per '{0}' con azioni '{1}' e '{2}' diverse.</target> <note /> </trans-unit> <trans-unit id="CantCreateModuleReferenceToAssembly"> <source>Can't create a module reference to an assembly.</source> <target state="translated">Non è possibile creare un riferimento del modulo a un assembly.</target> <note /> </trans-unit> <trans-unit id="CantCreateReferenceToDynamicAssembly"> <source>Can't create a metadata reference to a dynamic assembly.</source> <target state="translated">Non è possibile creare un riferimento dei metadati a un assembly dinamico.</target> <note /> </trans-unit> <trans-unit id="CantCreateReferenceToAssemblyWithoutLocation"> <source>Can't create a metadata reference to an assembly without location.</source> <target state="translated">Non è possibile creare un riferimento dei metadati a un assembly senza percorso.</target> <note /> </trans-unit> <trans-unit id="ArgumentCannotBeEmpty"> <source>Argument cannot be empty.</source> <target state="translated">L'argomento non può essere vuoto.</target> <note /> </trans-unit> <trans-unit id="ArgumentElementCannotBeNull"> <source>Argument cannot have a null element.</source> <target state="translated">L'argomento non può contenere un elemento Null.</target> <note /> </trans-unit> <trans-unit id="UnsupportedDiagnosticReported"> <source>Reported diagnostic with ID '{0}' is not supported by the analyzer.</source> <target state="translated">La diagnostica restituita con ID '{0}' non è supportata dall'analizzatore.</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticIdReported"> <source>Reported diagnostic has an ID '{0}', which is not a valid identifier.</source> <target state="translated">L'ID della diagnostica restituita è '{0}', che non è un identificatore valido.</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticLocationReported"> <source>Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed.</source> <target state="translated">Il percorso di origine della diagnostica restituita '{0}' è incluso nel file '{1}', che non fa parte della compilazione da analizzare.</target> <note /> </trans-unit> <trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder"> <source>The type '{0}' is not understood by the serialization binder.</source> <target state="translated">Il tipo '{0}' non è riconosciuto dal binder di serializzazioni.</target> <note /> </trans-unit> <trans-unit id="Cannot_deserialize_type_0"> <source>Cannot deserialize type '{0}'.</source> <target state="translated">Non è possibile deserializzare il tipo '{0}'.</target> <note /> </trans-unit> <trans-unit id="Cannot_serialize_type_0"> <source>Cannot serialize type '{0}'.</source> <target state="translated">Non è possibile serializzare il tipo '{0}'.</target> <note /> </trans-unit> <trans-unit id="InvalidNodeToTrack"> <source>Node to track is not a descendant of the root.</source> <target state="translated">Il nodo da tracciare non è un discendente della radice.</target> <note /> </trans-unit> <trans-unit id="NodeOrTokenOutOfSequence"> <source>A node or token is out of sequence.</source> <target state="translated">Un nodo o token è fuori sequenza.</target> <note /> </trans-unit> <trans-unit id="UnexpectedTypeOfNodeInList"> <source>A node in the list is not of the expected type.</source> <target state="translated">Un nodo nell'elenco non è del tipo previsto.</target> <note /> </trans-unit> <trans-unit id="MissingListItem"> <source>The item specified is not the element of a list.</source> <target state="translated">L'elemento specificato non è l'elemento di un elenco.</target> <note /> </trans-unit> <trans-unit id="InvalidPublicKey"> <source>Invalid public key.</source> <target state="translated">Chiave pubblica non valida.</target> <note /> </trans-unit> <trans-unit id="InvalidPublicKeyToken"> <source>Invalid public key token.</source> <target state="translated">Token di chiave pubblica non valido.</target> <note /> </trans-unit> <trans-unit id="InvalidDataAtOffset"> <source>Invalid data at offset {0}: {1}{2}*{3}{4}</source> <target state="translated">Dati non validi in corrispondenza dell'offset {0}: {1}{2}*{3}{4}</target> <note /> </trans-unit> <trans-unit id="SymWriterNotDeterministic"> <source>Windows PDB writer doesn't support deterministic compilation: '{0}'</source> <target state="translated">Il writer PDB di Windows non supporta la compilazione deterministica: '{0}'</target> <note /> </trans-unit> <trans-unit id="SymWriterOlderVersionThanRequired"> <source>The version of Windows PDB writer is older than required: '{0}'</source> <target state="translated">La versione del writer PDB di Windows è meno recente di quella richiesta: '{0}'</target> <note /> </trans-unit> <trans-unit id="SymWriterDoesNotSupportSourceLink"> <source>Windows PDB writer doesn't support SourceLink feature: '{0}'</source> <target state="translated">Il writer PDB di Windows non supporta la funzionalità SourceLink: '{0}'</target> <note /> </trans-unit> <trans-unit id="RuleSetBadAttributeValue"> <source>The attribute {0} has an invalid value of {1}.</source> <target state="translated">Il valore {1} dell'attributo {0} non è valido.</target> <note /> </trans-unit> <trans-unit id="RuleSetMissingAttribute"> <source>The element {0} is missing an attribute named {1}.</source> <target state="translated">Nell'elemento {0} manca un attributo denominato {1}.</target> <note /> </trans-unit> <trans-unit id="KeepAliveIsNotAnInteger"> <source>Argument to '/keepalive' option is not a 32-bit integer.</source> <target state="translated">L'argomento dell'opzione '/keepalive' non è un intero a 32 bit.</target> <note /> </trans-unit> <trans-unit id="KeepAliveIsTooSmall"> <source>Arguments to '/keepalive' option below -1 are invalid.</source> <target state="translated">Gli argomenti dell'opzione '/keepalive' il cui valore è inferiore a -1 non sono validi.</target> <note /> </trans-unit> <trans-unit id="KeepAliveWithoutShared"> <source>'/keepalive' option is only valid with '/shared' option.</source> <target state="translated">'L'opzione '/keepalive' è valida solo con l'opzione '/shared'.</target> <note /> </trans-unit> <trans-unit id="MismatchedVersion"> <source>Roslyn compiler server reports different protocol version than build task.</source> <target state="translated">Il server del compilatore Roslyn restituisce una versione del protocollo diversa da quella dell'attività di compilazione.</target> <note /> </trans-unit> <trans-unit id="MissingKeepAlive"> <source>Missing argument for '/keepalive' option.</source> <target state="translated">Manca l'argomento per l'opzione '/keepalive'.</target> <note /> </trans-unit> <trans-unit id="AnalyzerTotalExecutionTime"> <source>Total analyzer execution time: {0} seconds.</source> <target state="translated">Tempo totale di esecuzione dell'analizzatore: {0} secondi.</target> <note /> </trans-unit> <trans-unit id="MultithreadedAnalyzerExecutionNote"> <source>NOTE: Elapsed time may be less than analyzer execution time because analyzers can run concurrently.</source> <target state="translated">NOTE: il tempo trascorso può essere inferiore al tempo di esecuzione dell'analizzatore perché non è possibile eseguire gli analizzatori simultaneamente.</target> <note /> </trans-unit> <trans-unit id="AnalyzerExecutionTimeColumnHeader"> <source>Time (s)</source> <target state="translated">Tempo (s)</target> <note /> </trans-unit> <trans-unit id="AnalyzerNameColumnHeader"> <source>Analyzer</source> <target state="translated">Analizzatore</target> <note /> </trans-unit> <trans-unit id="NoAnalyzersFound"> <source>No analyzers found</source> <target state="translated">Non sono stati trovati analizzatori</target> <note /> </trans-unit> <trans-unit id="DuplicateAnalyzerInstances"> <source>Argument contains duplicate analyzer instances.</source> <target state="translated">L'argomento contiene istanze duplicate dell'analizzatore.</target> <note /> </trans-unit> <trans-unit id="UnsupportedAnalyzerInstance"> <source>Argument contains an analyzer instance that does not belong to the 'Analyzers' for this CompilationWithAnalyzers instance.</source> <target state="translated">L'argomento contiene un'istanza dell'analizzatore che non appartiene all'elemento 'Analyzers' per questa istanza di CompilationWithAnalyzers.</target> <note /> </trans-unit> <trans-unit id="InvalidTree"> <source>Syntax tree doesn't belong to the underlying 'Compilation'.</source> <target state="translated">L'albero sintattico non appartiene all'elemento 'Compilation' sottostante.</target> <note /> </trans-unit> <trans-unit id="ResourceStreamEndedUnexpectedly"> <source>Resource stream ended at {0} bytes, expected {1} bytes.</source> <target state="translated">Il flusso della risorsa è terminato a {0} byte, mentre era previsto a {1} byte.</target> <note /> </trans-unit> <trans-unit id="SharedArgumentMissing"> <source>Value for argument '/shared:' must not be empty</source> <target state="translated">Il valore dell'argomento '/shared:' non deve essere vuoto</target> <note /> </trans-unit> <trans-unit id="ExceptionContext"> <source>Exception occurred with following context: {0}</source> <target state="translated">Si è verificata un'eccezione con il contesto seguente: {0}</target> <note /> </trans-unit> <trans-unit id="AnonymousTypeMemberAndNamesCountMismatch2"> <source>{0} and {1} must have the same length.</source> <target state="translated">{0} e {1} devono avere la stessa lunghezza.</target> <note /> </trans-unit> <trans-unit id="AnonymousTypeArgumentCountMismatch2"> <source>{0} must either be 'default' or have the same length as {1}.</source> <target state="translated">{0} deve essere 'default' o avere la stessa lunghezza di {1}.</target> <note /> </trans-unit> <trans-unit id="InconsistentSyntaxTreeFeature"> <source>Inconsistent syntax tree features</source> <target state="translated">Funzionalità incoerenti dell'albero della sintassi</target> <note /> </trans-unit> <trans-unit id="ReferenceOfTypeIsInvalid1"> <source>Reference of type '{0}' is not valid for this compilation.</source> <target state="translated">Il riferimento di tipo '{0}' non è valido per questa compilazione.</target> <note /> </trans-unit> <trans-unit id="MetadataRefNotFoundToRemove1"> <source>MetadataReference '{0}' not found to remove.</source> <target state="translated">Non è stato trovato nessun elemento MetadataReference '{0}' da rimuovere.</target> <note /> </trans-unit> <trans-unit id="TupleElementNameCountMismatch"> <source>If tuple element names are specified, the number of element names must match the cardinality of the tuple.</source> <target state="translated">Se si specificano nomi di elementi di tupla, il numero dei nomi di elementi deve corrispondere alla cardinalità della tupla.</target> <note /> </trans-unit> <trans-unit id="TupleElementNameEmpty"> <source>Tuple element name cannot be an empty string.</source> <target state="translated">Il nome di elemento di tupla non può essere una stringa vuota.</target> <note /> </trans-unit> <trans-unit id="TupleElementLocationCountMismatch"> <source>If tuple element locations are specified, the number of locations must match the cardinality of the tuple.</source> <target state="translated">Se si specificano percorsi di elementi di tupla, il numero dei percorsi deve corrispondere alla cardinalità della tupla.</target> <note /> </trans-unit> <trans-unit id="TuplesNeedAtLeastTwoElements"> <source>Tuples must have at least two elements.</source> <target state="translated">Le tuple devono contenere almeno due elementi.</target> <note /> </trans-unit> <trans-unit id="CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion"> <source>The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers.</source> <target state="translated">La compilazione fa riferimento a più assembly le cui versioni differiscono solo nei numeri di revisione e/o di build generati automaticamente.</target> <note /> </trans-unit> <trans-unit id="TupleUnderlyingTypeMustBeTupleCompatible"> <source>The underlying type for a tuple must be tuple-compatible.</source> <target state="translated">Il tipo sottostante di una tupla deve essere compatibile con la tupla.</target> <note /> </trans-unit> <trans-unit id="UnrecognizedResourceFileFormat"> <source>Unrecognized resource file format.</source> <target state="translated">Il formato del file di risorse non è riconosciuto.</target> <note /> </trans-unit> <trans-unit id="SourceTextCannotBeEmbedded"> <source>SourceText cannot be embedded. Provide encoding or canBeEmbedded=true at construction.</source> <target state="translated">Non è possibile incorporare SourceText. Specificare la codifica oppure canBeEmbedded=true in fase di costruzione.</target> <note /> </trans-unit> <trans-unit id="StreamIsTooLong"> <source>Stream is too long.</source> <target state="translated">Il flusso è troppo lungo.</target> <note /> </trans-unit> <trans-unit id="EmbeddedTextsRequirePdb"> <source>Embedded texts are only supported when emitting a PDB.</source> <target state="translated">I testi incorporati sono supportati solo quando si crea un file PDB.</target> <note /> </trans-unit> <trans-unit id="TheStreamCannotBeWrittenTo"> <source>The stream cannot be written to.</source> <target state="translated">Non è possibile scrivere nel flusso.</target> <note /> </trans-unit> <trans-unit id="ElementIsExpected"> <source>element is expected</source> <target state="translated">è previsto un elemento</target> <note /> </trans-unit> <trans-unit id="SeparatorIsExpected"> <source>separator is expected</source> <target state="translated">è previsto il separatore</target> <note /> </trans-unit> <trans-unit id="TheStreamCannotBeReadFrom"> <source>The stream cannot be read from.</source> <target state="translated">Non è possibile leggere dal flusso.</target> <note /> </trans-unit> <trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values"> <source>Deserialization reader for '{0}' read incorrect number of values.</source> <target state="translated">Il numero di valori letto dal lettore di deserializzazioni per '{0}' non è corretto.</target> <note /> </trans-unit> <trans-unit id="Stream_contains_invalid_data"> <source>Stream contains invalid data</source> <target state="translated">Il flusso contiene dati non validi</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticSpanReported"> <source>Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file.</source> <target state="translated">Il percorso di origine '{1}' della diagnostica restituita '{0}' è incluso nel file '{2}', che non è presente nel file specificato.</target> <note /> </trans-unit> <trans-unit id="ExceptionEnablingMulticoreJit"> <source>Warning: Could not enable multicore JIT due to exception: {0}.</source> <target state="translated">Avviso: non è stato possibile abilitare JIT multicore a causa dell'eccezione {0}.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Interactive/Host/xlf/InteractiveHostResources.tr.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="tr" original="../InteractiveHostResources.resx"> <body> <trans-unit id="Attempt_to_connect_to_process_Sharp_0_failed_retrying"> <source>Attempt to connect to process #{0} failed, retrying ...</source> <target state="translated">#{0} işlemine bağlanma girişimi başarısız oldu, yeniden deneniyor...</target> <note /> </trans-unit> <trans-unit id="Cannot_resolve_reference_0"> <source>Cannot resolve reference '{0}'.</source> <target state="translated">'{0}' başvurusu çözümlenemiyor.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_a_remote_process_for_interactive_code_execution"> <source>Failed to create a remote process for interactive code execution: '{0}'</source> <target state="translated">Etkileşimli kod yürütme için uzak işlem oluşturulamadı: '{0}'</target> <note /> </trans-unit> <trans-unit id="Failed_to_initialize_remote_interactive_process"> <source>Failed to initialize remote interactive process.</source> <target state="translated">Uzak etkileşimli işlem başlatılamadı.</target> <note /> </trans-unit> <trans-unit id="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon"> <source>Failed to launch '{0}' process (exit code: {1}) with output: </source> <target state="translated">'{0}' işlemi (çıkış kodu: {1}) çıkış ile başlatılamadı: </target> <note /> </trans-unit> <trans-unit id="Hosting_process_exited_with_exit_code_0"> <source>Hosting process exited with exit code {0}.</source> <target state="translated">Barındırma işlemi {0} çıkış koduyla çıkış yaptı.</target> <note /> </trans-unit> <trans-unit id="Interactive_Host_not_initialized"> <source>Interactive Host not initialized.</source> <target state="translated">Etkileşimli Konak başlatılmadı.</target> <note /> </trans-unit> <trans-unit id="Loading_context_from_0"> <source>Loading context from '{0}'.</source> <target state="translated">'{0}' üzerinden bağlam yükleniyor.</target> <note /> </trans-unit> <trans-unit id="Searched_in_directories_colon"> <source>Searched in directories:</source> <target state="translated">Dizinlerde arandı:</target> <note /> </trans-unit> <trans-unit id="Searched_in_directory_colon"> <source>Searched in directory:</source> <target state="translated">Dizinde arandı:</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found"> <source>Specified file not found.</source> <target state="translated">Belirtilen dosya bulunamadı.</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found_colon_0"> <source>Specified file not found: {0}</source> <target state="translated">Belirtilen dosya bulunamadı: {0}</target> <note /> </trans-unit> <trans-unit id="Type_Sharphelp_for_more_information"> <source>Type "#help" for more information.</source> <target state="translated">Daha fazla bilgi için "#help" yazın.</target> <note /> </trans-unit> <trans-unit id="Unable_to_create_hosting_process"> <source>Unable to create hosting process.</source> <target state="translated">Barındırma işlemi oluşturulamıyor.</target> <note /> </trans-unit> <trans-unit id="plus_additional_0_1"> <source> + additional {0} {1}</source> <target state="translated"> + ek {0} {1}</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="tr" original="../InteractiveHostResources.resx"> <body> <trans-unit id="Attempt_to_connect_to_process_Sharp_0_failed_retrying"> <source>Attempt to connect to process #{0} failed, retrying ...</source> <target state="translated">#{0} işlemine bağlanma girişimi başarısız oldu, yeniden deneniyor...</target> <note /> </trans-unit> <trans-unit id="Cannot_resolve_reference_0"> <source>Cannot resolve reference '{0}'.</source> <target state="translated">'{0}' başvurusu çözümlenemiyor.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_a_remote_process_for_interactive_code_execution"> <source>Failed to create a remote process for interactive code execution: '{0}'</source> <target state="translated">Etkileşimli kod yürütme için uzak işlem oluşturulamadı: '{0}'</target> <note /> </trans-unit> <trans-unit id="Failed_to_initialize_remote_interactive_process"> <source>Failed to initialize remote interactive process.</source> <target state="translated">Uzak etkileşimli işlem başlatılamadı.</target> <note /> </trans-unit> <trans-unit id="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon"> <source>Failed to launch '{0}' process (exit code: {1}) with output: </source> <target state="translated">'{0}' işlemi (çıkış kodu: {1}) çıkış ile başlatılamadı: </target> <note /> </trans-unit> <trans-unit id="Hosting_process_exited_with_exit_code_0"> <source>Hosting process exited with exit code {0}.</source> <target state="translated">Barındırma işlemi {0} çıkış koduyla çıkış yaptı.</target> <note /> </trans-unit> <trans-unit id="Interactive_Host_not_initialized"> <source>Interactive Host not initialized.</source> <target state="translated">Etkileşimli Konak başlatılmadı.</target> <note /> </trans-unit> <trans-unit id="Loading_context_from_0"> <source>Loading context from '{0}'.</source> <target state="translated">'{0}' üzerinden bağlam yükleniyor.</target> <note /> </trans-unit> <trans-unit id="Searched_in_directories_colon"> <source>Searched in directories:</source> <target state="translated">Dizinlerde arandı:</target> <note /> </trans-unit> <trans-unit id="Searched_in_directory_colon"> <source>Searched in directory:</source> <target state="translated">Dizinde arandı:</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found"> <source>Specified file not found.</source> <target state="translated">Belirtilen dosya bulunamadı.</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found_colon_0"> <source>Specified file not found: {0}</source> <target state="translated">Belirtilen dosya bulunamadı: {0}</target> <note /> </trans-unit> <trans-unit id="Type_Sharphelp_for_more_information"> <source>Type "#help" for more information.</source> <target state="translated">Daha fazla bilgi için "#help" yazın.</target> <note /> </trans-unit> <trans-unit id="Unable_to_create_hosting_process"> <source>Unable to create hosting process.</source> <target state="translated">Barındırma işlemi oluşturulamıyor.</target> <note /> </trans-unit> <trans-unit id="plus_additional_0_1"> <source> + additional {0} {1}</source> <target state="translated"> + ek {0} {1}</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/AdditionalFile.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <AdditionalFiles Include="ValidAdditionalFile.txt" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <AdditionalFiles Include="ValidAdditionalFile.txt" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests : AbstractAddUsingTests { public AddUsingTests(ITestOutputHelper logger) : base(logger) { } [Theory] [CombinatorialData] public async Task TestTypeFromMultipleNamespaces1(TestHost testHost) { await TestAsync( @"class Class { [|IDictionary|] Method() { Goo(); } }", @"using System.Collections; class Class { IDictionary Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Outer(TestHost testHost) { await TestAsync( @" namespace N; class Class { [|IDictionary|] Method() { Goo(); } }", @" using System.Collections; namespace N; class Class { IDictionary Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Inner(TestHost testHost) { await TestAsync( @" namespace N; using System; class Class { [|IDictionary|] Method() { Goo(); } }", @" namespace N; using System; using System.Collections; class Class { IDictionary Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(11241, "https://github.com/dotnet/roslyn/issues/11241")] public async Task TestAddImportWithCaseChange(TestHost testHost) { await TestAsync( @"namespace N1 { public class TextBox { } } class Class1 : [|Textbox|] { }", @"using N1; namespace N1 { public class TextBox { } } class Class1 : TextBox { }", testHost); } [Theory] [CombinatorialData] public async Task TestTypeFromMultipleNamespaces2(TestHost testHost) { await TestAsync( @"class Class { [|IDictionary|] Method() { Goo(); } }", @"using System.Collections.Generic; class Class { IDictionary Method() { Goo(); } }", testHost, index: 1); } [Theory] [CombinatorialData] public async Task TestGenericWithNoArgs(TestHost testHost) { await TestAsync( @"class Class { [|List|] Method() { Goo(); } }", @"using System.Collections.Generic; class Class { List Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenericWithCorrectArgs(TestHost testHost) { await TestAsync( @"class Class { [|List<int>|] Method() { Goo(); } }", @"using System.Collections.Generic; class Class { List<int> Method() { Goo(); } }", testHost); } [Fact] public async Task TestGenericWithWrongArgs1() { await TestMissingInRegularAndScriptAsync( @"class Class { [|List<int, string, bool>|] Method() { Goo(); } }"); } [Fact] public async Task TestGenericWithWrongArgs2() { await TestMissingInRegularAndScriptAsync( @"class Class { [|List<int, string>|] Method() { Goo(); } }"); } [Theory] [CombinatorialData] public async Task TestGenericInLocalDeclaration(TestHost testHost) { await TestAsync( @"class Class { void Goo() { [|List<int>|] a = new List<int>(); } }", @"using System.Collections.Generic; class Class { void Goo() { List<int> a = new List<int>(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenericItemType(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Class { List<[|Int32|]> l; }", @"using System; using System.Collections.Generic; class Class { List<Int32> l; }", testHost); } [Theory] [CombinatorialData] public async Task TestGenerateWithExistingUsings(TestHost testHost) { await TestAsync( @"using System; class Class { [|List<int>|] Method() { Goo(); } }", @"using System; using System.Collections.Generic; class Class { List<int> Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenerateInNamespace(TestHost testHost) { await TestAsync( @"namespace N { class Class { [|List<int>|] Method() { Goo(); } } }", @"using System.Collections.Generic; namespace N { class Class { List<int> Method() { Goo(); } } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenerateInNamespaceWithUsings(TestHost testHost) { await TestAsync( @"namespace N { using System; class Class { [|List<int>|] Method() { Goo(); } } }", @"namespace N { using System; using System.Collections.Generic; class Class { List<int> Method() { Goo(); } } }", testHost); } [Fact] public async Task TestExistingUsing_ActionCount() { await TestActionCountAsync( @"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Goo(); } }", count: 1); } [Theory] [CombinatorialData] public async Task TestExistingUsing(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Goo(); } }", @"using System.Collections; using System.Collections.Generic; class Class { IDictionary Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] public async Task TestAddUsingForGenericExtensionMethod(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Class { void Method(IList<int> args) { args.[|Where|]() } }", @"using System.Collections.Generic; using System.Linq; class Class { void Method(IList<int> args) { args.Where() } }", testHost); } [Fact] [WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] public async Task TestAddUsingForNormalExtensionMethod() { await TestAsync( @"class Class { void Method(Class args) { args.[|Where|]() } } namespace N { static class E { public static void Where(this Class c) { } } }", @"using N; class Class { void Method(Class args) { args.Where() } } namespace N { static class E { public static void Where(this Class c) { } } }", parseOptions: Options.Regular); } [Theory] [CombinatorialData] public async Task TestOnEnum(TestHost testHost) { await TestAsync( @"class Class { void Goo() { var a = [|Colors|].Red; } } namespace A { enum Colors { Red, Green, Blue } }", @"using A; class Class { void Goo() { var a = Colors.Red; } } namespace A { enum Colors { Red, Green, Blue } }", testHost); } [Theory] [CombinatorialData] public async Task TestOnClassInheritance(TestHost testHost) { await TestAsync( @"class Class : [|Class2|] { } namespace A { class Class2 { } }", @"using A; class Class : Class2 { } namespace A { class Class2 { } }", testHost); } [Theory] [CombinatorialData] public async Task TestOnImplementedInterface(TestHost testHost) { await TestAsync( @"class Class : [|IGoo|] { } namespace A { interface IGoo { } }", @"using A; class Class : IGoo { } namespace A { interface IGoo { } }", testHost); } [Theory] [CombinatorialData] public async Task TestAllInBaseList(TestHost testHost) { await TestAsync( @"class Class : [|IGoo|], Class2 { } namespace A { class Class2 { } } namespace B { interface IGoo { } }", @"using B; class Class : IGoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IGoo { } }", testHost); await TestAsync( @"using B; class Class : IGoo, [|Class2|] { } namespace A { class Class2 { } } namespace B { interface IGoo { } }", @"using A; using B; class Class : IGoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IGoo { } }", testHost); } [Theory] [CombinatorialData] public async Task TestAttributeUnexpanded(TestHost testHost) { await TestAsync( @"[[|Obsolete|]] class Class { }", @"using System; [Obsolete] class Class { }", testHost); } [Theory] [CombinatorialData] public async Task TestAttributeExpanded(TestHost testHost) { await TestAsync( @"[[|ObsoleteAttribute|]] class Class { }", @"using System; [ObsoleteAttribute] class Class { }", testHost); } [Theory] [CombinatorialData] [WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")] public async Task TestAfterNew(TestHost testHost) { await TestAsync( @"class Class { void Goo() { List<int> l; l = new [|List<int>|](); } }", @"using System.Collections.Generic; class Class { void Goo() { List<int> l; l = new List<int>(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestArgumentsInMethodCall(TestHost testHost) { await TestAsync( @"class Class { void Test() { Console.WriteLine([|DateTime|].Today); } }", @"using System; class Class { void Test() { Console.WriteLine(DateTime.Today); } }", testHost); } [Theory] [CombinatorialData] public async Task TestCallSiteArgs(TestHost testHost) { await TestAsync( @"class Class { void Test([|DateTime|] dt) { } }", @"using System; class Class { void Test(DateTime dt) { } }", testHost); } [Theory] [CombinatorialData] public async Task TestUsePartialClass(TestHost testHost) { await TestAsync( @"namespace A { public class Class { [|PClass|] c; } } namespace B { public partial class PClass { } }", @"using B; namespace A { public class Class { PClass c; } } namespace B { public partial class PClass { } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenericClassInNestedNamespace(TestHost testHost) { await TestAsync( @"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { [|GenericClass<int>|] c; } }", @"using A.B; namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { GenericClass<int> c; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] public async Task TestExtensionMethods(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Goo { void Bar() { var values = new List<int>(); values.[|Where|](i => i > 1); } }", @"using System.Collections.Generic; using System.Linq; class Goo { void Bar() { var values = new List<int>(); values.Where(i => i > 1); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] public async Task TestQueryPatterns(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Goo { void Bar() { var values = new List<int>(); var q = [|from v in values where v > 1 select v + 10|]; } }", @"using System.Collections.Generic; using System.Linq; class Goo { void Bar() { var values = new List<int>(); var q = from v in values where v > 1 select v + 10; } }", testHost); } // Tests for Insertion Order [Theory] [CombinatorialData] public async Task TestSimplePresortedUsings1(TestHost testHost) { await TestAsync( @"using B; using C; class Class { void Method() { [|Goo|].Bar(); } } namespace D { class Goo { public static void Bar() { } } }", @"using B; using C; using D; class Class { void Method() { Goo.Bar(); } } namespace D { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimplePresortedUsings2(TestHost testHost) { await TestAsync( @"using B; using C; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using A; using B; using C; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleUnsortedUsings1(TestHost testHost) { await TestAsync( @"using C; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using C; using B; using A; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleUnsortedUsings2(TestHost testHost) { await TestAsync( @"using D; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace C { class Goo { public static void Bar() { } } }", @"using D; using B; using C; class Class { void Method() { Goo.Bar(); } } namespace C { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultiplePresortedUsings1(TestHost testHost) { await TestAsync( @"using B.X; using B.Y; class Class { void Method() { [|Goo|].Bar(); } } namespace B { class Goo { public static void Bar() { } } }", @"using B; using B.X; using B.Y; class Class { void Method() { Goo.Bar(); } } namespace B { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultiplePresortedUsings2(TestHost testHost) { await TestAsync( @"using B.X; using B.Y; class Class { void Method() { [|Goo|].Bar(); } } namespace B.A { class Goo { public static void Bar() { } } }", @"using B.A; using B.X; using B.Y; class Class { void Method() { Goo.Bar(); } } namespace B.A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultiplePresortedUsings3(TestHost testHost) { await TestAsync( @"using B.X; using B.Y; class Class { void Method() { [|Goo|].Bar(); } } namespace B { namespace A { class Goo { public static void Bar() { } } } }", @"using B.A; using B.X; using B.Y; class Class { void Method() { Goo.Bar(); } } namespace B { namespace A { class Goo { public static void Bar() { } } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultipleUnsortedUsings1(TestHost testHost) { await TestAsync( @"using B.Y; using B.X; class Class { void Method() { [|Goo|].Bar(); } } namespace B { namespace A { class Goo { public static void Bar() { } } } }", @"using B.Y; using B.X; using B.A; class Class { void Method() { Goo.Bar(); } } namespace B { namespace A { class Goo { public static void Bar() { } } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultipleUnsortedUsings2(TestHost testHost) { await TestAsync( @"using B.Y; using B.X; class Class { void Method() { [|Goo|].Bar(); } } namespace B { class Goo { public static void Bar() { } } }", @"using B.Y; using B.X; using B; class Class { void Method() { Goo.Bar(); } } namespace B { class Goo { public static void Bar() { } } }", testHost); } // System on top cases [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings1(TestHost testHost) { await TestAsync( @"using System; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using System; using A; using B; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings2(TestHost testHost) { await TestAsync( @"using System; using System.Collections.Generic; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using System; using System.Collections.Generic; using A; using B; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings3(TestHost testHost) { await TestAsync( @"using A; using B; class Class { void Method() { [|Console|].Write(1); } }", @"using System; using A; using B; class Class { void Method() { Console.Write(1); } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemUnsortedUsings1(TestHost testHost) { await TestAsync( @" using C; using B; using System; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @" using C; using B; using System; using A; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemUnsortedUsings2(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; using System; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using System.Collections.Generic; using System; using B; using A; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemUnsortedUsings3(TestHost testHost) { await TestAsync( @"using B; using A; class Class { void Method() { [|Console|].Write(1); } }", @"using B; using A; using System; class Class { void Method() { Console.Write(1); } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleBogusSystemUsings1(TestHost testHost) { await TestAsync( @"using A.System; class Class { void Method() { [|Console|].Write(1); } }", @"using System; using A.System; class Class { void Method() { Console.Write(1); } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleBogusSystemUsings2(TestHost testHost) { await TestAsync( @"using System.System; class Class { void Method() { [|Console|].Write(1); } }", @"using System; using System.System; class Class { void Method() { Console.Write(1); } }", testHost); } [Theory] [CombinatorialData] public async Task TestUsingsWithComments(TestHost testHost) { await TestAsync( @"using System./*...*/.Collections.Generic; class Class { void Method() { [|Console|].Write(1); } }", @"using System; using System./*...*/.Collections.Generic; class Class { void Method() { Console.Write(1); } }", testHost); } // System Not on top cases [Theory] [CombinatorialData] public async Task TestSimpleSystemUnsortedUsings4(TestHost testHost) { await TestAsync( @" using C; using System; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @" using C; using System; using B; using A; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings5(TestHost testHost) { await TestAsync( @"using B; using System; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using A; using B; using System; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings4(TestHost testHost) { await TestAsync( @"using A; using B; class Class { void Method() { [|Console|].Write(1); } }", @"using A; using B; using System; class Class { void Method() { Console.Write(1); } }", testHost, options: Option(GenerationOptions.PlaceSystemNamespaceFirst, false)); } [Fact] [WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")] [WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] public async Task TestAddUsingForNamespace() { await TestMissingInRegularAndScriptAsync( @"namespace A { class Class { [|C|].Test t; } } namespace B { namespace C { class Test { } } }"); } [Theory] [CombinatorialData] [WorkItem(538220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538220")] public async Task TestAddUsingForFieldWithFormatting(TestHost testHost) { await TestAsync( @"class C { [|DateTime|] t; }", @"using System; class C { DateTime t; }", testHost); } [Theory] [CombinatorialData] [WorkItem(539657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539657")] public async Task BugFix5688(TestHost testHost) { await TestAsync( @"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } } ", @"using System; class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = ""\r\n\r\n"" ; } } ", testHost); } [Fact] [WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")] public async Task BugFix5950() { await TestAsync( @"using System.Console; WriteLine([|Expression|].Constant(123));", @"using System.Console; using System.Linq.Expressions; WriteLine(Expression.Constant(123));", parseOptions: GetScriptOptions()); } [Theory] [CombinatorialData] [WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")] public async Task TestAddAfterDefineDirective1(TestHost testHost) { await TestAsync( @"#define goo using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")] public async Task TestAddAfterDefineDirective2(TestHost testHost) { await TestAsync( @"#define goo class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo using System; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterDefineDirective3(TestHost testHost) { await TestAsync( @"#define goo /// Goo class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo using System; /// Goo class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterDefineDirective4(TestHost testHost) { await TestAsync( @"#define goo // Goo class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo // Goo using System; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterExistingBanner(TestHost testHost) { await TestAsync( @"// Banner // Banner class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"// Banner // Banner using System; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterExternAlias1(TestHost testHost) { await TestAsync( @"#define goo extern alias Goo; class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo extern alias Goo; using System; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterExternAlias2(TestHost testHost) { await TestAsync( @"#define goo extern alias Goo; using System.Collections; class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo extern alias Goo; using System; using System.Collections; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Fact] public async Task TestWithReferenceDirective() { var resolver = new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>() { { "exprs", AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference() } }); await TestAsync( @"#r ""exprs"" [|Expression|]", @"#r ""exprs"" using System.Linq.Expressions; Expression", GetScriptOptions(), TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); } [Theory] [CombinatorialData] [WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")] public async Task TestAssemblyAttribute(TestHost testHost) { await TestAsync( @"[assembly: [|InternalsVisibleTo|](""Project"")]", @"using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Project"")]", testHost); } [Fact] public async Task TestDoNotAddIntoHiddenRegion() { await TestMissingInRegularAndScriptAsync( @"#line hidden using System.Collections.Generic; #line default class Program { void Main() { [|DateTime|] d; } }"); } [Theory] [CombinatorialData] public async Task TestAddToVisibleRegion(TestHost testHost) { await TestAsync( @"#line default using System.Collections.Generic; #line hidden class Program { void Main() { #line default [|DateTime|] d; #line hidden } } #line default", @"#line default using System; using System.Collections.Generic; #line hidden class Program { void Main() { #line default DateTime d; #line hidden } } #line default", testHost); } [Fact] [WorkItem(545248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545248")] public async Task TestVenusGeneration1() { await TestMissingInRegularAndScriptAsync( @"class C { void Goo() { #line 1 ""Default.aspx"" using (new [|StreamReader|]()) { #line default #line hidden } }"); } [Fact] [WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] public async Task TestAttribute_ActionCount() { var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] "; await TestActionCountAsync(input, 2); } [Theory] [CombinatorialData] [WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] public async Task TestAttribute(TestHost testHost) { var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] "; await TestAsync( input, @"using System.Runtime.InteropServices; [ assembly : Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost); } [Fact] [WorkItem(546833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546833")] public async Task TestNotOnOverloadResolutionError() { await TestMissingInRegularAndScriptAsync( @"namespace ConsoleApplication1 { class Program { void Main() { var test = new [|Test|](""""); } } class Test { } }"); } [Theory] [CombinatorialData] [WorkItem(17020, "DevDiv_Projects/Roslyn")] public async Task TestAddUsingForGenericArgument(TestHost testHost) { await TestAsync( @"namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var inArgument = new InArgument<[|IEnumerable<int>|]>(new int[] { 1, 2, 3 }); } } public class InArgument<T> { public InArgument(T constValue) { } } }", @"using System.Collections.Generic; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var inArgument = new InArgument<IEnumerable<int>>(new int[] { 1, 2, 3 }); } } public class InArgument<T> { public InArgument(T constValue) { } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")] public async Task ShouldTriggerOnCS0308(TestHost testHost) { // CS0308: The non-generic type 'A' cannot be used with type arguments await TestAsync( @"using System.Collections; class Test { static void Main(string[] args) { [|IEnumerable<int>|] f; } }", @"using System.Collections; using System.Collections.Generic; class Test { static void Main(string[] args) { IEnumerable<int> f; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(838253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838253")] public async Task TestConflictedInaccessibleType(TestHost testHost) { await TestAsync( @"using System.Diagnostics; namespace N { public class Log { } } class C { static void Main(string[] args) { [|Log|] } }", @"using System.Diagnostics; using N; namespace N { public class Log { } } class C { static void Main(string[] args) { Log } }", testHost); } [Theory] [CombinatorialData] [WorkItem(858085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858085")] public async Task TestConflictedAttributeName(TestHost testHost) { await TestAsync( @"[[|Description|]] class Description { }", @"using System.ComponentModel; [Description] class Description { }", testHost); } [Theory] [CombinatorialData] [WorkItem(872908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872908")] public async Task TestConflictedGenericName(TestHost testHost) { await TestAsync( @"using Task = System.AccessViolationException; class X { [|Task<X> x;|] }", @"using System.Threading.Tasks; using Task = System.AccessViolationException; class X { Task<X> x; }", testHost); } [Fact] [WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")] public async Task TestNoDuplicateReport_ActionCount() { await TestActionCountInAllFixesAsync( @"class C { void M(P p) { [|Console|] } static void Main(string[] args) { } }", count: 1); } [Theory] [CombinatorialData] [WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")] public async Task TestNoDuplicateReport(TestHost testHost) { await TestAsync( @"class C { void M(P p) { [|Console|] } static void Main(string[] args) { } }", @"using System; class C { void M(P p) { Console } static void Main(string[] args) { } }", testHost); } [Fact] [WorkItem(938296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938296")] public async Task TestNullParentInNode() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class MultiDictionary<K, V> : Dictionary<K, HashSet<V>> { void M() { new HashSet<V>([|Comparer|]); } }"); } [Fact] [WorkItem(968303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968303")] public async Task TestMalformedUsingSection() { await TestMissingInRegularAndScriptAsync( @"[ class Class { [|List<|] }"); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithExternAlias(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace ProjectLib { public class Project { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> namespace ExternAliases { class Program { static void Main(string[] args) { Project p = new [|Project()|]; } } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @"extern alias P; using P::ProjectLib; namespace ExternAliases { class Program { static void Main(string[] args) { Project p = new Project(); } } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithPreExistingExternAlias(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace ProjectLib { public class Project { } } namespace AnotherNS { public class AnotherClass { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> extern alias P; using P::ProjectLib; namespace ExternAliases { class Program { static void Main(string[] args) { Project p = new Project(); var x = new [|AnotherClass()|]; } } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @" extern alias P; using P::AnotherNS; using P::ProjectLib; namespace ExternAliases { class Program { static void Main(string[] args) { Project p = new Project(); var x = new [|AnotherClass()|]; } } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithPreExistingExternAlias_FileScopedNamespace(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace ProjectLib; { public class Project { } } namespace AnotherNS { public class AnotherClass { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> extern alias P; using P::ProjectLib; namespace ExternAliases; class Program { static void Main(string[] args) { Project p = new Project(); var x = new [|AnotherClass()|]; } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @" extern alias P; using P::AnotherNS; using P::ProjectLib; namespace ExternAliases; class Program { static void Main(string[] args) { Project p = new Project(); var x = new [|AnotherClass()|]; } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsNoExtern(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace AnotherNS { public class AnotherClass { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> using P::AnotherNS; namespace ExternAliases { class Program { static void Main(string[] args) { var x = new [|AnotherClass()|]; } } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @"extern alias P; using P::AnotherNS; namespace ExternAliases { class Program { static void Main(string[] args) { var x = new AnotherClass(); } } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsNoExtern_FileScopedNamespace(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace AnotherNS; public class AnotherClass { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> using P::AnotherNS; namespace ExternAliases; class Program { static void Main(string[] args) { var x = new [|AnotherClass()|]; } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @"extern alias P; using P::AnotherNS; namespace ExternAliases; class Program { static void Main(string[] args) { var x = new AnotherClass(); } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsNoExternFilterGlobalAlias(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { [|INotifyPropertyChanged.PropertyChanged|] } }", @"using System.ComponentModel; class Program { static void Main(string[] args) { INotifyPropertyChanged.PropertyChanged } }", testHost); } [Fact] [WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref() { var initialText = @"/// <summary> /// This is just like <see cref='[|INotifyPropertyChanged|]'/>, but this one is mine. /// </summary> interface MyNotifyPropertyChanged { }"; var expectedText = @"using System.ComponentModel; /// <summary> /// This is just like <see cref='INotifyPropertyChanged'/>, but this one is mine. /// </summary> interface MyNotifyPropertyChanged { }"; var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); await TestAsync(initialText, expectedText, parseOptions: options); } [Fact] [WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref2() { var initialText = @"/// <summary> /// This is just like <see cref='[|INotifyPropertyChanged.PropertyChanged|]'/>, but this one is mine. /// </summary> interface MyNotifyPropertyChanged { }"; var expectedText = @"using System.ComponentModel; /// <summary> /// This is just like <see cref='INotifyPropertyChanged.PropertyChanged'/>, but this one is mine. /// </summary> interface MyNotifyPropertyChanged { }"; var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); await TestAsync(initialText, expectedText, parseOptions: options); } [Fact] [WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref3() { var initialText = @"namespace N1 { public class D { } } public class MyClass { public static explicit operator N1.D (MyClass f) { return default(N1.D); } } /// <seealso cref='MyClass.explicit operator [|D(MyClass)|]'/> public class MyClass2 { }"; var expectedText = @"using N1; namespace N1 { public class D { } } public class MyClass { public static explicit operator N1.D (MyClass f) { return default(N1.D); } } /// <seealso cref='MyClass.explicit operator D(MyClass)'/> public class MyClass2 { }"; var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); await TestAsync(initialText, expectedText, parseOptions: options); } [Fact] [WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref4() { var initialText = @"namespace N1 { public class D { } } /// <seealso cref='[|Test(D)|]'/> public class MyClass { public void Test(N1.D i) { } }"; var expectedText = @"using N1; namespace N1 { public class D { } } /// <seealso cref='Test(D)'/> public class MyClass { public void Test(N1.D i) { } }"; var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); await TestAsync(initialText, expectedText, parseOptions: options); } [Theory] [CombinatorialData] [WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] public async Task TestAddStaticType(TestHost testHost) { var initialText = @"using System; public static class Outer { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } [[|My|]] class Test {}"; var expectedText = @"using System; using static Outer; public static class Outer { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } [My] class Test {}"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] public async Task TestAddStaticType2(TestHost testHost) { var initialText = @"using System; public static class Outer { public static class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [[|My|]] class Test {}"; var expectedText = @"using System; using static Outer.Inner; public static class Outer { public static class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [My] class Test {}"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] public async Task TestAddStaticType3(TestHost testHost) { await TestAsync( @"using System; public static class Outer { public class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [[|My|]] class Test { }", @"using System; using static Outer.Inner; public static class Outer { public class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [My] class Test { }", testHost); } [Theory] [CombinatorialData] [WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] public async Task TestAddStaticType4(TestHost testHost) { var initialText = @"using System; using Outer; public static class Outer { public static class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [[|My|]] class Test {}"; var expectedText = @"using System; using Outer; using static Outer.Inner; public static class Outer { public static class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [My] class Test {}"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective1(TestHost testHost) { await TestAsync( @"namespace ns { using B = [|Byte|]; }", @"using System; namespace ns { using B = Byte; }", testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective2(TestHost testHost) { await TestAsync( @"using System.Collections; namespace ns { using B = [|Byte|]; }", @"using System; using System.Collections; namespace ns { using B = Byte; }", testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective3(TestHost testHost) { await TestAsync( @"namespace ns2 { namespace ns3 { namespace ns { using B = [|Byte|]; namespace ns4 { } } } }", @"using System; namespace ns2 { namespace ns3 { namespace ns { using B = Byte; namespace ns4 { } } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective4(TestHost testHost) { await TestAsync( @"namespace ns2 { using System.Collections; namespace ns3 { namespace ns { using System.IO; using B = [|Byte|]; } } }", @"namespace ns2 { using System; using System.Collections; namespace ns3 { namespace ns { using System.IO; using B = Byte; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective5(TestHost testHost) { await TestAsync( @"using System.IO; namespace ns2 { using System.Diagnostics; namespace ns3 { using System.Collections; namespace ns { using B = [|Byte|]; } } }", @"using System.IO; namespace ns2 { using System.Diagnostics; namespace ns3 { using System; using System.Collections; namespace ns { using B = Byte; } } }", testHost); } [Fact] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective6() { await TestMissingInRegularAndScriptAsync( @"using B = [|Byte|];"); } [Theory] [CombinatorialData] [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] public async Task TestAddConditionalAccessExpression(TestHost testHost) { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> public class C { void Main(C a) { C x = a?[|.B()|]; } } </Document> <Document FilePath = ""Extensions""> namespace Extensions { public static class E { public static C B(this C c) { return c; } } } </Document> </Project> </Workspace> "; var expectedText = @" using Extensions; public class C { void Main(C a) { C x = a?.B(); } } "; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] public async Task TestAddConditionalAccessExpression2(TestHost testHost) { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> public class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.[|C()|]; } public class E { } } </Document> <Document FilePath = ""Extensions""> namespace Extensions { public static class D { public static C.E C(this C.E c) { return c; } } } </Document> </Project> </Workspace> "; var expectedText = @" using Extensions; public class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.C(); } public class E { } } "; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1089138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089138")] public async Task TestAmbiguousUsingName(TestHost testHost) { await TestAsync( @"namespace ClassLibrary1 { using System; public class SomeTypeUser { [|SomeType|] field; } } namespace SubNamespaceName { using System; class SomeType { } } namespace ClassLibrary1.SubNamespaceName { using System; class SomeOtherFile { } }", @"namespace ClassLibrary1 { using System; using global::SubNamespaceName; public class SomeTypeUser { SomeType field; } } namespace SubNamespaceName { using System; class SomeType { } } namespace ClassLibrary1.SubNamespaceName { using System; class SomeOtherFile { } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingInDirective(TestHost testHost) { await TestAsync( @"#define DEBUG #if DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Text; #endif class Program { static void Main(string[] args) { var a = [|File|].OpenRead(""""); } }", @"#define DEBUG #if DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Text; using System.IO; #endif class Program { static void Main(string[] args) { var a = File.OpenRead(""""); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingInDirective2(TestHost testHost) { await TestAsync( @"#define DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; #if DEBUG using System.Text; #endif class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", @"#define DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; #if DEBUG using System.Text; #endif class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingInDirective3(TestHost testHost) { await TestAsync( @"#define DEBUG using System; using System.Collections.Generic; #if DEBUG using System.Text; #endif using System.Linq; using System.Threading.Tasks; class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", @"#define DEBUG using System; using System.Collections.Generic; #if DEBUG using System.Text; #endif using System.Linq; using System.Threading.Tasks; using System.IO; class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingInDirective4(TestHost testHost) { await TestAsync( @"#define DEBUG #if DEBUG using System; #endif using System.Collections.Generic; using System.Text; using System.Linq; using System.Threading.Tasks; class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", @"#define DEBUG #if DEBUG using System; #endif using System.Collections.Generic; using System.Text; using System.Linq; using System.Threading.Tasks; using System.IO; class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); } [Fact] public async Task TestInaccessibleExtensionMethod() { const string initial = @" namespace N1 { public static class C { private static bool ExtMethod1(this string arg1) { return true; } } } namespace N2 { class Program { static void Main(string[] args) { var x = ""str1"".[|ExtMethod1()|]; } } }"; await TestMissingInRegularAndScriptAsync(initial); } [Theory] [CombinatorialData] [WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")] public async Task TestAddUsingForProperty(TestHost testHost) { await TestAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public BindingFlags BindingFlags { get { return BindingFlags.[|Instance|]; } } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; class Program { public BindingFlags BindingFlags { get { return BindingFlags.Instance; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")] public async Task TestAddUsingForField(TestHost testHost) { await TestAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public B B { get { return B.[|Instance|]; } } } namespace A { public class B { public static readonly B Instance; } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using A; class Program { public B B { get { return B.Instance; } } } namespace A { public class B { public static readonly B Instance; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(1893, "https://github.com/dotnet/roslyn/issues/1893")] public async Task TestNameSimplification(TestHost testHost) { // Generated using directive must be simplified from "using A.B;" to "using B;" below. await TestAsync( @"namespace A.B { class T1 { } } namespace A.C { using System; class T2 { void Test() { Console.WriteLine(); [|T1|] t1; } } }", @"namespace A.B { class T1 { } } namespace A.C { using System; using A.B; class T2 { void Test() { Console.WriteLine(); T1 t1; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")] public async Task TestAddUsingWithOtherExtensionsInScope(TestHost testHost) { await TestAsync( @"using System.Linq; using System.Collections; using X; namespace X { public static class Ext { public static void ExtMethod(this int a) { } } } namespace Y { public static class Ext { public static void ExtMethod(this int a, int v) { } } } public class B { static void Main() { var b = 0; b.[|ExtMethod|](0); } }", @"using System.Linq; using System.Collections; using X; using Y; namespace X { public static class Ext { public static void ExtMethod(this int a) { } } } namespace Y { public static class Ext { public static void ExtMethod(this int a, int v) { } } } public class B { static void Main() { var b = 0; b.ExtMethod(0); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")] public async Task TestAddUsingWithOtherExtensionsInScope2(TestHost testHost) { await TestAsync( @"using System.Linq; using System.Collections; using X; namespace X { public static class Ext { public static void ExtMethod(this int? a) { } } } namespace Y { public static class Ext { public static void ExtMethod(this int? a, int v) { } } } public class B { static void Main() { var b = new int?(); b?[|.ExtMethod|](0); } }", @"using System.Linq; using System.Collections; using X; using Y; namespace X { public static class Ext { public static void ExtMethod(this int? a) { } } } namespace Y { public static class Ext { public static void ExtMethod(this int? a, int v) { } } } public class B { static void Main() { var b = new int?(); b?.ExtMethod(0); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")] public async Task TestAddUsingWithOtherExtensionsInScope3(TestHost testHost) { await TestAsync( @"using System.Linq; class C { int i = 0.[|All|](); } namespace X { static class E { public static int All(this int o) => 0; } }", @"using System.Linq; using X; class C { int i = 0.All(); } namespace X { static class E { public static int All(this int o) => 0; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")] public async Task TestAddUsingWithOtherExtensionsInScope4(TestHost testHost) { await TestAsync( @"using System.Linq; class C { static void Main(string[] args) { var a = new int?(); int? i = a?[|.All|](); } } namespace X { static class E { public static int? All(this int? o) => 0; } }", @"using System.Linq; using X; class C { static void Main(string[] args) { var a = new int?(); int? i = a?.All(); } } namespace X { static class E { public static int? All(this int? o) => 0; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using Win32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using Microsoft.Win32.SafeHandles; using Win32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified2(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using Zin32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using Microsoft.Win32.SafeHandles; using Zin32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified3(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using System; using Win32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using System; using Microsoft.Win32.SafeHandles; using Win32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified4(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using System; using Zin32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using System; using Microsoft.Win32.SafeHandles; using Zin32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified5(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { #if true using Win32; #else using System; #endif class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using Microsoft.Win32.SafeHandles; #if true using Win32; #else using System; #endif class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified6(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using System; #if false using Win32; #endif using Win32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using System; using Microsoft.Win32.SafeHandles; #if false using Win32; #endif using Win32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingOrdinalUppercase(TestHost testHost) { await TestAsync( @"namespace A { class A { static void Main(string[] args) { var b = new [|B|](); } } } namespace lowercase { class b { } } namespace Uppercase { class B { } }", @"using Uppercase; namespace A { class A { static void Main(string[] args) { var b = new B(); } } } namespace lowercase { class b { } } namespace Uppercase { class B { } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingOrdinalLowercase(TestHost testHost) { await TestAsync( @"namespace A { class A { static void Main(string[] args) { var a = new [|b|](); } } } namespace lowercase { class b { } } namespace Uppercase { class B { } }", @"using lowercase; namespace A { class A { static void Main(string[] args) { var a = new b(); } } } namespace lowercase { class b { } } namespace Uppercase { class B { } }", testHost); } [Theory] [CombinatorialData] [WorkItem(7443, "https://github.com/dotnet/roslyn/issues/7443")] public async Task TestWithExistingIncompatibleExtension(TestHost testHost) { await TestAsync( @"using N; class C { int x() { System.Collections.Generic.IEnumerable<int> x = null; return x.[|Any|] } } namespace N { static class Extensions { public static void Any(this string s) { } } }", @"using System.Linq; using N; class C { int x() { System.Collections.Generic.IEnumerable<int> x = null; return x.Any } } namespace N { static class Extensions { public static void Any(this string s) { } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(1744, @"https://github.com/dotnet/roslyn/issues/1744")] public async Task TestIncompleteCatchBlockInLambda(TestHost testHost) { await TestAsync( @"class A { System.Action a = () => { try { } catch ([|Exception|]", @"using System; class A { System.Action a = () => { try { } catch (Exception", testHost); } [Theory] [CombinatorialData] [WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] public async Task TestAddInsideLambda(TestHost testHost) { var initialText = @"using System; static void Main(string[] args) { Func<int> f = () => { [|List<int>|]. } }"; var expectedText = @"using System; using System.Collections.Generic; static void Main(string[] args) { Func<int> f = () => { List<int>. } }"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] public async Task TestAddInsideLambda2(TestHost testHost) { var initialText = @"using System; static void Main(string[] args) { Func<int> f = () => { [|List<int>|] } }"; var expectedText = @"using System; using System.Collections.Generic; static void Main(string[] args) { Func<int> f = () => { List<int> } }"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] public async Task TestAddInsideLambda3(TestHost testHost) { var initialText = @"using System; static void Main(string[] args) { Func<int> f = () => { var a = 3; [|List<int>|]. return a; }; }"; var expectedText = @"using System; using System.Collections.Generic; static void Main(string[] args) { Func<int> f = () => { var a = 3; List<int>. return a; }; }"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] public async Task TestAddInsideLambda4(TestHost testHost) { var initialText = @"using System; static void Main(string[] args) { Func<int> f = () => { var a = 3; [|List<int>|] return a; }; }"; var expectedText = @"using System; using System.Collections.Generic; static void Main(string[] args) { Func<int> f = () => { var a = 3; List<int> return a; }; }"; await TestAsync(initialText, expectedText, testHost); } [WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")] [Theory] [CombinatorialData] [WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")] public async Task TestIncompleteParenthesizedLambdaExpression(TestHost testHost) { await TestAsync( @"using System; class Test { void Goo() { Action a = () => { [|IBindCtx|] }; string a; } }", @"using System; using System.Runtime.InteropServices.ComTypes; class Test { void Goo() { Action a = () => { IBindCtx }; string a; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(7461, "https://github.com/dotnet/roslyn/issues/7461")] public async Task TestExtensionWithIncompatibleInstance(TestHost testHost) { await TestAsync( @"using System.IO; namespace Namespace1 { static class StreamExtensions { public static void Write(this Stream stream, byte[] bytes) { } } } namespace Namespace2 { class Goo { void Bar() { Stream stream = null; stream.[|Write|](new byte[] { 1, 2, 3 }); } } }", @"using System.IO; using Namespace1; namespace Namespace1 { static class StreamExtensions { public static void Write(this Stream stream, byte[] bytes) { } } } namespace Namespace2 { class Goo { void Bar() { Stream stream = null; stream.Write(new byte[] { 1, 2, 3 }); } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(5499, "https://github.com/dotnet/roslyn/issues/5499")] public async Task TestFormattingForNamespaceUsings(TestHost testHost) { await TestAsync( @"namespace N { using System; using System.Collections.Generic; using System.Linq; using System.Text; class Program { void Main() { [|Task<int>|] } } }", @"namespace N { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { void Main() { Task<int> } } }", testHost); } [Fact] public async Task TestGenericAmbiguityInSameNamespace() { await TestMissingInRegularAndScriptAsync( @"namespace NS { class C<T> where T : [|C|].N { public class N { } } }"); } [Fact] public async Task TestNotOnVar1() { await TestMissingInRegularAndScriptAsync( @"namespace N { class var { } } class C { void M() { [|var|] } } "); } [Fact] public async Task TestNotOnVar2() { await TestMissingInRegularAndScriptAsync( @"namespace N { class Bar { } } class C { void M() { [|var|] } } "); } [Theory] [CombinatorialData] [WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing1(TestHost testHost) { await TestAsync( @" /// Copyright 2016 - MyCompany /// All Rights Reserved using System; class C : [|IEnumerable|]<int> { } ", @" /// Copyright 2016 - MyCompany /// All Rights Reserved using System; using System.Collections.Generic; class C : IEnumerable<int> { } ", testHost); } [Theory] [CombinatorialData] [WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing2(TestHost testHost) { await TestAsync( @" /// Copyright 2016 - MyCompany /// All Rights Reserved using System.Collections; class C { [|DateTime|] d; } ", @" /// Copyright 2016 - MyCompany /// All Rights Reserved using System; using System.Collections; class C { DateTime d; } ", testHost); } [Theory] [CombinatorialData] [WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] public async Task TestAddUsingWithLeadingDocCommentInFrontOfClass1(TestHost testHost) { await TestAsync( @" /// Copyright 2016 - MyCompany /// All Rights Reserved class C { [|DateTime|] d; } ", @" using System; /// Copyright 2016 - MyCompany /// All Rights Reserved class C { DateTime d; } ", testHost); } [Theory] [CombinatorialData] public async Task TestPlaceUsingWithUsings_NotWithAliases(TestHost testHost) { await TestAsync( @" using System; namespace N { using C = System.Collections; class Class { [|List<int>|] Method() { Goo(); } } }", @" using System; using System.Collections.Generic; namespace N { using C = System.Collections; class Class { List<int> Method() { Goo(); } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")] public async Task TestPreferSystemNamespaceFirst(TestHost testHost) { await TestAsync( @" namespace Microsoft { public class SomeClass { } } namespace System { public class SomeClass { } } namespace N { class Class { [|SomeClass|] c; } }", @" using System; namespace Microsoft { public class SomeClass { } } namespace System { public class SomeClass { } } namespace N { class Class { SomeClass c; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")] public async Task TestPreferSystemNamespaceFirst2(TestHost testHost) { await TestAsync( @" namespace Microsoft { public class SomeClass { } } namespace System { public class SomeClass { } } namespace N { class Class { [|SomeClass|] c; } }", @" using Microsoft; namespace Microsoft { public class SomeClass { } } namespace System { public class SomeClass { } } namespace N { class Class { SomeClass c; } }", testHost, index: 1); } [Fact] [WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")] public async Task TestContextualKeyword1() { await TestMissingInRegularAndScriptAsync( @" namespace N { class nameof { } } class C { void M() { [|nameof|] } }"); } [Theory] [CombinatorialData] [WorkItem(19218, "https://github.com/dotnet/roslyn/issues/19218")] public async Task TestChangeCaseWithUsingsInNestedNamespace(TestHost testHost) { await TestAsync( @"namespace VS { interface IVsStatusbar { } } namespace Outer { using System; class C { void M() { // Note: IVsStatusBar is cased incorrectly. [|IVsStatusBar|] b; } } } ", @"namespace VS { interface IVsStatusbar { } } namespace Outer { using System; using VS; class C { void M() { // Note: IVsStatusBar is cased incorrectly. IVsStatusbar b; } } } ", testHost); } [Fact] [WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")] public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression() { var code = @" class C { private void GetEvaluationRuleNames() { [|IEnumerable|] < Int32 > return ImmutableArray.CreateRange(); } }"; await TestActionCountAsync(code, count: 1); await TestInRegularAndScriptAsync( code, @" using System.Collections.Generic; class C { private void GetEvaluationRuleNames() { IEnumerable < Int32 > return ImmutableArray.CreateRange(); } }"); } [Theory] [CombinatorialData] [WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")] public async Task TestWhenInRome1(TestHost testHost) { // System is set to be sorted first, but the actual file shows it at the end. // Keep things sorted, but respect that 'System' is at the end. await TestAsync( @" using B; using System; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @" using A; using B; using System; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")] public async Task TestWhenInRome2(TestHost testHost) { // System is set to not be sorted first, but the actual file shows it sorted first. // Keep things sorted, but respect that 'System' is at the beginning. await TestAsync( @" using System; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @" using System; using A; using B; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Fact] public async Task TestExactMatchNoGlyph() { await TestSmartTagGlyphTagsAsync( @"namespace VS { interface Other { } } class C { void M() { [|Other|] b; } } ", ImmutableArray<string>.Empty); } [Fact] public async Task TestFuzzyMatchGlyph() { await TestSmartTagGlyphTagsAsync( @"namespace VS { interface Other { } } class C { void M() { [|Otter|] b; } } ", WellKnownTagArrays.Namespace); } [Theory] [CombinatorialData] [WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")] public async Task TestGetAwaiterExtensionMethod1(TestHost testHost) { await TestAsync( @" namespace A { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { async Task M() => await [|Goo|]; C Goo { get; set; } } } namespace B { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using A; static class Extensions { public static Awaiter GetAwaiter(this C scheduler) => null; public class Awaiter : INotifyCompletion { public object GetResult() => null; public void OnCompleted(Action continuation) { } public bool IsCompleted => true; } } }", @" namespace A { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using B; class C { async Task M() => await Goo; C Goo { get; set; } } } namespace B { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using A; static class Extensions { public static Awaiter GetAwaiter(this C scheduler) => null; public class Awaiter : INotifyCompletion { public object GetResult() => null; public void OnCompleted(Action continuation) { } public bool IsCompleted => true; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")] public async Task TestGetAwaiterExtensionMethod2(TestHost testHost) { await TestAsync( @" namespace A { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { async Task M() => await [|GetC|](); C GetC() => null; } } namespace B { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using A; static class Extensions { public static Awaiter GetAwaiter(this C scheduler) => null; public class Awaiter : INotifyCompletion { public object GetResult() => null; public void OnCompleted(Action continuation) { } public bool IsCompleted => true; } } }", @" namespace A { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using B; class C { async Task M() => await GetC(); C GetC() => null; } } namespace B { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using A; static class Extensions { public static Awaiter GetAwaiter(this C scheduler) => null; public class Awaiter : INotifyCompletion { public object GetResult() => null; public void OnCompleted(Action continuation) { } public bool IsCompleted => true; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(745490, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/745490")] public async Task TestAddUsingForAwaitableReturningExtensionMethod(TestHost testHost) { await TestAsync( @" namespace A { using System; using System.Threading.Tasks; class C { C Instance { get; } async Task M() => await Instance.[|Foo|](); } } namespace B { using System; using System.Threading.Tasks; using A; static class Extensions { public static Task Foo(this C instance) => null; } }", @" namespace A { using System; using System.Threading.Tasks; using B; class C { C Instance { get; } async Task M() => await Instance.Foo(); } } namespace B { using System; using System.Threading.Tasks; using A; static class Extensions { public static Task Foo(this C instance) => null; } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetEnumeratorReturningIEnumerator(TestHost testHost) { await TestAsync( @" namespace A { class C { C Instance { get; } void M() { foreach (var i in [|Instance|]); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IEnumerator<int> GetEnumerator(this C instance) => null; } }", @" using B; namespace A { class C { C Instance { get; } void M() { foreach (var i in Instance); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IEnumerator<int> GetEnumerator(this C instance) => null; } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumerator(TestHost testHost) { await TestAsync( @" namespace A { class C { C Instance { get; } void M() { foreach (var i in [|Instance|]); } } } namespace B { using A; static class Extensions { public static Enumerator GetEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public bool MoveNext(); } }", @" using B; namespace A { class C { C Instance { get; } void M() { foreach (var i in Instance); } } } namespace B { using A; static class Extensions { public static Enumerator GetEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public bool MoveNext(); } }", testHost); } [Fact] public async Task TestMissingForExtensionInvalidGetEnumerator() { await TestMissingAsync( @" namespace A { class C { C Instance { get; } void M() { foreach (var i in [|Instance|]); } } } namespace B { using A; static class Extensions { public static bool GetEnumerator(this C instance) => null; } }"); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost) { await TestAsync( @" namespace A { class C { C Instance { get; }; void M() { foreach (var i in [|Instance|]); } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new Enumerator(); } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } } } namespace B { using A; static class Extensions { public static Enumerator GetEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public bool MoveNext(); } }", @" using B; namespace A { class C { C Instance { get; }; void M() { foreach (var i in Instance); } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new Enumerator(); } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } } } namespace B { using A; static class Extensions { public static Enumerator GetEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public bool MoveNext(); } }", testHost); } [Fact] public async Task TestMissingForExtensionGetAsyncEnumeratorOnForeach() { await TestMissingAsync( @" namespace A { class C { C Instance { get; } void M() { foreach (var i in [|Instance|]); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null; } }" + IAsyncEnumerable); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningIAsyncEnumerator(TestHost testHost) { await TestAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in [|Instance|]); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null; } }" + IAsyncEnumerable, @" using System.Threading.Tasks; using B; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in Instance); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null; } }" + IAsyncEnumerable, testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumerator(TestHost testHost) { await TestAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in [|Instance|]); } } } namespace B { using A; static class Extensions { public static Enumerator GetAsyncEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public Task<bool> MoveNextAsync(); } }", @" using System.Threading.Tasks; using B; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in Instance); } } } namespace B { using A; static class Extensions { public static Enumerator GetAsyncEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public Task<bool> MoveNextAsync(); } }", testHost); } [Fact] public async Task TestMissingForExtensionInvalidGetAsyncEnumerator() { await TestMissingAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in [|Instance|]); } } } namespace B { using A; static class Extensions { public static bool GetAsyncEnumerator(this C instance) => null; } }"); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost) { await TestAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } Task M() { await foreach (var i in [|Instance|]); } public Enumerator GetEnumerator() { return new Enumerator(); } public class Enumerator { public int Current { get; } public bool MoveNext(); } } } namespace B { using A; static class Extensions { public static Enumerator GetAsyncEnumerator(this C instance) => null; } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } }", @" using System.Threading.Tasks; using B; namespace A { class C { C Instance { get; } Task M() { await foreach (var i in Instance); } public Enumerator GetEnumerator() { return new Enumerator(); } public class Enumerator { public int Current { get; } public bool MoveNext(); } } } namespace B { using A; static class Extensions { public static Enumerator GetAsyncEnumerator(this C instance) => null; } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } }", testHost); } [Fact] public async Task TestMissingForExtensionGetEnumeratorOnAsyncForeach() { await TestMissingAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } Task M() { await foreach (var i in [|Instance|]); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IEnumerator<int> GetEnumerator(this C instance) => null; } }"); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithStaticUsingInNamespace_WhenNoExistingUsings(TestHost testHost) { await TestAsync( @" namespace N { using static System.Math; class C { public [|List<int>|] F; } } ", @" namespace N { using System.Collections.Generic; using static System.Math; class C { public List<int> F; } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithStaticUsingInInnerNestedNamespace_WhenNoExistingUsings(TestHost testHost) { await TestAsync( @" namespace N { namespace M { using static System.Math; class C { public [|List<int>|] F; } } } ", @" namespace N { namespace M { using System.Collections.Generic; using static System.Math; class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithStaticUsingInOuterNestedNamespace_WhenNoExistingUsings(TestHost testHost) { await TestAsync( @" namespace N { using static System.Math; namespace M { class C { public [|List<int>|] F; } } } ", @" namespace N { using System.Collections.Generic; using static System.Math; namespace M { class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenStaticUsingInNamespace(TestHost testHost) { await TestAsync( @" using System; namespace N { using static System.Math; class C { public [|List<int>|] F; } } ", @" using System; using System.Collections.Generic; namespace N { using static System.Math; class C { public List<int> F; } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInInnerNestedNamespace(TestHost testHost) { await TestAsync( @" namespace N { using System; namespace M { using static System.Math; class C { public [|List<int>|] F; } } } ", @" namespace N { using System; using System.Collections.Generic; namespace M { using static System.Math; class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInOuterNestedNamespace(TestHost testHost) { await TestAsync( @" namespace N { using static System.Math; namespace M { using System; class C { public [|List<int>|] F; } } } ", @" namespace N { using static System.Math; namespace M { using System; using System.Collections.Generic; class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithUsingAliasInNamespace_WhenNoExistingUsing(TestHost testHost) { await TestAsync( @" namespace N { using SAction = System.Action; class C { public [|List<int>|] F; } } ", @" namespace N { using System.Collections.Generic; using SAction = System.Action; class C { public List<int> F; } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithUsingAliasInInnerNestedNamespace_WhenNoExistingUsing(TestHost testHost) { await TestAsync( @" namespace N { namespace M { using SAction = System.Action; class C { public [|List<int>|] F; } } } ", @" namespace N { namespace M { using System.Collections.Generic; using SAction = System.Action; class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithUsingAliasInOuterNestedNamespace_WhenNoExistingUsing(TestHost testHost) { await TestAsync( @" namespace N { using SAction = System.Action; namespace M { class C { public [|List<int>|] F; } } } ", @" namespace N { using System.Collections.Generic; using SAction = System.Action; namespace M { class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenUsingAliasInNamespace(TestHost testHost) { await TestAsync( @" using System; namespace N { using SAction = System.Action; class C { public [|List<int>|] F; } } ", @" using System; using System.Collections.Generic; namespace N { using SAction = System.Action; class C { public List<int> F; } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInInnerNestedNamespace(TestHost testHost) { await TestAsync( @" namespace N { using System; namespace M { using SAction = System.Action; class C { public [|List<int>|] F; } } } ", @" namespace N { using System; using System.Collections.Generic; namespace M { using SAction = System.Action; class C { public [|List<int>|] F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInOuterNestedNamespace(TestHost testHost) { await TestAsync( @" namespace N { using SAction = System.Action; namespace M { using System; class C { public [|List<int>|] F; } } } ", @" namespace N { using SAction = System.Action; namespace M { using System; using System.Collections.Generic; class C { public [|List<int>|] F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] public async Task KeepUsingsGrouped1(TestHost testHost) { await TestAsync( @" using System; class Program { static void Main(string[] args) { [|Goo|] } } namespace Microsoft { public class Goo { } }", @" using System; using Microsoft; class Program { static void Main(string[] args) { Goo } } namespace Microsoft { public class Goo { } }", testHost); } [WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")] [Fact] public async Task TestIncompleteLambda1() { await TestInRegularAndScriptAsync( @"using System.Linq; class C { C() { """".Select(() => { new [|Byte|]", @"using System; using System.Linq; class C { C() { """".Select(() => { new Byte"); } [WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")] [Fact] public async Task TestIncompleteLambda2() { await TestInRegularAndScriptAsync( @"using System.Linq; class C { C() { """".Select(() => { new [|Byte|]() }", @"using System; using System.Linq; class C { C() { """".Select(() => { new Byte() }"); } [WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")] [WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")] [Fact] public async Task TestIncompleteSimpleLambdaExpression() { await TestInRegularAndScriptAsync( @"using System.Linq; class Program { static void Main(string[] args) { args[0].Any(x => [|IBindCtx|] string a; } }", @"using System.Linq; using System.Runtime.InteropServices.ComTypes; class Program { static void Main(string[] args) { args[0].Any(x => IBindCtx string a; } }"); } [Theory] [CombinatorialData] [WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableNeverSameProject(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> using System.ComponentModel; namespace ProjectLib { [EditorBrowsable(EditorBrowsableState.Never)] public class Project { } } </Document> <Document FilePath=""Program.cs""> class Program { static void Main(string[] args) { Project p = new [|Project()|]; } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @" using ProjectLib; class Program { static void Main(string[] args) { Project p = new [|Project()|]; } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableNeverDifferentProject(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.vb""> imports System.ComponentModel namespace ProjectLib &lt;EditorBrowsable(EditorBrowsableState.Never)&gt; public class Project end class end namespace </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference>lib</ProjectReference> <Document FilePath=""Program.cs""> class Program { static void Main(string[] args) { [|Project|] p = new Project(); } } </Document> </Project> </Workspace>"; await TestMissingAsync(InitialWorkspace, new TestParameters(testHost: testHost)); } [Theory] [CombinatorialData] [WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.vb""> imports System.ComponentModel namespace ProjectLib &lt;EditorBrowsable(EditorBrowsableState.Advanced)&gt; public class Project end class end namespace </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference>lib</ProjectReference> <Document FilePath=""Program.cs""> class Program { static void Main(string[] args) { [|Project|] p = new Project(); } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @" using ProjectLib; class Program { static void Main(string[] args) { Project p = new [|Project()|]; } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.vb""> imports System.ComponentModel namespace ProjectLib &lt;EditorBrowsable(EditorBrowsableState.Advanced)&gt; public class Project end class end namespace </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference>lib</ProjectReference> <Document FilePath=""Program.cs""> class Program { static void Main(string[] args) { [|Project|] p = new Project(); } } </Document> </Project> </Workspace>"; await TestMissingAsync(InitialWorkspace, new TestParameters( options: Option(CompletionOptions.HideAdvancedMembers, true), testHost: testHost)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests : AbstractAddUsingTests { public AddUsingTests(ITestOutputHelper logger) : base(logger) { } [Theory] [CombinatorialData] public async Task TestTypeFromMultipleNamespaces1(TestHost testHost) { await TestAsync( @"class Class { [|IDictionary|] Method() { Goo(); } }", @"using System.Collections; class Class { IDictionary Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Outer(TestHost testHost) { await TestAsync( @" namespace N; class Class { [|IDictionary|] Method() { Goo(); } }", @" using System.Collections; namespace N; class Class { IDictionary Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Inner(TestHost testHost) { await TestAsync( @" namespace N; using System; class Class { [|IDictionary|] Method() { Goo(); } }", @" namespace N; using System; using System.Collections; class Class { IDictionary Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(11241, "https://github.com/dotnet/roslyn/issues/11241")] public async Task TestAddImportWithCaseChange(TestHost testHost) { await TestAsync( @"namespace N1 { public class TextBox { } } class Class1 : [|Textbox|] { }", @"using N1; namespace N1 { public class TextBox { } } class Class1 : TextBox { }", testHost); } [Theory] [CombinatorialData] public async Task TestTypeFromMultipleNamespaces2(TestHost testHost) { await TestAsync( @"class Class { [|IDictionary|] Method() { Goo(); } }", @"using System.Collections.Generic; class Class { IDictionary Method() { Goo(); } }", testHost, index: 1); } [Theory] [CombinatorialData] public async Task TestGenericWithNoArgs(TestHost testHost) { await TestAsync( @"class Class { [|List|] Method() { Goo(); } }", @"using System.Collections.Generic; class Class { List Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenericWithCorrectArgs(TestHost testHost) { await TestAsync( @"class Class { [|List<int>|] Method() { Goo(); } }", @"using System.Collections.Generic; class Class { List<int> Method() { Goo(); } }", testHost); } [Fact] public async Task TestGenericWithWrongArgs1() { await TestMissingInRegularAndScriptAsync( @"class Class { [|List<int, string, bool>|] Method() { Goo(); } }"); } [Fact] public async Task TestGenericWithWrongArgs2() { await TestMissingInRegularAndScriptAsync( @"class Class { [|List<int, string>|] Method() { Goo(); } }"); } [Theory] [CombinatorialData] public async Task TestGenericInLocalDeclaration(TestHost testHost) { await TestAsync( @"class Class { void Goo() { [|List<int>|] a = new List<int>(); } }", @"using System.Collections.Generic; class Class { void Goo() { List<int> a = new List<int>(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenericItemType(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Class { List<[|Int32|]> l; }", @"using System; using System.Collections.Generic; class Class { List<Int32> l; }", testHost); } [Theory] [CombinatorialData] public async Task TestGenerateWithExistingUsings(TestHost testHost) { await TestAsync( @"using System; class Class { [|List<int>|] Method() { Goo(); } }", @"using System; using System.Collections.Generic; class Class { List<int> Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenerateInNamespace(TestHost testHost) { await TestAsync( @"namespace N { class Class { [|List<int>|] Method() { Goo(); } } }", @"using System.Collections.Generic; namespace N { class Class { List<int> Method() { Goo(); } } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenerateInNamespaceWithUsings(TestHost testHost) { await TestAsync( @"namespace N { using System; class Class { [|List<int>|] Method() { Goo(); } } }", @"namespace N { using System; using System.Collections.Generic; class Class { List<int> Method() { Goo(); } } }", testHost); } [Fact] public async Task TestExistingUsing_ActionCount() { await TestActionCountAsync( @"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Goo(); } }", count: 1); } [Theory] [CombinatorialData] public async Task TestExistingUsing(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Goo(); } }", @"using System.Collections; using System.Collections.Generic; class Class { IDictionary Method() { Goo(); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] public async Task TestAddUsingForGenericExtensionMethod(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Class { void Method(IList<int> args) { args.[|Where|]() } }", @"using System.Collections.Generic; using System.Linq; class Class { void Method(IList<int> args) { args.Where() } }", testHost); } [Fact] [WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] public async Task TestAddUsingForNormalExtensionMethod() { await TestAsync( @"class Class { void Method(Class args) { args.[|Where|]() } } namespace N { static class E { public static void Where(this Class c) { } } }", @"using N; class Class { void Method(Class args) { args.Where() } } namespace N { static class E { public static void Where(this Class c) { } } }", parseOptions: Options.Regular); } [Theory] [CombinatorialData] public async Task TestOnEnum(TestHost testHost) { await TestAsync( @"class Class { void Goo() { var a = [|Colors|].Red; } } namespace A { enum Colors { Red, Green, Blue } }", @"using A; class Class { void Goo() { var a = Colors.Red; } } namespace A { enum Colors { Red, Green, Blue } }", testHost); } [Theory] [CombinatorialData] public async Task TestOnClassInheritance(TestHost testHost) { await TestAsync( @"class Class : [|Class2|] { } namespace A { class Class2 { } }", @"using A; class Class : Class2 { } namespace A { class Class2 { } }", testHost); } [Theory] [CombinatorialData] public async Task TestOnImplementedInterface(TestHost testHost) { await TestAsync( @"class Class : [|IGoo|] { } namespace A { interface IGoo { } }", @"using A; class Class : IGoo { } namespace A { interface IGoo { } }", testHost); } [Theory] [CombinatorialData] public async Task TestAllInBaseList(TestHost testHost) { await TestAsync( @"class Class : [|IGoo|], Class2 { } namespace A { class Class2 { } } namespace B { interface IGoo { } }", @"using B; class Class : IGoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IGoo { } }", testHost); await TestAsync( @"using B; class Class : IGoo, [|Class2|] { } namespace A { class Class2 { } } namespace B { interface IGoo { } }", @"using A; using B; class Class : IGoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IGoo { } }", testHost); } [Theory] [CombinatorialData] public async Task TestAttributeUnexpanded(TestHost testHost) { await TestAsync( @"[[|Obsolete|]] class Class { }", @"using System; [Obsolete] class Class { }", testHost); } [Theory] [CombinatorialData] public async Task TestAttributeExpanded(TestHost testHost) { await TestAsync( @"[[|ObsoleteAttribute|]] class Class { }", @"using System; [ObsoleteAttribute] class Class { }", testHost); } [Theory] [CombinatorialData] [WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")] public async Task TestAfterNew(TestHost testHost) { await TestAsync( @"class Class { void Goo() { List<int> l; l = new [|List<int>|](); } }", @"using System.Collections.Generic; class Class { void Goo() { List<int> l; l = new List<int>(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestArgumentsInMethodCall(TestHost testHost) { await TestAsync( @"class Class { void Test() { Console.WriteLine([|DateTime|].Today); } }", @"using System; class Class { void Test() { Console.WriteLine(DateTime.Today); } }", testHost); } [Theory] [CombinatorialData] public async Task TestCallSiteArgs(TestHost testHost) { await TestAsync( @"class Class { void Test([|DateTime|] dt) { } }", @"using System; class Class { void Test(DateTime dt) { } }", testHost); } [Theory] [CombinatorialData] public async Task TestUsePartialClass(TestHost testHost) { await TestAsync( @"namespace A { public class Class { [|PClass|] c; } } namespace B { public partial class PClass { } }", @"using B; namespace A { public class Class { PClass c; } } namespace B { public partial class PClass { } }", testHost); } [Theory] [CombinatorialData] public async Task TestGenericClassInNestedNamespace(TestHost testHost) { await TestAsync( @"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { [|GenericClass<int>|] c; } }", @"using A.B; namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { GenericClass<int> c; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] public async Task TestExtensionMethods(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Goo { void Bar() { var values = new List<int>(); values.[|Where|](i => i > 1); } }", @"using System.Collections.Generic; using System.Linq; class Goo { void Bar() { var values = new List<int>(); values.Where(i => i > 1); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] public async Task TestQueryPatterns(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class Goo { void Bar() { var values = new List<int>(); var q = [|from v in values where v > 1 select v + 10|]; } }", @"using System.Collections.Generic; using System.Linq; class Goo { void Bar() { var values = new List<int>(); var q = from v in values where v > 1 select v + 10; } }", testHost); } // Tests for Insertion Order [Theory] [CombinatorialData] public async Task TestSimplePresortedUsings1(TestHost testHost) { await TestAsync( @"using B; using C; class Class { void Method() { [|Goo|].Bar(); } } namespace D { class Goo { public static void Bar() { } } }", @"using B; using C; using D; class Class { void Method() { Goo.Bar(); } } namespace D { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimplePresortedUsings2(TestHost testHost) { await TestAsync( @"using B; using C; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using A; using B; using C; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleUnsortedUsings1(TestHost testHost) { await TestAsync( @"using C; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using C; using B; using A; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleUnsortedUsings2(TestHost testHost) { await TestAsync( @"using D; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace C { class Goo { public static void Bar() { } } }", @"using D; using B; using C; class Class { void Method() { Goo.Bar(); } } namespace C { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultiplePresortedUsings1(TestHost testHost) { await TestAsync( @"using B.X; using B.Y; class Class { void Method() { [|Goo|].Bar(); } } namespace B { class Goo { public static void Bar() { } } }", @"using B; using B.X; using B.Y; class Class { void Method() { Goo.Bar(); } } namespace B { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultiplePresortedUsings2(TestHost testHost) { await TestAsync( @"using B.X; using B.Y; class Class { void Method() { [|Goo|].Bar(); } } namespace B.A { class Goo { public static void Bar() { } } }", @"using B.A; using B.X; using B.Y; class Class { void Method() { Goo.Bar(); } } namespace B.A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultiplePresortedUsings3(TestHost testHost) { await TestAsync( @"using B.X; using B.Y; class Class { void Method() { [|Goo|].Bar(); } } namespace B { namespace A { class Goo { public static void Bar() { } } } }", @"using B.A; using B.X; using B.Y; class Class { void Method() { Goo.Bar(); } } namespace B { namespace A { class Goo { public static void Bar() { } } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultipleUnsortedUsings1(TestHost testHost) { await TestAsync( @"using B.Y; using B.X; class Class { void Method() { [|Goo|].Bar(); } } namespace B { namespace A { class Goo { public static void Bar() { } } } }", @"using B.Y; using B.X; using B.A; class Class { void Method() { Goo.Bar(); } } namespace B { namespace A { class Goo { public static void Bar() { } } } }", testHost); } [Theory] [CombinatorialData] public async Task TestMultipleUnsortedUsings2(TestHost testHost) { await TestAsync( @"using B.Y; using B.X; class Class { void Method() { [|Goo|].Bar(); } } namespace B { class Goo { public static void Bar() { } } }", @"using B.Y; using B.X; using B; class Class { void Method() { Goo.Bar(); } } namespace B { class Goo { public static void Bar() { } } }", testHost); } // System on top cases [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings1(TestHost testHost) { await TestAsync( @"using System; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using System; using A; using B; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings2(TestHost testHost) { await TestAsync( @"using System; using System.Collections.Generic; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using System; using System.Collections.Generic; using A; using B; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings3(TestHost testHost) { await TestAsync( @"using A; using B; class Class { void Method() { [|Console|].Write(1); } }", @"using System; using A; using B; class Class { void Method() { Console.Write(1); } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemUnsortedUsings1(TestHost testHost) { await TestAsync( @" using C; using B; using System; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @" using C; using B; using System; using A; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemUnsortedUsings2(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; using System; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using System.Collections.Generic; using System; using B; using A; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemUnsortedUsings3(TestHost testHost) { await TestAsync( @"using B; using A; class Class { void Method() { [|Console|].Write(1); } }", @"using B; using A; using System; class Class { void Method() { Console.Write(1); } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleBogusSystemUsings1(TestHost testHost) { await TestAsync( @"using A.System; class Class { void Method() { [|Console|].Write(1); } }", @"using System; using A.System; class Class { void Method() { Console.Write(1); } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleBogusSystemUsings2(TestHost testHost) { await TestAsync( @"using System.System; class Class { void Method() { [|Console|].Write(1); } }", @"using System; using System.System; class Class { void Method() { Console.Write(1); } }", testHost); } [Theory] [CombinatorialData] public async Task TestUsingsWithComments(TestHost testHost) { await TestAsync( @"using System./*...*/.Collections.Generic; class Class { void Method() { [|Console|].Write(1); } }", @"using System; using System./*...*/.Collections.Generic; class Class { void Method() { Console.Write(1); } }", testHost); } // System Not on top cases [Theory] [CombinatorialData] public async Task TestSimpleSystemUnsortedUsings4(TestHost testHost) { await TestAsync( @" using C; using System; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @" using C; using System; using B; using A; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings5(TestHost testHost) { await TestAsync( @"using B; using System; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @"using A; using B; using System; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] public async Task TestSimpleSystemSortedUsings4(TestHost testHost) { await TestAsync( @"using A; using B; class Class { void Method() { [|Console|].Write(1); } }", @"using A; using B; using System; class Class { void Method() { Console.Write(1); } }", testHost, options: Option(GenerationOptions.PlaceSystemNamespaceFirst, false)); } [Fact] [WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")] [WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] public async Task TestAddUsingForNamespace() { await TestMissingInRegularAndScriptAsync( @"namespace A { class Class { [|C|].Test t; } } namespace B { namespace C { class Test { } } }"); } [Theory] [CombinatorialData] [WorkItem(538220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538220")] public async Task TestAddUsingForFieldWithFormatting(TestHost testHost) { await TestAsync( @"class C { [|DateTime|] t; }", @"using System; class C { DateTime t; }", testHost); } [Theory] [CombinatorialData] [WorkItem(539657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539657")] public async Task BugFix5688(TestHost testHost) { await TestAsync( @"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } } ", @"using System; class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = ""\r\n\r\n"" ; } } ", testHost); } [Fact] [WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")] public async Task BugFix5950() { await TestAsync( @"using System.Console; WriteLine([|Expression|].Constant(123));", @"using System.Console; using System.Linq.Expressions; WriteLine(Expression.Constant(123));", parseOptions: GetScriptOptions()); } [Theory] [CombinatorialData] [WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")] public async Task TestAddAfterDefineDirective1(TestHost testHost) { await TestAsync( @"#define goo using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")] public async Task TestAddAfterDefineDirective2(TestHost testHost) { await TestAsync( @"#define goo class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo using System; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterDefineDirective3(TestHost testHost) { await TestAsync( @"#define goo /// Goo class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo using System; /// Goo class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterDefineDirective4(TestHost testHost) { await TestAsync( @"#define goo // Goo class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo // Goo using System; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterExistingBanner(TestHost testHost) { await TestAsync( @"// Banner // Banner class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"// Banner // Banner using System; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterExternAlias1(TestHost testHost) { await TestAsync( @"#define goo extern alias Goo; class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo extern alias Goo; using System; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddAfterExternAlias2(TestHost testHost) { await TestAsync( @"#define goo extern alias Goo; using System.Collections; class Program { static void Main(string[] args) { [|Console|].WriteLine(); } }", @"#define goo extern alias Goo; using System; using System.Collections; class Program { static void Main(string[] args) { Console.WriteLine(); } }", testHost); } [Fact] public async Task TestWithReferenceDirective() { var resolver = new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>() { { "exprs", AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference() } }); await TestAsync( @"#r ""exprs"" [|Expression|]", @"#r ""exprs"" using System.Linq.Expressions; Expression", GetScriptOptions(), TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); } [Theory] [CombinatorialData] [WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")] public async Task TestAssemblyAttribute(TestHost testHost) { await TestAsync( @"[assembly: [|InternalsVisibleTo|](""Project"")]", @"using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Project"")]", testHost); } [Fact] public async Task TestDoNotAddIntoHiddenRegion() { await TestMissingInRegularAndScriptAsync( @"#line hidden using System.Collections.Generic; #line default class Program { void Main() { [|DateTime|] d; } }"); } [Theory] [CombinatorialData] public async Task TestAddToVisibleRegion(TestHost testHost) { await TestAsync( @"#line default using System.Collections.Generic; #line hidden class Program { void Main() { #line default [|DateTime|] d; #line hidden } } #line default", @"#line default using System; using System.Collections.Generic; #line hidden class Program { void Main() { #line default DateTime d; #line hidden } } #line default", testHost); } [Fact] [WorkItem(545248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545248")] public async Task TestVenusGeneration1() { await TestMissingInRegularAndScriptAsync( @"class C { void Goo() { #line 1 ""Default.aspx"" using (new [|StreamReader|]()) { #line default #line hidden } }"); } [Fact] [WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] public async Task TestAttribute_ActionCount() { var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] "; await TestActionCountAsync(input, 2); } [Theory] [CombinatorialData] [WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] public async Task TestAttribute(TestHost testHost) { var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] "; await TestAsync( input, @"using System.Runtime.InteropServices; [ assembly : Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost); } [Fact] [WorkItem(546833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546833")] public async Task TestNotOnOverloadResolutionError() { await TestMissingInRegularAndScriptAsync( @"namespace ConsoleApplication1 { class Program { void Main() { var test = new [|Test|](""""); } } class Test { } }"); } [Theory] [CombinatorialData] [WorkItem(17020, "DevDiv_Projects/Roslyn")] public async Task TestAddUsingForGenericArgument(TestHost testHost) { await TestAsync( @"namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var inArgument = new InArgument<[|IEnumerable<int>|]>(new int[] { 1, 2, 3 }); } } public class InArgument<T> { public InArgument(T constValue) { } } }", @"using System.Collections.Generic; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var inArgument = new InArgument<IEnumerable<int>>(new int[] { 1, 2, 3 }); } } public class InArgument<T> { public InArgument(T constValue) { } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")] public async Task ShouldTriggerOnCS0308(TestHost testHost) { // CS0308: The non-generic type 'A' cannot be used with type arguments await TestAsync( @"using System.Collections; class Test { static void Main(string[] args) { [|IEnumerable<int>|] f; } }", @"using System.Collections; using System.Collections.Generic; class Test { static void Main(string[] args) { IEnumerable<int> f; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(838253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838253")] public async Task TestConflictedInaccessibleType(TestHost testHost) { await TestAsync( @"using System.Diagnostics; namespace N { public class Log { } } class C { static void Main(string[] args) { [|Log|] } }", @"using System.Diagnostics; using N; namespace N { public class Log { } } class C { static void Main(string[] args) { Log } }", testHost); } [Theory] [CombinatorialData] [WorkItem(858085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858085")] public async Task TestConflictedAttributeName(TestHost testHost) { await TestAsync( @"[[|Description|]] class Description { }", @"using System.ComponentModel; [Description] class Description { }", testHost); } [Theory] [CombinatorialData] [WorkItem(872908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872908")] public async Task TestConflictedGenericName(TestHost testHost) { await TestAsync( @"using Task = System.AccessViolationException; class X { [|Task<X> x;|] }", @"using System.Threading.Tasks; using Task = System.AccessViolationException; class X { Task<X> x; }", testHost); } [Fact] [WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")] public async Task TestNoDuplicateReport_ActionCount() { await TestActionCountInAllFixesAsync( @"class C { void M(P p) { [|Console|] } static void Main(string[] args) { } }", count: 1); } [Theory] [CombinatorialData] [WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")] public async Task TestNoDuplicateReport(TestHost testHost) { await TestAsync( @"class C { void M(P p) { [|Console|] } static void Main(string[] args) { } }", @"using System; class C { void M(P p) { Console } static void Main(string[] args) { } }", testHost); } [Fact] [WorkItem(938296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938296")] public async Task TestNullParentInNode() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class MultiDictionary<K, V> : Dictionary<K, HashSet<V>> { void M() { new HashSet<V>([|Comparer|]); } }"); } [Fact] [WorkItem(968303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968303")] public async Task TestMalformedUsingSection() { await TestMissingInRegularAndScriptAsync( @"[ class Class { [|List<|] }"); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithExternAlias(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace ProjectLib { public class Project { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> namespace ExternAliases { class Program { static void Main(string[] args) { Project p = new [|Project()|]; } } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @"extern alias P; using P::ProjectLib; namespace ExternAliases { class Program { static void Main(string[] args) { Project p = new Project(); } } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithPreExistingExternAlias(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace ProjectLib { public class Project { } } namespace AnotherNS { public class AnotherClass { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> extern alias P; using P::ProjectLib; namespace ExternAliases { class Program { static void Main(string[] args) { Project p = new Project(); var x = new [|AnotherClass()|]; } } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @" extern alias P; using P::AnotherNS; using P::ProjectLib; namespace ExternAliases { class Program { static void Main(string[] args) { Project p = new Project(); var x = new [|AnotherClass()|]; } } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithPreExistingExternAlias_FileScopedNamespace(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace ProjectLib; { public class Project { } } namespace AnotherNS { public class AnotherClass { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> extern alias P; using P::ProjectLib; namespace ExternAliases; class Program { static void Main(string[] args) { Project p = new Project(); var x = new [|AnotherClass()|]; } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @" extern alias P; using P::AnotherNS; using P::ProjectLib; namespace ExternAliases; class Program { static void Main(string[] args) { Project p = new Project(); var x = new [|AnotherClass()|]; } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsNoExtern(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace AnotherNS { public class AnotherClass { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> using P::AnotherNS; namespace ExternAliases { class Program { static void Main(string[] args) { var x = new [|AnotherClass()|]; } } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @"extern alias P; using P::AnotherNS; namespace ExternAliases { class Program { static void Main(string[] args) { var x = new AnotherClass(); } } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsNoExtern_FileScopedNamespace(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> namespace AnotherNS; public class AnotherClass { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference Alias=""P"">lib</ProjectReference> <Document FilePath=""Program.cs""> using P::AnotherNS; namespace ExternAliases; class Program { static void Main(string[] args) { var x = new [|AnotherClass()|]; } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @"extern alias P; using P::AnotherNS; namespace ExternAliases; class Program { static void Main(string[] args) { var x = new AnotherClass(); } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsNoExternFilterGlobalAlias(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { [|INotifyPropertyChanged.PropertyChanged|] } }", @"using System.ComponentModel; class Program { static void Main(string[] args) { INotifyPropertyChanged.PropertyChanged } }", testHost); } [Fact] [WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref() { var initialText = @"/// <summary> /// This is just like <see cref='[|INotifyPropertyChanged|]'/>, but this one is mine. /// </summary> interface MyNotifyPropertyChanged { }"; var expectedText = @"using System.ComponentModel; /// <summary> /// This is just like <see cref='INotifyPropertyChanged'/>, but this one is mine. /// </summary> interface MyNotifyPropertyChanged { }"; var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); await TestAsync(initialText, expectedText, parseOptions: options); } [Fact] [WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref2() { var initialText = @"/// <summary> /// This is just like <see cref='[|INotifyPropertyChanged.PropertyChanged|]'/>, but this one is mine. /// </summary> interface MyNotifyPropertyChanged { }"; var expectedText = @"using System.ComponentModel; /// <summary> /// This is just like <see cref='INotifyPropertyChanged.PropertyChanged'/>, but this one is mine. /// </summary> interface MyNotifyPropertyChanged { }"; var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); await TestAsync(initialText, expectedText, parseOptions: options); } [Fact] [WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref3() { var initialText = @"namespace N1 { public class D { } } public class MyClass { public static explicit operator N1.D (MyClass f) { return default(N1.D); } } /// <seealso cref='MyClass.explicit operator [|D(MyClass)|]'/> public class MyClass2 { }"; var expectedText = @"using N1; namespace N1 { public class D { } } public class MyClass { public static explicit operator N1.D (MyClass f) { return default(N1.D); } } /// <seealso cref='MyClass.explicit operator D(MyClass)'/> public class MyClass2 { }"; var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); await TestAsync(initialText, expectedText, parseOptions: options); } [Fact] [WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref4() { var initialText = @"namespace N1 { public class D { } } /// <seealso cref='[|Test(D)|]'/> public class MyClass { public void Test(N1.D i) { } }"; var expectedText = @"using N1; namespace N1 { public class D { } } /// <seealso cref='Test(D)'/> public class MyClass { public void Test(N1.D i) { } }"; var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); await TestAsync(initialText, expectedText, parseOptions: options); } [Theory] [CombinatorialData] [WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] public async Task TestAddStaticType(TestHost testHost) { var initialText = @"using System; public static class Outer { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } [[|My|]] class Test {}"; var expectedText = @"using System; using static Outer; public static class Outer { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } [My] class Test {}"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] public async Task TestAddStaticType2(TestHost testHost) { var initialText = @"using System; public static class Outer { public static class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [[|My|]] class Test {}"; var expectedText = @"using System; using static Outer.Inner; public static class Outer { public static class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [My] class Test {}"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] public async Task TestAddStaticType3(TestHost testHost) { await TestAsync( @"using System; public static class Outer { public class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [[|My|]] class Test { }", @"using System; using static Outer.Inner; public static class Outer { public class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [My] class Test { }", testHost); } [Theory] [CombinatorialData] [WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] public async Task TestAddStaticType4(TestHost testHost) { var initialText = @"using System; using Outer; public static class Outer { public static class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [[|My|]] class Test {}"; var expectedText = @"using System; using Outer; using static Outer.Inner; public static class Outer { public static class Inner { [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { } } } [My] class Test {}"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective1(TestHost testHost) { await TestAsync( @"namespace ns { using B = [|Byte|]; }", @"using System; namespace ns { using B = Byte; }", testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective2(TestHost testHost) { await TestAsync( @"using System.Collections; namespace ns { using B = [|Byte|]; }", @"using System; using System.Collections; namespace ns { using B = Byte; }", testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective3(TestHost testHost) { await TestAsync( @"namespace ns2 { namespace ns3 { namespace ns { using B = [|Byte|]; namespace ns4 { } } } }", @"using System; namespace ns2 { namespace ns3 { namespace ns { using B = Byte; namespace ns4 { } } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective4(TestHost testHost) { await TestAsync( @"namespace ns2 { using System.Collections; namespace ns3 { namespace ns { using System.IO; using B = [|Byte|]; } } }", @"namespace ns2 { using System; using System.Collections; namespace ns3 { namespace ns { using System.IO; using B = Byte; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective5(TestHost testHost) { await TestAsync( @"using System.IO; namespace ns2 { using System.Diagnostics; namespace ns3 { using System.Collections; namespace ns { using B = [|Byte|]; } } }", @"using System.IO; namespace ns2 { using System.Diagnostics; namespace ns3 { using System; using System.Collections; namespace ns { using B = Byte; } } }", testHost); } [Fact] [WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] public async Task TestAddInsideUsingDirective6() { await TestMissingInRegularAndScriptAsync( @"using B = [|Byte|];"); } [Theory] [CombinatorialData] [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] public async Task TestAddConditionalAccessExpression(TestHost testHost) { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> public class C { void Main(C a) { C x = a?[|.B()|]; } } </Document> <Document FilePath = ""Extensions""> namespace Extensions { public static class E { public static C B(this C c) { return c; } } } </Document> </Project> </Workspace> "; var expectedText = @" using Extensions; public class C { void Main(C a) { C x = a?.B(); } } "; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] public async Task TestAddConditionalAccessExpression2(TestHost testHost) { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> public class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.[|C()|]; } public class E { } } </Document> <Document FilePath = ""Extensions""> namespace Extensions { public static class D { public static C.E C(this C.E c) { return c; } } } </Document> </Project> </Workspace> "; var expectedText = @" using Extensions; public class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.C(); } public class E { } } "; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1089138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089138")] public async Task TestAmbiguousUsingName(TestHost testHost) { await TestAsync( @"namespace ClassLibrary1 { using System; public class SomeTypeUser { [|SomeType|] field; } } namespace SubNamespaceName { using System; class SomeType { } } namespace ClassLibrary1.SubNamespaceName { using System; class SomeOtherFile { } }", @"namespace ClassLibrary1 { using System; using global::SubNamespaceName; public class SomeTypeUser { SomeType field; } } namespace SubNamespaceName { using System; class SomeType { } } namespace ClassLibrary1.SubNamespaceName { using System; class SomeOtherFile { } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingInDirective(TestHost testHost) { await TestAsync( @"#define DEBUG #if DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Text; #endif class Program { static void Main(string[] args) { var a = [|File|].OpenRead(""""); } }", @"#define DEBUG #if DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Text; using System.IO; #endif class Program { static void Main(string[] args) { var a = File.OpenRead(""""); } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingInDirective2(TestHost testHost) { await TestAsync( @"#define DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; #if DEBUG using System.Text; #endif class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", @"#define DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; #if DEBUG using System.Text; #endif class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingInDirective3(TestHost testHost) { await TestAsync( @"#define DEBUG using System; using System.Collections.Generic; #if DEBUG using System.Text; #endif using System.Linq; using System.Threading.Tasks; class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", @"#define DEBUG using System; using System.Collections.Generic; #if DEBUG using System.Text; #endif using System.Linq; using System.Threading.Tasks; using System.IO; class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingInDirective4(TestHost testHost) { await TestAsync( @"#define DEBUG #if DEBUG using System; #endif using System.Collections.Generic; using System.Text; using System.Linq; using System.Threading.Tasks; class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", @"#define DEBUG #if DEBUG using System; #endif using System.Collections.Generic; using System.Text; using System.Linq; using System.Threading.Tasks; using System.IO; class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); } [Fact] public async Task TestInaccessibleExtensionMethod() { const string initial = @" namespace N1 { public static class C { private static bool ExtMethod1(this string arg1) { return true; } } } namespace N2 { class Program { static void Main(string[] args) { var x = ""str1"".[|ExtMethod1()|]; } } }"; await TestMissingInRegularAndScriptAsync(initial); } [Theory] [CombinatorialData] [WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")] public async Task TestAddUsingForProperty(TestHost testHost) { await TestAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public BindingFlags BindingFlags { get { return BindingFlags.[|Instance|]; } } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; class Program { public BindingFlags BindingFlags { get { return BindingFlags.Instance; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")] public async Task TestAddUsingForField(TestHost testHost) { await TestAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public B B { get { return B.[|Instance|]; } } } namespace A { public class B { public static readonly B Instance; } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using A; class Program { public B B { get { return B.Instance; } } } namespace A { public class B { public static readonly B Instance; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(1893, "https://github.com/dotnet/roslyn/issues/1893")] public async Task TestNameSimplification(TestHost testHost) { // Generated using directive must be simplified from "using A.B;" to "using B;" below. await TestAsync( @"namespace A.B { class T1 { } } namespace A.C { using System; class T2 { void Test() { Console.WriteLine(); [|T1|] t1; } } }", @"namespace A.B { class T1 { } } namespace A.C { using System; using A.B; class T2 { void Test() { Console.WriteLine(); T1 t1; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")] public async Task TestAddUsingWithOtherExtensionsInScope(TestHost testHost) { await TestAsync( @"using System.Linq; using System.Collections; using X; namespace X { public static class Ext { public static void ExtMethod(this int a) { } } } namespace Y { public static class Ext { public static void ExtMethod(this int a, int v) { } } } public class B { static void Main() { var b = 0; b.[|ExtMethod|](0); } }", @"using System.Linq; using System.Collections; using X; using Y; namespace X { public static class Ext { public static void ExtMethod(this int a) { } } } namespace Y { public static class Ext { public static void ExtMethod(this int a, int v) { } } } public class B { static void Main() { var b = 0; b.ExtMethod(0); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")] public async Task TestAddUsingWithOtherExtensionsInScope2(TestHost testHost) { await TestAsync( @"using System.Linq; using System.Collections; using X; namespace X { public static class Ext { public static void ExtMethod(this int? a) { } } } namespace Y { public static class Ext { public static void ExtMethod(this int? a, int v) { } } } public class B { static void Main() { var b = new int?(); b?[|.ExtMethod|](0); } }", @"using System.Linq; using System.Collections; using X; using Y; namespace X { public static class Ext { public static void ExtMethod(this int? a) { } } } namespace Y { public static class Ext { public static void ExtMethod(this int? a, int v) { } } } public class B { static void Main() { var b = new int?(); b?.ExtMethod(0); } }", testHost); } [Theory] [CombinatorialData] [WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")] public async Task TestAddUsingWithOtherExtensionsInScope3(TestHost testHost) { await TestAsync( @"using System.Linq; class C { int i = 0.[|All|](); } namespace X { static class E { public static int All(this int o) => 0; } }", @"using System.Linq; using X; class C { int i = 0.All(); } namespace X { static class E { public static int All(this int o) => 0; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")] public async Task TestAddUsingWithOtherExtensionsInScope4(TestHost testHost) { await TestAsync( @"using System.Linq; class C { static void Main(string[] args) { var a = new int?(); int? i = a?[|.All|](); } } namespace X { static class E { public static int? All(this int? o) => 0; } }", @"using System.Linq; using X; class C { static void Main(string[] args) { var a = new int?(); int? i = a?.All(); } } namespace X { static class E { public static int? All(this int? o) => 0; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using Win32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using Microsoft.Win32.SafeHandles; using Win32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified2(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using Zin32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using Microsoft.Win32.SafeHandles; using Zin32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified3(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using System; using Win32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using System; using Microsoft.Win32.SafeHandles; using Win32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified4(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using System; using Zin32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using System; using Microsoft.Win32.SafeHandles; using Zin32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified5(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { #if true using Win32; #else using System; #endif class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using Microsoft.Win32.SafeHandles; #if true using Win32; #else using System; #endif class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")] public async Task TestNestedNamespaceSimplified6(TestHost testHost) { await TestAsync( @"namespace Microsoft.MyApp { using System; #if false using Win32; #endif using Win32; class Program { static void Main(string[] args) { [|SafeRegistryHandle|] h; } } }", @"namespace Microsoft.MyApp { using System; using Microsoft.Win32.SafeHandles; #if false using Win32; #endif using Win32; class Program { static void Main(string[] args) { SafeRegistryHandle h; } } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingOrdinalUppercase(TestHost testHost) { await TestAsync( @"namespace A { class A { static void Main(string[] args) { var b = new [|B|](); } } } namespace lowercase { class b { } } namespace Uppercase { class B { } }", @"using Uppercase; namespace A { class A { static void Main(string[] args) { var b = new B(); } } } namespace lowercase { class b { } } namespace Uppercase { class B { } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingOrdinalLowercase(TestHost testHost) { await TestAsync( @"namespace A { class A { static void Main(string[] args) { var a = new [|b|](); } } } namespace lowercase { class b { } } namespace Uppercase { class B { } }", @"using lowercase; namespace A { class A { static void Main(string[] args) { var a = new b(); } } } namespace lowercase { class b { } } namespace Uppercase { class B { } }", testHost); } [Theory] [CombinatorialData] [WorkItem(7443, "https://github.com/dotnet/roslyn/issues/7443")] public async Task TestWithExistingIncompatibleExtension(TestHost testHost) { await TestAsync( @"using N; class C { int x() { System.Collections.Generic.IEnumerable<int> x = null; return x.[|Any|] } } namespace N { static class Extensions { public static void Any(this string s) { } } }", @"using System.Linq; using N; class C { int x() { System.Collections.Generic.IEnumerable<int> x = null; return x.Any } } namespace N { static class Extensions { public static void Any(this string s) { } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(1744, @"https://github.com/dotnet/roslyn/issues/1744")] public async Task TestIncompleteCatchBlockInLambda(TestHost testHost) { await TestAsync( @"class A { System.Action a = () => { try { } catch ([|Exception|]", @"using System; class A { System.Action a = () => { try { } catch (Exception", testHost); } [Theory] [CombinatorialData] [WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] public async Task TestAddInsideLambda(TestHost testHost) { var initialText = @"using System; static void Main(string[] args) { Func<int> f = () => { [|List<int>|]. } }"; var expectedText = @"using System; using System.Collections.Generic; static void Main(string[] args) { Func<int> f = () => { List<int>. } }"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] public async Task TestAddInsideLambda2(TestHost testHost) { var initialText = @"using System; static void Main(string[] args) { Func<int> f = () => { [|List<int>|] } }"; var expectedText = @"using System; using System.Collections.Generic; static void Main(string[] args) { Func<int> f = () => { List<int> } }"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] public async Task TestAddInsideLambda3(TestHost testHost) { var initialText = @"using System; static void Main(string[] args) { Func<int> f = () => { var a = 3; [|List<int>|]. return a; }; }"; var expectedText = @"using System; using System.Collections.Generic; static void Main(string[] args) { Func<int> f = () => { var a = 3; List<int>. return a; }; }"; await TestAsync(initialText, expectedText, testHost); } [Theory] [CombinatorialData] [WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] public async Task TestAddInsideLambda4(TestHost testHost) { var initialText = @"using System; static void Main(string[] args) { Func<int> f = () => { var a = 3; [|List<int>|] return a; }; }"; var expectedText = @"using System; using System.Collections.Generic; static void Main(string[] args) { Func<int> f = () => { var a = 3; List<int> return a; }; }"; await TestAsync(initialText, expectedText, testHost); } [WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")] [Theory] [CombinatorialData] [WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")] public async Task TestIncompleteParenthesizedLambdaExpression(TestHost testHost) { await TestAsync( @"using System; class Test { void Goo() { Action a = () => { [|IBindCtx|] }; string a; } }", @"using System; using System.Runtime.InteropServices.ComTypes; class Test { void Goo() { Action a = () => { IBindCtx }; string a; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(7461, "https://github.com/dotnet/roslyn/issues/7461")] public async Task TestExtensionWithIncompatibleInstance(TestHost testHost) { await TestAsync( @"using System.IO; namespace Namespace1 { static class StreamExtensions { public static void Write(this Stream stream, byte[] bytes) { } } } namespace Namespace2 { class Goo { void Bar() { Stream stream = null; stream.[|Write|](new byte[] { 1, 2, 3 }); } } }", @"using System.IO; using Namespace1; namespace Namespace1 { static class StreamExtensions { public static void Write(this Stream stream, byte[] bytes) { } } } namespace Namespace2 { class Goo { void Bar() { Stream stream = null; stream.Write(new byte[] { 1, 2, 3 }); } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(5499, "https://github.com/dotnet/roslyn/issues/5499")] public async Task TestFormattingForNamespaceUsings(TestHost testHost) { await TestAsync( @"namespace N { using System; using System.Collections.Generic; using System.Linq; using System.Text; class Program { void Main() { [|Task<int>|] } } }", @"namespace N { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { void Main() { Task<int> } } }", testHost); } [Fact] public async Task TestGenericAmbiguityInSameNamespace() { await TestMissingInRegularAndScriptAsync( @"namespace NS { class C<T> where T : [|C|].N { public class N { } } }"); } [Fact] public async Task TestNotOnVar1() { await TestMissingInRegularAndScriptAsync( @"namespace N { class var { } } class C { void M() { [|var|] } } "); } [Fact] public async Task TestNotOnVar2() { await TestMissingInRegularAndScriptAsync( @"namespace N { class Bar { } } class C { void M() { [|var|] } } "); } [Theory] [CombinatorialData] [WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing1(TestHost testHost) { await TestAsync( @" /// Copyright 2016 - MyCompany /// All Rights Reserved using System; class C : [|IEnumerable|]<int> { } ", @" /// Copyright 2016 - MyCompany /// All Rights Reserved using System; using System.Collections.Generic; class C : IEnumerable<int> { } ", testHost); } [Theory] [CombinatorialData] [WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing2(TestHost testHost) { await TestAsync( @" /// Copyright 2016 - MyCompany /// All Rights Reserved using System.Collections; class C { [|DateTime|] d; } ", @" /// Copyright 2016 - MyCompany /// All Rights Reserved using System; using System.Collections; class C { DateTime d; } ", testHost); } [Theory] [CombinatorialData] [WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] public async Task TestAddUsingWithLeadingDocCommentInFrontOfClass1(TestHost testHost) { await TestAsync( @" /// Copyright 2016 - MyCompany /// All Rights Reserved class C { [|DateTime|] d; } ", @" using System; /// Copyright 2016 - MyCompany /// All Rights Reserved class C { DateTime d; } ", testHost); } [Theory] [CombinatorialData] public async Task TestPlaceUsingWithUsings_NotWithAliases(TestHost testHost) { await TestAsync( @" using System; namespace N { using C = System.Collections; class Class { [|List<int>|] Method() { Goo(); } } }", @" using System; using System.Collections.Generic; namespace N { using C = System.Collections; class Class { List<int> Method() { Goo(); } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")] public async Task TestPreferSystemNamespaceFirst(TestHost testHost) { await TestAsync( @" namespace Microsoft { public class SomeClass { } } namespace System { public class SomeClass { } } namespace N { class Class { [|SomeClass|] c; } }", @" using System; namespace Microsoft { public class SomeClass { } } namespace System { public class SomeClass { } } namespace N { class Class { SomeClass c; } }", testHost); } [Theory] [CombinatorialData] [WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")] public async Task TestPreferSystemNamespaceFirst2(TestHost testHost) { await TestAsync( @" namespace Microsoft { public class SomeClass { } } namespace System { public class SomeClass { } } namespace N { class Class { [|SomeClass|] c; } }", @" using Microsoft; namespace Microsoft { public class SomeClass { } } namespace System { public class SomeClass { } } namespace N { class Class { SomeClass c; } }", testHost, index: 1); } [Fact] [WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")] public async Task TestContextualKeyword1() { await TestMissingInRegularAndScriptAsync( @" namespace N { class nameof { } } class C { void M() { [|nameof|] } }"); } [Theory] [CombinatorialData] [WorkItem(19218, "https://github.com/dotnet/roslyn/issues/19218")] public async Task TestChangeCaseWithUsingsInNestedNamespace(TestHost testHost) { await TestAsync( @"namespace VS { interface IVsStatusbar { } } namespace Outer { using System; class C { void M() { // Note: IVsStatusBar is cased incorrectly. [|IVsStatusBar|] b; } } } ", @"namespace VS { interface IVsStatusbar { } } namespace Outer { using System; using VS; class C { void M() { // Note: IVsStatusBar is cased incorrectly. IVsStatusbar b; } } } ", testHost); } [Fact] [WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")] public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression() { var code = @" class C { private void GetEvaluationRuleNames() { [|IEnumerable|] < Int32 > return ImmutableArray.CreateRange(); } }"; await TestActionCountAsync(code, count: 1); await TestInRegularAndScriptAsync( code, @" using System.Collections.Generic; class C { private void GetEvaluationRuleNames() { IEnumerable < Int32 > return ImmutableArray.CreateRange(); } }"); } [Theory] [CombinatorialData] [WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")] public async Task TestWhenInRome1(TestHost testHost) { // System is set to be sorted first, but the actual file shows it at the end. // Keep things sorted, but respect that 'System' is at the end. await TestAsync( @" using B; using System; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @" using A; using B; using System; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")] public async Task TestWhenInRome2(TestHost testHost) { // System is set to not be sorted first, but the actual file shows it sorted first. // Keep things sorted, but respect that 'System' is at the beginning. await TestAsync( @" using System; using B; class Class { void Method() { [|Goo|].Bar(); } } namespace A { class Goo { public static void Bar() { } } }", @" using System; using A; using B; class Class { void Method() { Goo.Bar(); } } namespace A { class Goo { public static void Bar() { } } }", testHost); } [Fact] public async Task TestExactMatchNoGlyph() { await TestSmartTagGlyphTagsAsync( @"namespace VS { interface Other { } } class C { void M() { [|Other|] b; } } ", ImmutableArray<string>.Empty); } [Fact] public async Task TestFuzzyMatchGlyph() { await TestSmartTagGlyphTagsAsync( @"namespace VS { interface Other { } } class C { void M() { [|Otter|] b; } } ", WellKnownTagArrays.Namespace); } [Theory] [CombinatorialData] [WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")] public async Task TestGetAwaiterExtensionMethod1(TestHost testHost) { await TestAsync( @" namespace A { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { async Task M() => await [|Goo|]; C Goo { get; set; } } } namespace B { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using A; static class Extensions { public static Awaiter GetAwaiter(this C scheduler) => null; public class Awaiter : INotifyCompletion { public object GetResult() => null; public void OnCompleted(Action continuation) { } public bool IsCompleted => true; } } }", @" namespace A { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using B; class C { async Task M() => await Goo; C Goo { get; set; } } } namespace B { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using A; static class Extensions { public static Awaiter GetAwaiter(this C scheduler) => null; public class Awaiter : INotifyCompletion { public object GetResult() => null; public void OnCompleted(Action continuation) { } public bool IsCompleted => true; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")] public async Task TestGetAwaiterExtensionMethod2(TestHost testHost) { await TestAsync( @" namespace A { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { async Task M() => await [|GetC|](); C GetC() => null; } } namespace B { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using A; static class Extensions { public static Awaiter GetAwaiter(this C scheduler) => null; public class Awaiter : INotifyCompletion { public object GetResult() => null; public void OnCompleted(Action continuation) { } public bool IsCompleted => true; } } }", @" namespace A { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using B; class C { async Task M() => await GetC(); C GetC() => null; } } namespace B { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using A; static class Extensions { public static Awaiter GetAwaiter(this C scheduler) => null; public class Awaiter : INotifyCompletion { public object GetResult() => null; public void OnCompleted(Action continuation) { } public bool IsCompleted => true; } } }", testHost); } [Theory] [CombinatorialData] [WorkItem(745490, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/745490")] public async Task TestAddUsingForAwaitableReturningExtensionMethod(TestHost testHost) { await TestAsync( @" namespace A { using System; using System.Threading.Tasks; class C { C Instance { get; } async Task M() => await Instance.[|Foo|](); } } namespace B { using System; using System.Threading.Tasks; using A; static class Extensions { public static Task Foo(this C instance) => null; } }", @" namespace A { using System; using System.Threading.Tasks; using B; class C { C Instance { get; } async Task M() => await Instance.Foo(); } } namespace B { using System; using System.Threading.Tasks; using A; static class Extensions { public static Task Foo(this C instance) => null; } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetEnumeratorReturningIEnumerator(TestHost testHost) { await TestAsync( @" namespace A { class C { C Instance { get; } void M() { foreach (var i in [|Instance|]); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IEnumerator<int> GetEnumerator(this C instance) => null; } }", @" using B; namespace A { class C { C Instance { get; } void M() { foreach (var i in Instance); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IEnumerator<int> GetEnumerator(this C instance) => null; } }", testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumerator(TestHost testHost) { await TestAsync( @" namespace A { class C { C Instance { get; } void M() { foreach (var i in [|Instance|]); } } } namespace B { using A; static class Extensions { public static Enumerator GetEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public bool MoveNext(); } }", @" using B; namespace A { class C { C Instance { get; } void M() { foreach (var i in Instance); } } } namespace B { using A; static class Extensions { public static Enumerator GetEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public bool MoveNext(); } }", testHost); } [Fact] public async Task TestMissingForExtensionInvalidGetEnumerator() { await TestMissingAsync( @" namespace A { class C { C Instance { get; } void M() { foreach (var i in [|Instance|]); } } } namespace B { using A; static class Extensions { public static bool GetEnumerator(this C instance) => null; } }"); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost) { await TestAsync( @" namespace A { class C { C Instance { get; }; void M() { foreach (var i in [|Instance|]); } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new Enumerator(); } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } } } namespace B { using A; static class Extensions { public static Enumerator GetEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public bool MoveNext(); } }", @" using B; namespace A { class C { C Instance { get; }; void M() { foreach (var i in Instance); } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new Enumerator(); } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } } } namespace B { using A; static class Extensions { public static Enumerator GetEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public bool MoveNext(); } }", testHost); } [Fact] public async Task TestMissingForExtensionGetAsyncEnumeratorOnForeach() { await TestMissingAsync( @" namespace A { class C { C Instance { get; } void M() { foreach (var i in [|Instance|]); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null; } }" + IAsyncEnumerable); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningIAsyncEnumerator(TestHost testHost) { await TestAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in [|Instance|]); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null; } }" + IAsyncEnumerable, @" using System.Threading.Tasks; using B; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in Instance); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null; } }" + IAsyncEnumerable, testHost); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumerator(TestHost testHost) { await TestAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in [|Instance|]); } } } namespace B { using A; static class Extensions { public static Enumerator GetAsyncEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public Task<bool> MoveNextAsync(); } }", @" using System.Threading.Tasks; using B; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in Instance); } } } namespace B { using A; static class Extensions { public static Enumerator GetAsyncEnumerator(this C instance) => null; } public class Enumerator { public int Current { get; } public Task<bool> MoveNextAsync(); } }", testHost); } [Fact] public async Task TestMissingForExtensionInvalidGetAsyncEnumerator() { await TestMissingAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } async Task M() { await foreach (var i in [|Instance|]); } } } namespace B { using A; static class Extensions { public static bool GetAsyncEnumerator(this C instance) => null; } }"); } [Theory] [CombinatorialData] public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost) { await TestAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } Task M() { await foreach (var i in [|Instance|]); } public Enumerator GetEnumerator() { return new Enumerator(); } public class Enumerator { public int Current { get; } public bool MoveNext(); } } } namespace B { using A; static class Extensions { public static Enumerator GetAsyncEnumerator(this C instance) => null; } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } }", @" using System.Threading.Tasks; using B; namespace A { class C { C Instance { get; } Task M() { await foreach (var i in Instance); } public Enumerator GetEnumerator() { return new Enumerator(); } public class Enumerator { public int Current { get; } public bool MoveNext(); } } } namespace B { using A; static class Extensions { public static Enumerator GetAsyncEnumerator(this C instance) => null; } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } }", testHost); } [Fact] public async Task TestMissingForExtensionGetEnumeratorOnAsyncForeach() { await TestMissingAsync( @" using System.Threading.Tasks; namespace A { class C { C Instance { get; } Task M() { await foreach (var i in [|Instance|]); } } } namespace B { using A; using System.Collections.Generic; static class Extensions { public static IEnumerator<int> GetEnumerator(this C instance) => null; } }"); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithStaticUsingInNamespace_WhenNoExistingUsings(TestHost testHost) { await TestAsync( @" namespace N { using static System.Math; class C { public [|List<int>|] F; } } ", @" namespace N { using System.Collections.Generic; using static System.Math; class C { public List<int> F; } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithStaticUsingInInnerNestedNamespace_WhenNoExistingUsings(TestHost testHost) { await TestAsync( @" namespace N { namespace M { using static System.Math; class C { public [|List<int>|] F; } } } ", @" namespace N { namespace M { using System.Collections.Generic; using static System.Math; class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithStaticUsingInOuterNestedNamespace_WhenNoExistingUsings(TestHost testHost) { await TestAsync( @" namespace N { using static System.Math; namespace M { class C { public [|List<int>|] F; } } } ", @" namespace N { using System.Collections.Generic; using static System.Math; namespace M { class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenStaticUsingInNamespace(TestHost testHost) { await TestAsync( @" using System; namespace N { using static System.Math; class C { public [|List<int>|] F; } } ", @" using System; using System.Collections.Generic; namespace N { using static System.Math; class C { public List<int> F; } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInInnerNestedNamespace(TestHost testHost) { await TestAsync( @" namespace N { using System; namespace M { using static System.Math; class C { public [|List<int>|] F; } } } ", @" namespace N { using System; using System.Collections.Generic; namespace M { using static System.Math; class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInOuterNestedNamespace(TestHost testHost) { await TestAsync( @" namespace N { using static System.Math; namespace M { using System; class C { public [|List<int>|] F; } } } ", @" namespace N { using static System.Math; namespace M { using System; using System.Collections.Generic; class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithUsingAliasInNamespace_WhenNoExistingUsing(TestHost testHost) { await TestAsync( @" namespace N { using SAction = System.Action; class C { public [|List<int>|] F; } } ", @" namespace N { using System.Collections.Generic; using SAction = System.Action; class C { public List<int> F; } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithUsingAliasInInnerNestedNamespace_WhenNoExistingUsing(TestHost testHost) { await TestAsync( @" namespace N { namespace M { using SAction = System.Action; class C { public [|List<int>|] F; } } } ", @" namespace N { namespace M { using System.Collections.Generic; using SAction = System.Action; class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithUsingAliasInOuterNestedNamespace_WhenNoExistingUsing(TestHost testHost) { await TestAsync( @" namespace N { using SAction = System.Action; namespace M { class C { public [|List<int>|] F; } } } ", @" namespace N { using System.Collections.Generic; using SAction = System.Action; namespace M { class C { public List<int> F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenUsingAliasInNamespace(TestHost testHost) { await TestAsync( @" using System; namespace N { using SAction = System.Action; class C { public [|List<int>|] F; } } ", @" using System; using System.Collections.Generic; namespace N { using SAction = System.Action; class C { public List<int> F; } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInInnerNestedNamespace(TestHost testHost) { await TestAsync( @" namespace N { using System; namespace M { using SAction = System.Action; class C { public [|List<int>|] F; } } } ", @" namespace N { using System; using System.Collections.Generic; namespace M { using SAction = System.Action; class C { public [|List<int>|] F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")] public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInOuterNestedNamespace(TestHost testHost) { await TestAsync( @" namespace N { using SAction = System.Action; namespace M { using System; class C { public [|List<int>|] F; } } } ", @" namespace N { using SAction = System.Action; namespace M { using System; using System.Collections.Generic; class C { public [|List<int>|] F; } } } ", testHost); } [Theory] [CombinatorialData] [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] public async Task KeepUsingsGrouped1(TestHost testHost) { await TestAsync( @" using System; class Program { static void Main(string[] args) { [|Goo|] } } namespace Microsoft { public class Goo { } }", @" using System; using Microsoft; class Program { static void Main(string[] args) { Goo } } namespace Microsoft { public class Goo { } }", testHost); } [WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")] [Fact] public async Task TestIncompleteLambda1() { await TestInRegularAndScriptAsync( @"using System.Linq; class C { C() { """".Select(() => { new [|Byte|]", @"using System; using System.Linq; class C { C() { """".Select(() => { new Byte"); } [WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")] [Fact] public async Task TestIncompleteLambda2() { await TestInRegularAndScriptAsync( @"using System.Linq; class C { C() { """".Select(() => { new [|Byte|]() }", @"using System; using System.Linq; class C { C() { """".Select(() => { new Byte() }"); } [WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")] [WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")] [Fact] public async Task TestIncompleteSimpleLambdaExpression() { await TestInRegularAndScriptAsync( @"using System.Linq; class Program { static void Main(string[] args) { args[0].Any(x => [|IBindCtx|] string a; } }", @"using System.Linq; using System.Runtime.InteropServices.ComTypes; class Program { static void Main(string[] args) { args[0].Any(x => IBindCtx string a; } }"); } [Theory] [CombinatorialData] [WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableNeverSameProject(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.cs""> using System.ComponentModel; namespace ProjectLib { [EditorBrowsable(EditorBrowsableState.Never)] public class Project { } } </Document> <Document FilePath=""Program.cs""> class Program { static void Main(string[] args) { Project p = new [|Project()|]; } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @" using ProjectLib; class Program { static void Main(string[] args) { Project p = new [|Project()|]; } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableNeverDifferentProject(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.vb""> imports System.ComponentModel namespace ProjectLib &lt;EditorBrowsable(EditorBrowsableState.Never)&gt; public class Project end class end namespace </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference>lib</ProjectReference> <Document FilePath=""Program.cs""> class Program { static void Main(string[] args) { [|Project|] p = new Project(); } } </Document> </Project> </Workspace>"; await TestMissingAsync(InitialWorkspace, new TestParameters(testHost: testHost)); } [Theory] [CombinatorialData] [WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.vb""> imports System.ComponentModel namespace ProjectLib &lt;EditorBrowsable(EditorBrowsableState.Advanced)&gt; public class Project end class end namespace </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference>lib</ProjectReference> <Document FilePath=""Program.cs""> class Program { static void Main(string[] args) { [|Project|] p = new Project(); } } </Document> </Project> </Workspace>"; const string ExpectedDocumentText = @" using ProjectLib; class Program { static void Main(string[] args) { Project p = new [|Project()|]; } } "; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory] [CombinatorialData] [WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost) { const string InitialWorkspace = @" <Workspace> <Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true""> <Document FilePath=""lib.vb""> imports System.ComponentModel namespace ProjectLib &lt;EditorBrowsable(EditorBrowsableState.Advanced)&gt; public class Project end class end namespace </Document> </Project> <Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true""> <ProjectReference>lib</ProjectReference> <Document FilePath=""Program.cs""> class Program { static void Main(string[] args) { [|Project|] p = new Project(); } } </Document> </Project> </Workspace>"; await TestMissingAsync(InitialWorkspace, new TestParameters( options: Option(CompletionOptions.HideAdvancedMembers, true), testHost: testHost)); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingEventSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { internal sealed class RetargetingEventSymbol : WrappedEventSymbol { /// <summary> /// Owning RetargetingModuleSymbol. /// </summary> private readonly RetargetingModuleSymbol _retargetingModule; //we want to compute this lazily since it may be expensive for the underlying symbol private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations; private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized; public RetargetingEventSymbol(RetargetingModuleSymbol retargetingModule, EventSymbol underlyingEvent) : base(underlyingEvent) { RoslynDebug.Assert((object)retargetingModule != null); Debug.Assert(!(underlyingEvent is RetargetingEventSymbol)); _retargetingModule = retargetingModule; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return _retargetingModule.RetargetingTranslator; } } public override TypeWithAnnotations TypeWithAnnotations { get { return this.RetargetingTranslator.Retarget(_underlyingEvent.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); } } public override MethodSymbol? AddMethod { get { return (object?)_underlyingEvent.AddMethod == null ? null : this.RetargetingTranslator.Retarget(_underlyingEvent.AddMethod); } } public override MethodSymbol? RemoveMethod { get { return (object?)_underlyingEvent.RemoveMethod == null ? null : this.RetargetingTranslator.Retarget(_underlyingEvent.RemoveMethod); } } internal override FieldSymbol? AssociatedField { get { return (object?)_underlyingEvent.AssociatedField == null ? null : this.RetargetingTranslator.Retarget(_underlyingEvent.AssociatedField); } } internal override bool IsExplicitInterfaceImplementation { get { return _underlyingEvent.IsExplicitInterfaceImplementation; } } public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get { if (_lazyExplicitInterfaceImplementations.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange( ref _lazyExplicitInterfaceImplementations, this.RetargetExplicitInterfaceImplementations(), default(ImmutableArray<EventSymbol>)); } return _lazyExplicitInterfaceImplementations; } } private ImmutableArray<EventSymbol> RetargetExplicitInterfaceImplementations() { var impls = _underlyingEvent.ExplicitInterfaceImplementations; if (impls.IsEmpty) { return impls; } // CONSIDER: we could skip the builder until the first time we see a different method after retargeting var builder = ArrayBuilder<EventSymbol>.GetInstance(); for (int i = 0; i < impls.Length; i++) { var retargeted = this.RetargetingTranslator.Retarget(impls[i]); if ((object?)retargeted != null) { builder.Add(retargeted); } } return builder.ToImmutableAndFree(); } public override Symbol? ContainingSymbol { get { return this.RetargetingTranslator.Retarget(_underlyingEvent.ContainingSymbol); } } public override AssemblySymbol ContainingAssembly { get { return _retargetingModule.ContainingAssembly; } } internal override ModuleSymbol ContainingModule { get { return _retargetingModule; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return _underlyingEvent.GetAttributes(); } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return this.RetargetingTranslator.RetargetAttributes(_underlyingEvent.GetCustomAttributesToEmit(moduleBuilder)); } internal override bool MustCallMethodsDirectly { get { return _underlyingEvent.MustCallMethodsDirectly; } } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (!_lazyCachedUseSiteInfo.IsInitialized) { AssemblySymbol primaryDependency = PrimaryDependency; var result = new UseSiteInfo<AssemblySymbol>(primaryDependency); CalculateUseSiteDiagnostic(ref result); _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); } return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency); } internal sealed override CSharpCompilation? DeclaringCompilation // perf, not correctness { get { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { internal sealed class RetargetingEventSymbol : WrappedEventSymbol { /// <summary> /// Owning RetargetingModuleSymbol. /// </summary> private readonly RetargetingModuleSymbol _retargetingModule; //we want to compute this lazily since it may be expensive for the underlying symbol private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations; private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized; public RetargetingEventSymbol(RetargetingModuleSymbol retargetingModule, EventSymbol underlyingEvent) : base(underlyingEvent) { RoslynDebug.Assert((object)retargetingModule != null); Debug.Assert(!(underlyingEvent is RetargetingEventSymbol)); _retargetingModule = retargetingModule; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return _retargetingModule.RetargetingTranslator; } } public override TypeWithAnnotations TypeWithAnnotations { get { return this.RetargetingTranslator.Retarget(_underlyingEvent.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); } } public override MethodSymbol? AddMethod { get { return (object?)_underlyingEvent.AddMethod == null ? null : this.RetargetingTranslator.Retarget(_underlyingEvent.AddMethod); } } public override MethodSymbol? RemoveMethod { get { return (object?)_underlyingEvent.RemoveMethod == null ? null : this.RetargetingTranslator.Retarget(_underlyingEvent.RemoveMethod); } } internal override FieldSymbol? AssociatedField { get { return (object?)_underlyingEvent.AssociatedField == null ? null : this.RetargetingTranslator.Retarget(_underlyingEvent.AssociatedField); } } internal override bool IsExplicitInterfaceImplementation { get { return _underlyingEvent.IsExplicitInterfaceImplementation; } } public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get { if (_lazyExplicitInterfaceImplementations.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange( ref _lazyExplicitInterfaceImplementations, this.RetargetExplicitInterfaceImplementations(), default(ImmutableArray<EventSymbol>)); } return _lazyExplicitInterfaceImplementations; } } private ImmutableArray<EventSymbol> RetargetExplicitInterfaceImplementations() { var impls = _underlyingEvent.ExplicitInterfaceImplementations; if (impls.IsEmpty) { return impls; } // CONSIDER: we could skip the builder until the first time we see a different method after retargeting var builder = ArrayBuilder<EventSymbol>.GetInstance(); for (int i = 0; i < impls.Length; i++) { var retargeted = this.RetargetingTranslator.Retarget(impls[i]); if ((object?)retargeted != null) { builder.Add(retargeted); } } return builder.ToImmutableAndFree(); } public override Symbol? ContainingSymbol { get { return this.RetargetingTranslator.Retarget(_underlyingEvent.ContainingSymbol); } } public override AssemblySymbol ContainingAssembly { get { return _retargetingModule.ContainingAssembly; } } internal override ModuleSymbol ContainingModule { get { return _retargetingModule; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return _underlyingEvent.GetAttributes(); } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return this.RetargetingTranslator.RetargetAttributes(_underlyingEvent.GetCustomAttributesToEmit(moduleBuilder)); } internal override bool MustCallMethodsDirectly { get { return _underlyingEvent.MustCallMethodsDirectly; } } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (!_lazyCachedUseSiteInfo.IsInitialized) { AssemblySymbol primaryDependency = PrimaryDependency; var result = new UseSiteInfo<AssemblySymbol>(primaryDependency); CalculateUseSiteDiagnostic(ref result); _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); } return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency); } internal sealed override CSharpCompilation? DeclaringCompilation // perf, not correctness { get { return null; } } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using RoslynLogger = Microsoft.CodeAnalysis.Internal.Log.Logger; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// This service is used by the <see cref="SolutionChecksumUpdater"/> to proactively update the solution snapshot in /// the out-of-process workspace. We do this to limit the amount of time required to synchronize a solution over after an edit /// once a feature is asking for a snapshot. /// </summary> internal sealed class RemoteAssetSynchronizationService : BrokeredServiceBase, IRemoteAssetSynchronizationService { internal sealed class Factory : FactoryBase<IRemoteAssetSynchronizationService> { protected override IRemoteAssetSynchronizationService CreateService(in ServiceConstructionArguments arguments) => new RemoteAssetSynchronizationService(in arguments); } public RemoteAssetSynchronizationService(in ServiceConstructionArguments arguments) : base(in arguments) { } public ValueTask SynchronizePrimaryWorkspaceAsync(PinnedSolutionInfo solutionInfo, Checksum checksum, int workspaceVersion, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { using (RoslynLogger.LogBlock(FunctionId.RemoteHostService_SynchronizePrimaryWorkspaceAsync, Checksum.GetChecksumLogInfo, checksum, cancellationToken)) { var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, WorkspaceManager.SolutionAssetCache, SolutionAssetSource); await workspace.UpdatePrimaryBranchSolutionAsync(assetProvider, checksum, workspaceVersion, cancellationToken).ConfigureAwait(false); } }, cancellationToken); } public ValueTask SynchronizeTextAsync(DocumentId documentId, Checksum baseTextChecksum, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var workspace = GetWorkspace(); using (RoslynLogger.LogBlock(FunctionId.RemoteHostService_SynchronizeTextAsync, Checksum.GetChecksumLogInfo, baseTextChecksum, cancellationToken)) { var serializer = workspace.Services.GetRequiredService<ISerializerService>(); var text = await TryGetSourceTextAsync().ConfigureAwait(false); if (text == null) { // it won't bring in base text if it is not there already. // text needed will be pulled in when there is request return; } var newText = new SerializableSourceText(text.WithChanges(textChanges)); var newChecksum = serializer.CreateChecksum(newText, cancellationToken); // save new text in the cache so that when asked, the data is most likely already there // // this cache is very short live. and new text created above is ChangedText which share // text data with original text except the changes. // so memory wise, this doesn't put too much pressure on the cache. it will not duplicates // same text multiple times. // // also, once the changes are picked up and put into Workspace, normal Workspace // caching logic will take care of the text WorkspaceManager.SolutionAssetCache.TryAddAsset(newChecksum, newText); } async Task<SourceText?> TryGetSourceTextAsync() { // check the cheap and fast one first. // see if the cache has the source text if (WorkspaceManager.SolutionAssetCache.TryGetAsset<SerializableSourceText>(baseTextChecksum, out var serializableSourceText)) { return await serializableSourceText.GetTextAsync(cancellationToken).ConfigureAwait(false); } // do slower one // check whether existing solution has it var document = workspace.CurrentSolution.GetDocument(documentId); if (document == null) { return null; } // check checksum whether it is there. // since we lazily synchronize whole solution (SynchronizePrimaryWorkspaceAsync) when things are idle, // soon or later this will get hit even if text changes got out of sync due to issues in VS side // such as file is first opened and there is no SourceText in memory yet. if (!document.State.TryGetStateChecksums(out var state) || !state.Text.Equals(baseTextChecksum)) { return null; } return await document.GetTextAsync(cancellationToken).ConfigureAwait(false); } }, 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.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using RoslynLogger = Microsoft.CodeAnalysis.Internal.Log.Logger; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// This service is used by the <see cref="SolutionChecksumUpdater"/> to proactively update the solution snapshot in /// the out-of-process workspace. We do this to limit the amount of time required to synchronize a solution over after an edit /// once a feature is asking for a snapshot. /// </summary> internal sealed class RemoteAssetSynchronizationService : BrokeredServiceBase, IRemoteAssetSynchronizationService { internal sealed class Factory : FactoryBase<IRemoteAssetSynchronizationService> { protected override IRemoteAssetSynchronizationService CreateService(in ServiceConstructionArguments arguments) => new RemoteAssetSynchronizationService(in arguments); } public RemoteAssetSynchronizationService(in ServiceConstructionArguments arguments) : base(in arguments) { } public ValueTask SynchronizePrimaryWorkspaceAsync(PinnedSolutionInfo solutionInfo, Checksum checksum, int workspaceVersion, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { using (RoslynLogger.LogBlock(FunctionId.RemoteHostService_SynchronizePrimaryWorkspaceAsync, Checksum.GetChecksumLogInfo, checksum, cancellationToken)) { var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, WorkspaceManager.SolutionAssetCache, SolutionAssetSource); await workspace.UpdatePrimaryBranchSolutionAsync(assetProvider, checksum, workspaceVersion, cancellationToken).ConfigureAwait(false); } }, cancellationToken); } public ValueTask SynchronizeTextAsync(DocumentId documentId, Checksum baseTextChecksum, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var workspace = GetWorkspace(); using (RoslynLogger.LogBlock(FunctionId.RemoteHostService_SynchronizeTextAsync, Checksum.GetChecksumLogInfo, baseTextChecksum, cancellationToken)) { var serializer = workspace.Services.GetRequiredService<ISerializerService>(); var text = await TryGetSourceTextAsync().ConfigureAwait(false); if (text == null) { // it won't bring in base text if it is not there already. // text needed will be pulled in when there is request return; } var newText = new SerializableSourceText(text.WithChanges(textChanges)); var newChecksum = serializer.CreateChecksum(newText, cancellationToken); // save new text in the cache so that when asked, the data is most likely already there // // this cache is very short live. and new text created above is ChangedText which share // text data with original text except the changes. // so memory wise, this doesn't put too much pressure on the cache. it will not duplicates // same text multiple times. // // also, once the changes are picked up and put into Workspace, normal Workspace // caching logic will take care of the text WorkspaceManager.SolutionAssetCache.TryAddAsset(newChecksum, newText); } async Task<SourceText?> TryGetSourceTextAsync() { // check the cheap and fast one first. // see if the cache has the source text if (WorkspaceManager.SolutionAssetCache.TryGetAsset<SerializableSourceText>(baseTextChecksum, out var serializableSourceText)) { return await serializableSourceText.GetTextAsync(cancellationToken).ConfigureAwait(false); } // do slower one // check whether existing solution has it var document = workspace.CurrentSolution.GetDocument(documentId); if (document == null) { return null; } // check checksum whether it is there. // since we lazily synchronize whole solution (SynchronizePrimaryWorkspaceAsync) when things are idle, // soon or later this will get hit even if text changes got out of sync due to issues in VS side // such as file is first opened and there is no SourceText in memory yet. if (!document.State.TryGetStateChecksums(out var state) || !state.Text.Equals(baseTextChecksum)) { return null; } return await document.GetTextAsync(cancellationToken).ConfigureAwait(false); } }, cancellationToken); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Emitter/NoPia/EmbeddedEvent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Collections.Generic; #if !DEBUG using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol; #endif namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia { internal sealed class EmbeddedEvent : EmbeddedTypesManager.CommonEmbeddedEvent { public EmbeddedEvent(EventSymbolAdapter underlyingEvent, EmbeddedMethod adder, EmbeddedMethod remover) : base(underlyingEvent, adder, remover, null) { } protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return UnderlyingEvent.AdaptedEventSymbol.GetCustomAttributesToEmit(moduleBuilder); } protected override bool IsRuntimeSpecial { get { return UnderlyingEvent.AdaptedEventSymbol.HasRuntimeSpecialName; } } protected override bool IsSpecialName { get { return UnderlyingEvent.AdaptedEventSymbol.HasSpecialName; } } protected override Cci.ITypeReference GetType(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return moduleBuilder.Translate(UnderlyingEvent.AdaptedEventSymbol.Type, syntaxNodeOpt, diagnostics); } protected override EmbeddedType ContainingType { get { return AnAccessor.ContainingType; } } protected override Cci.TypeMemberVisibility Visibility { get { return PEModuleBuilder.MemberVisibility(UnderlyingEvent.AdaptedEventSymbol); } } protected override string Name { get { return UnderlyingEvent.AdaptedEventSymbol.MetadataName; } } protected override void EmbedCorrespondingComEventInterfaceMethodInternal(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) { // If the event happens to belong to a class with a ComEventInterfaceAttribute, there will also be // a paired method living on its source interface. The ComAwareEventInfo class expects to find this // method through reflection. If we embed an event, therefore, we must ensure that the associated source // interface method is also included, even if it is not otherwise referenced in the embedding project. NamedTypeSymbol underlyingContainingType = ContainingType.UnderlyingNamedType.AdaptedNamedTypeSymbol; foreach (var attrData in underlyingContainingType.GetAttributes()) { if (attrData.IsTargetAttribute(underlyingContainingType, AttributeDescription.ComEventInterfaceAttribute)) { bool foundMatch = false; NamedTypeSymbol sourceInterface = null; if (attrData.CommonConstructorArguments.Length == 2) { sourceInterface = attrData.CommonConstructorArguments[0].ValueInternal as NamedTypeSymbol; if ((object)sourceInterface != null) { foundMatch = EmbedMatchingInterfaceMethods(sourceInterface, syntaxNodeOpt, diagnostics); foreach (NamedTypeSymbol source in sourceInterface.AllInterfacesNoUseSiteDiagnostics) { if (EmbedMatchingInterfaceMethods(source, syntaxNodeOpt, diagnostics)) { foundMatch = true; } } } } if (!foundMatch && isUsedForComAwareEventBinding) { if ((object)sourceInterface == null) { // ERRID_SourceInterfaceMustBeInterface/ERR_MissingSourceInterface EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingSourceInterface, syntaxNodeOpt, underlyingContainingType, UnderlyingEvent.AdaptedEventSymbol); } else { var useSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; sourceInterface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); diagnostics.Add(syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location, useSiteInfo.Diagnostics); // ERRID_EventNoPIANoBackingMember/ERR_MissingMethodOnSourceInterface EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingMethodOnSourceInterface, syntaxNodeOpt, sourceInterface, UnderlyingEvent.AdaptedEventSymbol.MetadataName, UnderlyingEvent.AdaptedEventSymbol); } } break; } } } private bool EmbedMatchingInterfaceMethods(NamedTypeSymbol sourceInterface, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { bool foundMatch = false; foreach (Symbol m in sourceInterface.GetMembers(UnderlyingEvent.AdaptedEventSymbol.MetadataName)) { if (m.Kind == SymbolKind.Method) { TypeManager.EmbedMethodIfNeedTo(((MethodSymbol)m).GetCciAdapter(), syntaxNodeOpt, diagnostics); foundMatch = true; } } return foundMatch; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Collections.Generic; #if !DEBUG using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol; #endif namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia { internal sealed class EmbeddedEvent : EmbeddedTypesManager.CommonEmbeddedEvent { public EmbeddedEvent(EventSymbolAdapter underlyingEvent, EmbeddedMethod adder, EmbeddedMethod remover) : base(underlyingEvent, adder, remover, null) { } protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return UnderlyingEvent.AdaptedEventSymbol.GetCustomAttributesToEmit(moduleBuilder); } protected override bool IsRuntimeSpecial { get { return UnderlyingEvent.AdaptedEventSymbol.HasRuntimeSpecialName; } } protected override bool IsSpecialName { get { return UnderlyingEvent.AdaptedEventSymbol.HasSpecialName; } } protected override Cci.ITypeReference GetType(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return moduleBuilder.Translate(UnderlyingEvent.AdaptedEventSymbol.Type, syntaxNodeOpt, diagnostics); } protected override EmbeddedType ContainingType { get { return AnAccessor.ContainingType; } } protected override Cci.TypeMemberVisibility Visibility { get { return PEModuleBuilder.MemberVisibility(UnderlyingEvent.AdaptedEventSymbol); } } protected override string Name { get { return UnderlyingEvent.AdaptedEventSymbol.MetadataName; } } protected override void EmbedCorrespondingComEventInterfaceMethodInternal(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) { // If the event happens to belong to a class with a ComEventInterfaceAttribute, there will also be // a paired method living on its source interface. The ComAwareEventInfo class expects to find this // method through reflection. If we embed an event, therefore, we must ensure that the associated source // interface method is also included, even if it is not otherwise referenced in the embedding project. NamedTypeSymbol underlyingContainingType = ContainingType.UnderlyingNamedType.AdaptedNamedTypeSymbol; foreach (var attrData in underlyingContainingType.GetAttributes()) { if (attrData.IsTargetAttribute(underlyingContainingType, AttributeDescription.ComEventInterfaceAttribute)) { bool foundMatch = false; NamedTypeSymbol sourceInterface = null; if (attrData.CommonConstructorArguments.Length == 2) { sourceInterface = attrData.CommonConstructorArguments[0].ValueInternal as NamedTypeSymbol; if ((object)sourceInterface != null) { foundMatch = EmbedMatchingInterfaceMethods(sourceInterface, syntaxNodeOpt, diagnostics); foreach (NamedTypeSymbol source in sourceInterface.AllInterfacesNoUseSiteDiagnostics) { if (EmbedMatchingInterfaceMethods(source, syntaxNodeOpt, diagnostics)) { foundMatch = true; } } } } if (!foundMatch && isUsedForComAwareEventBinding) { if ((object)sourceInterface == null) { // ERRID_SourceInterfaceMustBeInterface/ERR_MissingSourceInterface EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingSourceInterface, syntaxNodeOpt, underlyingContainingType, UnderlyingEvent.AdaptedEventSymbol); } else { var useSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; sourceInterface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); diagnostics.Add(syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location, useSiteInfo.Diagnostics); // ERRID_EventNoPIANoBackingMember/ERR_MissingMethodOnSourceInterface EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingMethodOnSourceInterface, syntaxNodeOpt, sourceInterface, UnderlyingEvent.AdaptedEventSymbol.MetadataName, UnderlyingEvent.AdaptedEventSymbol); } } break; } } } private bool EmbedMatchingInterfaceMethods(NamedTypeSymbol sourceInterface, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { bool foundMatch = false; foreach (Symbol m in sourceInterface.GetMembers(UnderlyingEvent.AdaptedEventSymbol.MetadataName)) { if (m.Kind == SymbolKind.Method) { TypeManager.EmbedMethodIfNeedTo(((MethodSymbol)m).GetCciAdapter(), syntaxNodeOpt, diagnostics); foundMatch = true; } } return foundMatch; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Tools/IdeCoreBenchmarks/CSharpIdeAnalyzerBenchmarks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AnalyzerRunner; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.MSBuild; namespace IdeCoreBenchmarks { [MemoryDiagnoser] [RyuJitX64Job] public class CSharpIdeAnalyzerBenchmarks { private readonly string _solutionPath; private Options _options; private MSBuildWorkspace _workspace; private DiagnosticAnalyzerRunner _diagnosticAnalyzerRunner; [Params("CSharpAddBracesDiagnosticAnalyzer")] public string AnalyzerName { get; set; } public CSharpIdeAnalyzerBenchmarks() { var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); _solutionPath = Path.Combine(roslynRoot, @"src\Tools\IdeCoreBenchmarks\Assets\Microsoft.CodeAnalysis.sln"); if (!File.Exists(_solutionPath)) { throw new ArgumentException(); } } [GlobalSetup] public void Setup() { var analyzerAssemblyPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.CodeAnalysis.CSharp.Features.dll"); _options = new Options( analyzerPath: analyzerAssemblyPath, solutionPath: _solutionPath, analyzerIds: ImmutableHashSet.Create(AnalyzerName), refactoringNodes: ImmutableHashSet<string>.Empty, runConcurrent: true, reportSuppressedDiagnostics: true, applyChanges: false, useAll: false, iterations: 1, usePersistentStorage: false, fullSolutionAnalysis: false, incrementalAnalyzerNames: ImmutableArray<string>.Empty); _workspace = AnalyzerRunnerHelper.CreateWorkspace(); _diagnosticAnalyzerRunner = new DiagnosticAnalyzerRunner(_workspace, _options); _ = _workspace.OpenSolutionAsync(_solutionPath, progress: null, CancellationToken.None).Result; } [GlobalCleanup] public void Cleanup() { _workspace?.Dispose(); _workspace = null; } [Benchmark] public async Task RunAnalyzer() { await _diagnosticAnalyzerRunner.RunAsync(CancellationToken.None).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AnalyzerRunner; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.MSBuild; namespace IdeCoreBenchmarks { [MemoryDiagnoser] [RyuJitX64Job] public class CSharpIdeAnalyzerBenchmarks { private readonly string _solutionPath; private Options _options; private MSBuildWorkspace _workspace; private DiagnosticAnalyzerRunner _diagnosticAnalyzerRunner; [Params("CSharpAddBracesDiagnosticAnalyzer")] public string AnalyzerName { get; set; } public CSharpIdeAnalyzerBenchmarks() { var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); _solutionPath = Path.Combine(roslynRoot, @"src\Tools\IdeCoreBenchmarks\Assets\Microsoft.CodeAnalysis.sln"); if (!File.Exists(_solutionPath)) { throw new ArgumentException(); } } [GlobalSetup] public void Setup() { var analyzerAssemblyPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.CodeAnalysis.CSharp.Features.dll"); _options = new Options( analyzerPath: analyzerAssemblyPath, solutionPath: _solutionPath, analyzerIds: ImmutableHashSet.Create(AnalyzerName), refactoringNodes: ImmutableHashSet<string>.Empty, runConcurrent: true, reportSuppressedDiagnostics: true, applyChanges: false, useAll: false, iterations: 1, usePersistentStorage: false, fullSolutionAnalysis: false, incrementalAnalyzerNames: ImmutableArray<string>.Empty); _workspace = AnalyzerRunnerHelper.CreateWorkspace(); _diagnosticAnalyzerRunner = new DiagnosticAnalyzerRunner(_workspace, _options); _ = _workspace.OpenSolutionAsync(_solutionPath, progress: null, CancellationToken.None).Result; } [GlobalCleanup] public void Cleanup() { _workspace?.Dispose(); _workspace = null; } [Benchmark] public async Task RunAnalyzer() { await _diagnosticAnalyzerRunner.RunAsync(CancellationToken.None).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Symbols/NullableAnnotationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; // https://github.com/dotnet/roslyn/issues/34962 IDE005 "Fix formatting" does a poor job with a switch expression as the body of an expression-bodied method #pragma warning disable IDE0055 namespace Microsoft.CodeAnalysis.CSharp { internal static class NullableAnnotationExtensions { public static bool IsAnnotated(this NullableAnnotation annotation) => annotation == NullableAnnotation.Annotated; public static bool IsNotAnnotated(this NullableAnnotation annotation) => annotation == NullableAnnotation.NotAnnotated; public static bool IsOblivious(this NullableAnnotation annotation) => annotation == NullableAnnotation.Oblivious; /// <summary> /// Join nullable annotations from the set of lower bounds for fixing a type parameter. /// This uses the covariant merging rules. (Annotated wins over Oblivious which wins over NotAnnotated) /// </summary> public static NullableAnnotation Join(this NullableAnnotation a, NullableAnnotation b) { Debug.Assert(a != NullableAnnotation.Ignored); Debug.Assert(b != NullableAnnotation.Ignored); return (a < b) ? b : a; } /// <summary> /// Meet two nullable annotations for computing the nullable annotation of a type parameter from upper bounds. /// This uses the contravariant merging rules. (NotAnnotated wins over Oblivious which wins over Annotated) /// </summary> public static NullableAnnotation Meet(this NullableAnnotation a, NullableAnnotation b) { Debug.Assert(a != NullableAnnotation.Ignored); Debug.Assert(b != NullableAnnotation.Ignored); return (a < b) ? a : b; } /// <summary> /// Return the nullable annotation to use when two annotations are expected to be "compatible", which means /// they could be the same. These are the "invariant" merging rules. (NotAnnotated wins over Annotated which wins over Oblivious) /// </summary> public static NullableAnnotation EnsureCompatible(this NullableAnnotation a, NullableAnnotation b) { Debug.Assert(a != NullableAnnotation.Ignored); Debug.Assert(b != NullableAnnotation.Ignored); return (a, b) switch { (NullableAnnotation.Oblivious, _) => b, (_, NullableAnnotation.Oblivious) => a, _ => a < b ? a : b, }; } /// <summary> /// Merges nullability. /// </summary> public static NullableAnnotation MergeNullableAnnotation(this NullableAnnotation a, NullableAnnotation b, VarianceKind variance) { Debug.Assert(a != NullableAnnotation.Ignored); Debug.Assert(b != NullableAnnotation.Ignored); return variance switch { VarianceKind.In => a.Meet(b), VarianceKind.Out => a.Join(b), VarianceKind.None => a.EnsureCompatible(b), _ => throw ExceptionUtilities.UnexpectedValue(variance) }; } /// <summary> /// The attribute (metadata) representation of <see cref="NullableAnnotation.NotAnnotated"/>. /// </summary> public const byte NotAnnotatedAttributeValue = 1; /// <summary> /// The attribute (metadata) representation of <see cref="NullableAnnotation.Annotated"/>. /// </summary> public const byte AnnotatedAttributeValue = 2; /// <summary> /// The attribute (metadata) representation of <see cref="NullableAnnotation.Oblivious"/>. /// </summary> public const byte ObliviousAttributeValue = 0; internal static NullabilityInfo ToNullabilityInfo(this CodeAnalysis.NullableAnnotation annotation, TypeSymbol type) { if (annotation == CodeAnalysis.NullableAnnotation.None) { return default; } CSharp.NullableAnnotation internalAnnotation = annotation.ToInternalAnnotation(); return internalAnnotation.ToNullabilityInfo(type); } internal static NullabilityInfo ToNullabilityInfo(this NullableAnnotation annotation, TypeSymbol type) { var flowState = TypeWithAnnotations.Create(type, annotation).ToTypeWithState().State; return new NullabilityInfo(ToPublicAnnotation(type, annotation), flowState.ToPublicFlowState()); } internal static ITypeSymbol GetPublicSymbol(this TypeWithAnnotations type) { return type.Type?.GetITypeSymbol(type.ToPublicAnnotation()); } internal static ImmutableArray<ITypeSymbol> GetPublicSymbols(this ImmutableArray<TypeWithAnnotations> types) { return types.SelectAsArray(t => t.GetPublicSymbol()); } internal static CodeAnalysis.NullableAnnotation ToPublicAnnotation(this TypeWithAnnotations type) => ToPublicAnnotation(type.Type, type.NullableAnnotation); internal static ImmutableArray<CodeAnalysis.NullableAnnotation> ToPublicAnnotations(this ImmutableArray<TypeWithAnnotations> types) => types.SelectAsArray(t => t.ToPublicAnnotation()); #nullable enable internal static CodeAnalysis.NullableAnnotation ToPublicAnnotation(TypeSymbol? type, NullableAnnotation annotation) { Debug.Assert(annotation != NullableAnnotation.Ignored); return annotation switch { NullableAnnotation.Annotated => CodeAnalysis.NullableAnnotation.Annotated, NullableAnnotation.NotAnnotated => CodeAnalysis.NullableAnnotation.NotAnnotated, // A value type may be oblivious or not annotated depending on whether the type reference // is from source or metadata. (Binding using the #nullable context only when setting the annotation // to avoid checking IsValueType early.) The annotation is normalized here in the public API. NullableAnnotation.Oblivious when type?.IsValueType == true => CodeAnalysis.NullableAnnotation.NotAnnotated, NullableAnnotation.Oblivious => CodeAnalysis.NullableAnnotation.None, NullableAnnotation.Ignored => CodeAnalysis.NullableAnnotation.None, _ => throw ExceptionUtilities.UnexpectedValue(annotation) }; } #nullable disable internal static CSharp.NullableAnnotation ToInternalAnnotation(this CodeAnalysis.NullableAnnotation annotation) => annotation switch { CodeAnalysis.NullableAnnotation.None => CSharp.NullableAnnotation.Oblivious, CodeAnalysis.NullableAnnotation.NotAnnotated => CSharp.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated => CSharp.NullableAnnotation.Annotated, _ => throw ExceptionUtilities.UnexpectedValue(annotation) }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; // https://github.com/dotnet/roslyn/issues/34962 IDE005 "Fix formatting" does a poor job with a switch expression as the body of an expression-bodied method #pragma warning disable IDE0055 namespace Microsoft.CodeAnalysis.CSharp { internal static class NullableAnnotationExtensions { public static bool IsAnnotated(this NullableAnnotation annotation) => annotation == NullableAnnotation.Annotated; public static bool IsNotAnnotated(this NullableAnnotation annotation) => annotation == NullableAnnotation.NotAnnotated; public static bool IsOblivious(this NullableAnnotation annotation) => annotation == NullableAnnotation.Oblivious; /// <summary> /// Join nullable annotations from the set of lower bounds for fixing a type parameter. /// This uses the covariant merging rules. (Annotated wins over Oblivious which wins over NotAnnotated) /// </summary> public static NullableAnnotation Join(this NullableAnnotation a, NullableAnnotation b) { Debug.Assert(a != NullableAnnotation.Ignored); Debug.Assert(b != NullableAnnotation.Ignored); return (a < b) ? b : a; } /// <summary> /// Meet two nullable annotations for computing the nullable annotation of a type parameter from upper bounds. /// This uses the contravariant merging rules. (NotAnnotated wins over Oblivious which wins over Annotated) /// </summary> public static NullableAnnotation Meet(this NullableAnnotation a, NullableAnnotation b) { Debug.Assert(a != NullableAnnotation.Ignored); Debug.Assert(b != NullableAnnotation.Ignored); return (a < b) ? a : b; } /// <summary> /// Return the nullable annotation to use when two annotations are expected to be "compatible", which means /// they could be the same. These are the "invariant" merging rules. (NotAnnotated wins over Annotated which wins over Oblivious) /// </summary> public static NullableAnnotation EnsureCompatible(this NullableAnnotation a, NullableAnnotation b) { Debug.Assert(a != NullableAnnotation.Ignored); Debug.Assert(b != NullableAnnotation.Ignored); return (a, b) switch { (NullableAnnotation.Oblivious, _) => b, (_, NullableAnnotation.Oblivious) => a, _ => a < b ? a : b, }; } /// <summary> /// Merges nullability. /// </summary> public static NullableAnnotation MergeNullableAnnotation(this NullableAnnotation a, NullableAnnotation b, VarianceKind variance) { Debug.Assert(a != NullableAnnotation.Ignored); Debug.Assert(b != NullableAnnotation.Ignored); return variance switch { VarianceKind.In => a.Meet(b), VarianceKind.Out => a.Join(b), VarianceKind.None => a.EnsureCompatible(b), _ => throw ExceptionUtilities.UnexpectedValue(variance) }; } /// <summary> /// The attribute (metadata) representation of <see cref="NullableAnnotation.NotAnnotated"/>. /// </summary> public const byte NotAnnotatedAttributeValue = 1; /// <summary> /// The attribute (metadata) representation of <see cref="NullableAnnotation.Annotated"/>. /// </summary> public const byte AnnotatedAttributeValue = 2; /// <summary> /// The attribute (metadata) representation of <see cref="NullableAnnotation.Oblivious"/>. /// </summary> public const byte ObliviousAttributeValue = 0; internal static NullabilityInfo ToNullabilityInfo(this CodeAnalysis.NullableAnnotation annotation, TypeSymbol type) { if (annotation == CodeAnalysis.NullableAnnotation.None) { return default; } CSharp.NullableAnnotation internalAnnotation = annotation.ToInternalAnnotation(); return internalAnnotation.ToNullabilityInfo(type); } internal static NullabilityInfo ToNullabilityInfo(this NullableAnnotation annotation, TypeSymbol type) { var flowState = TypeWithAnnotations.Create(type, annotation).ToTypeWithState().State; return new NullabilityInfo(ToPublicAnnotation(type, annotation), flowState.ToPublicFlowState()); } internal static ITypeSymbol GetPublicSymbol(this TypeWithAnnotations type) { return type.Type?.GetITypeSymbol(type.ToPublicAnnotation()); } internal static ImmutableArray<ITypeSymbol> GetPublicSymbols(this ImmutableArray<TypeWithAnnotations> types) { return types.SelectAsArray(t => t.GetPublicSymbol()); } internal static CodeAnalysis.NullableAnnotation ToPublicAnnotation(this TypeWithAnnotations type) => ToPublicAnnotation(type.Type, type.NullableAnnotation); internal static ImmutableArray<CodeAnalysis.NullableAnnotation> ToPublicAnnotations(this ImmutableArray<TypeWithAnnotations> types) => types.SelectAsArray(t => t.ToPublicAnnotation()); #nullable enable internal static CodeAnalysis.NullableAnnotation ToPublicAnnotation(TypeSymbol? type, NullableAnnotation annotation) { Debug.Assert(annotation != NullableAnnotation.Ignored); return annotation switch { NullableAnnotation.Annotated => CodeAnalysis.NullableAnnotation.Annotated, NullableAnnotation.NotAnnotated => CodeAnalysis.NullableAnnotation.NotAnnotated, // A value type may be oblivious or not annotated depending on whether the type reference // is from source or metadata. (Binding using the #nullable context only when setting the annotation // to avoid checking IsValueType early.) The annotation is normalized here in the public API. NullableAnnotation.Oblivious when type?.IsValueType == true => CodeAnalysis.NullableAnnotation.NotAnnotated, NullableAnnotation.Oblivious => CodeAnalysis.NullableAnnotation.None, NullableAnnotation.Ignored => CodeAnalysis.NullableAnnotation.None, _ => throw ExceptionUtilities.UnexpectedValue(annotation) }; } #nullable disable internal static CSharp.NullableAnnotation ToInternalAnnotation(this CodeAnalysis.NullableAnnotation annotation) => annotation switch { CodeAnalysis.NullableAnnotation.None => CSharp.NullableAnnotation.Oblivious, CodeAnalysis.NullableAnnotation.NotAnnotated => CSharp.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated => CSharp.NullableAnnotation.Annotated, _ => throw ExceptionUtilities.UnexpectedValue(annotation) }; } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/CSharp/Test/ProjectSystemShim/CSharpHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Microsoft.VisualStudio.Shell.Interop; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim { internal static class CSharpHelpers { public static CSharpProjectShim CreateCSharpProject(TestEnvironment environment, string projectName) { var projectBinPath = Path.GetTempPath(); var hierarchy = environment.CreateHierarchy(projectName, projectBinPath, projectRefPath: null, projectCapabilities: "CSharp"); return CreateCSharpProject(environment, projectName, hierarchy); } public static CSharpProjectShim CreateCSharpProject(TestEnvironment environment, string projectName, IVsHierarchy hierarchy) { return new CSharpProjectShim( new MockCSharpProjectRoot(hierarchy), projectSystemName: projectName, hierarchy: hierarchy, serviceProvider: environment.ServiceProvider, threadingContext: environment.ThreadingContext); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, params string[] commandLineArguments) { return CreateCSharpCPSProjectAsync(environment, projectName, projectGuid: Guid.NewGuid(), commandLineArguments: commandLineArguments); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, Guid projectGuid, params string[] commandLineArguments) { var projectFilePath = Path.GetTempPath(); var binOutputPath = GetOutputPathFromArguments(commandLineArguments) ?? Path.Combine(projectFilePath, projectName + ".dll"); return CreateCSharpCPSProjectAsync(environment, projectName, projectFilePath, binOutputPath, projectGuid, commandLineArguments); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, string binOutputPath, params string[] commandLineArguments) { var projectFilePath = Path.GetTempPath(); return CreateCSharpCPSProjectAsync(environment, projectName, projectFilePath, binOutputPath, projectGuid: Guid.NewGuid(), commandLineArguments: commandLineArguments); } public static unsafe void SetOption(this CSharpProjectShim csharpProject, CompilerOptions optionID, object value) { Assert.Equal(sizeof(HACK_VariantStructure), 8 + 2 * IntPtr.Size); Assert.Equal(8, (int)Marshal.OffsetOf<HACK_VariantStructure>("_booleanValue")); HACK_VariantStructure variant = default; Marshal.GetNativeVariantForObject(value, (IntPtr)(&variant)); csharpProject.SetOption(optionID, variant); } public static async Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, string projectFilePath, string binOutputPath, Guid projectGuid, params string[] commandLineArguments) { var hierarchy = environment.CreateHierarchy(projectName, binOutputPath, projectRefPath: null, "CSharp"); var cpsProjectFactory = environment.ExportProvider.GetExportedValue<IWorkspaceProjectContextFactory>(); var cpsProject = (CPSProject)await cpsProjectFactory.CreateProjectContextAsync( LanguageNames.CSharp, projectName, projectFilePath, projectGuid, hierarchy, binOutputPath, assemblyName: null, CancellationToken.None); cpsProject.SetOptions(ImmutableArray.Create(commandLineArguments)); return cpsProject; } public static async Task<CPSProject> CreateNonCompilableProjectAsync(TestEnvironment environment, string projectName, string projectFilePath) { var hierarchy = environment.CreateHierarchy(projectName, projectBinPath: null, projectRefPath: null, ""); var cpsProjectFactory = environment.ExportProvider.GetExportedValue<IWorkspaceProjectContextFactory>(); return (CPSProject)await cpsProjectFactory.CreateProjectContextAsync( NoCompilationConstants.LanguageName, projectName, projectFilePath, Guid.NewGuid(), hierarchy, binOutputPath: null, assemblyName: null, CancellationToken.None); } private static string GetOutputPathFromArguments(string[] commandLineArguments) { const string outPrefix = "/out:"; string outputPath = null; foreach (var arg in commandLineArguments) { var index = arg.IndexOf(outPrefix); if (index >= 0) { outputPath = arg.Substring(index + outPrefix.Length); } } return outputPath; } private sealed class TestCSharpCommandLineParserService : ICommandLineParserService { public CommandLineArguments Parse(IEnumerable<string> arguments, string baseDirectory, bool isInteractive, string sdkDirectory) { if (baseDirectory == null || !Directory.Exists(baseDirectory)) { baseDirectory = Path.GetTempPath(); } return CSharpCommandLineParser.Default.Parse(arguments, baseDirectory, sdkDirectory); } } private class MockCSharpProjectRoot : ICSharpProjectRoot { private readonly IVsHierarchy _hierarchy; public MockCSharpProjectRoot(IVsHierarchy hierarchy) { _hierarchy = hierarchy; } int ICSharpProjectRoot.BelongsToProject(string pszFileName) { throw new NotImplementedException(); } string ICSharpProjectRoot.BuildPerConfigCacheFileName() { throw new NotImplementedException(); } bool ICSharpProjectRoot.CanCreateFileCodeModel(string pszFile) { throw new NotImplementedException(); } void ICSharpProjectRoot.ConfigureCompiler(ICSCompiler compiler, ICSInputSet inputSet, bool addSources) { throw new NotImplementedException(); } object ICSharpProjectRoot.CreateFileCodeModel(string pszFile, ref Guid riid) { throw new NotImplementedException(); } string ICSharpProjectRoot.GetActiveConfigurationName() { throw new NotImplementedException(); } string ICSharpProjectRoot.GetFullProjectName() { throw new NotImplementedException(); } int ICSharpProjectRoot.GetHierarchyAndItemID(string pszFile, out IVsHierarchy ppHier, out uint pItemID) { ppHier = _hierarchy; // Each item should have it's own ItemID, but for simplicity we'll just hard-code a value of // no particular significance. pItemID = 42; return VSConstants.S_OK; } void ICSharpProjectRoot.GetHierarchyAndItemIDOptionallyInProject(string pszFile, out IVsHierarchy ppHier, out uint pItemID, bool mustBeInProject) { throw new NotImplementedException(); } string ICSharpProjectRoot.GetProjectLocation() { throw new NotImplementedException(); } object ICSharpProjectRoot.GetProjectSite(ref Guid riid) { throw new NotImplementedException(); } void ICSharpProjectRoot.SetProjectSite(ICSharpProjectSite site) { 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Microsoft.VisualStudio.Shell.Interop; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim { internal static class CSharpHelpers { public static CSharpProjectShim CreateCSharpProject(TestEnvironment environment, string projectName) { var projectBinPath = Path.GetTempPath(); var hierarchy = environment.CreateHierarchy(projectName, projectBinPath, projectRefPath: null, projectCapabilities: "CSharp"); return CreateCSharpProject(environment, projectName, hierarchy); } public static CSharpProjectShim CreateCSharpProject(TestEnvironment environment, string projectName, IVsHierarchy hierarchy) { return new CSharpProjectShim( new MockCSharpProjectRoot(hierarchy), projectSystemName: projectName, hierarchy: hierarchy, serviceProvider: environment.ServiceProvider, threadingContext: environment.ThreadingContext); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, params string[] commandLineArguments) { return CreateCSharpCPSProjectAsync(environment, projectName, projectGuid: Guid.NewGuid(), commandLineArguments: commandLineArguments); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, Guid projectGuid, params string[] commandLineArguments) { var projectFilePath = Path.GetTempPath(); var binOutputPath = GetOutputPathFromArguments(commandLineArguments) ?? Path.Combine(projectFilePath, projectName + ".dll"); return CreateCSharpCPSProjectAsync(environment, projectName, projectFilePath, binOutputPath, projectGuid, commandLineArguments); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, string binOutputPath, params string[] commandLineArguments) { var projectFilePath = Path.GetTempPath(); return CreateCSharpCPSProjectAsync(environment, projectName, projectFilePath, binOutputPath, projectGuid: Guid.NewGuid(), commandLineArguments: commandLineArguments); } public static unsafe void SetOption(this CSharpProjectShim csharpProject, CompilerOptions optionID, object value) { Assert.Equal(sizeof(HACK_VariantStructure), 8 + 2 * IntPtr.Size); Assert.Equal(8, (int)Marshal.OffsetOf<HACK_VariantStructure>("_booleanValue")); HACK_VariantStructure variant = default; Marshal.GetNativeVariantForObject(value, (IntPtr)(&variant)); csharpProject.SetOption(optionID, variant); } public static async Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, string projectFilePath, string binOutputPath, Guid projectGuid, params string[] commandLineArguments) { var hierarchy = environment.CreateHierarchy(projectName, binOutputPath, projectRefPath: null, "CSharp"); var cpsProjectFactory = environment.ExportProvider.GetExportedValue<IWorkspaceProjectContextFactory>(); var cpsProject = (CPSProject)await cpsProjectFactory.CreateProjectContextAsync( LanguageNames.CSharp, projectName, projectFilePath, projectGuid, hierarchy, binOutputPath, assemblyName: null, CancellationToken.None); cpsProject.SetOptions(ImmutableArray.Create(commandLineArguments)); return cpsProject; } public static async Task<CPSProject> CreateNonCompilableProjectAsync(TestEnvironment environment, string projectName, string projectFilePath) { var hierarchy = environment.CreateHierarchy(projectName, projectBinPath: null, projectRefPath: null, ""); var cpsProjectFactory = environment.ExportProvider.GetExportedValue<IWorkspaceProjectContextFactory>(); return (CPSProject)await cpsProjectFactory.CreateProjectContextAsync( NoCompilationConstants.LanguageName, projectName, projectFilePath, Guid.NewGuid(), hierarchy, binOutputPath: null, assemblyName: null, CancellationToken.None); } private static string GetOutputPathFromArguments(string[] commandLineArguments) { const string outPrefix = "/out:"; string outputPath = null; foreach (var arg in commandLineArguments) { var index = arg.IndexOf(outPrefix); if (index >= 0) { outputPath = arg.Substring(index + outPrefix.Length); } } return outputPath; } private sealed class TestCSharpCommandLineParserService : ICommandLineParserService { public CommandLineArguments Parse(IEnumerable<string> arguments, string baseDirectory, bool isInteractive, string sdkDirectory) { if (baseDirectory == null || !Directory.Exists(baseDirectory)) { baseDirectory = Path.GetTempPath(); } return CSharpCommandLineParser.Default.Parse(arguments, baseDirectory, sdkDirectory); } } private class MockCSharpProjectRoot : ICSharpProjectRoot { private readonly IVsHierarchy _hierarchy; public MockCSharpProjectRoot(IVsHierarchy hierarchy) { _hierarchy = hierarchy; } int ICSharpProjectRoot.BelongsToProject(string pszFileName) { throw new NotImplementedException(); } string ICSharpProjectRoot.BuildPerConfigCacheFileName() { throw new NotImplementedException(); } bool ICSharpProjectRoot.CanCreateFileCodeModel(string pszFile) { throw new NotImplementedException(); } void ICSharpProjectRoot.ConfigureCompiler(ICSCompiler compiler, ICSInputSet inputSet, bool addSources) { throw new NotImplementedException(); } object ICSharpProjectRoot.CreateFileCodeModel(string pszFile, ref Guid riid) { throw new NotImplementedException(); } string ICSharpProjectRoot.GetActiveConfigurationName() { throw new NotImplementedException(); } string ICSharpProjectRoot.GetFullProjectName() { throw new NotImplementedException(); } int ICSharpProjectRoot.GetHierarchyAndItemID(string pszFile, out IVsHierarchy ppHier, out uint pItemID) { ppHier = _hierarchy; // Each item should have it's own ItemID, but for simplicity we'll just hard-code a value of // no particular significance. pItemID = 42; return VSConstants.S_OK; } void ICSharpProjectRoot.GetHierarchyAndItemIDOptionallyInProject(string pszFile, out IVsHierarchy ppHier, out uint pItemID, bool mustBeInProject) { throw new NotImplementedException(); } string ICSharpProjectRoot.GetProjectLocation() { throw new NotImplementedException(); } object ICSharpProjectRoot.GetProjectSite(ref Guid riid) { throw new NotImplementedException(); } void ICSharpProjectRoot.SetProjectSite(ICSharpProjectSite site) { throw new NotImplementedException(); } } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/IVSTypeScriptDiagnosticAnalyzerImplementation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptDiagnosticAnalyzerImplementation { Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSyntaxAsync(Document document, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSemanticsAsync(Document document, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptDiagnosticAnalyzerImplementation { Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSyntaxAsync(Document document, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSemanticsAsync(Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/Editor_OutOfProc.Verifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { /// <summary> /// Provides a means of interacting with the Visual Studio editor by remoting calls into Visual Studio. /// </summary> public partial class Editor_OutOfProc : TextViewWindow_OutOfProc { public class Verifier : Verifier<Editor_OutOfProc> { public Verifier(Editor_OutOfProc editor, VisualStudioInstance instance) : base(editor, instance) { } public void IsNotSaved() { _textViewWindow._editorInProc.VerifyNotSaved(); } public string IsSaved() { return _textViewWindow._editorInProc.VerifySaved(); } public void CurrentLineText( string expectedText, bool assertCaretPosition = false, bool trimWhitespace = true) { if (assertCaretPosition) { CurrentLineTextAndAssertCaretPosition(expectedText, trimWhitespace); } else { var lineText = _textViewWindow.GetCurrentLineText(); if (trimWhitespace) { lineText = lineText.Trim(); } Assert.Equal(expectedText, lineText); } } private void CurrentLineTextAndAssertCaretPosition( string expectedText, bool trimWhitespace) { var expectedCaretIndex = expectedText.IndexOf("$$"); if (expectedCaretIndex < 0) { throw new ArgumentException("Expected caret position to be specified with $$", nameof(expectedText)); } var expectedCaretMarkupEndIndex = expectedCaretIndex + "$$".Length; var expectedTextBeforeCaret = expectedText.Substring(0, expectedCaretIndex); var expectedTextAfterCaret = expectedText.Substring(expectedCaretMarkupEndIndex); var lineText = _textViewWindow.GetCurrentLineText(); var lineTextBeforeCaret = _textViewWindow.GetLineTextBeforeCaret(); var lineTextAfterCaret = _textViewWindow.GetLineTextAfterCaret(); // Asserts below perform separate verifications of text before and after the caret. // Depending on the position of the caret, if trimWhitespace, we trim beginning, end or both sides. if (trimWhitespace) { if (expectedCaretIndex == 0) { lineText = lineText.TrimEnd(); lineTextAfterCaret = lineTextAfterCaret.TrimEnd(); } else if (expectedCaretMarkupEndIndex == expectedText.Length) { lineText = lineText.TrimStart(); lineTextBeforeCaret = lineTextBeforeCaret.TrimStart(); } else { lineText = lineText.Trim(); lineTextBeforeCaret = lineTextBeforeCaret.TrimStart(); lineTextAfterCaret = lineTextAfterCaret.TrimEnd(); } } Assert.Equal(expectedTextBeforeCaret, lineTextBeforeCaret); Assert.Equal(expectedTextAfterCaret, lineTextAfterCaret); Assert.Equal(expectedTextBeforeCaret.Length + expectedTextAfterCaret.Length, lineText.Length); } public void TextContains( string expectedText, bool assertCaretPosition = false) { if (assertCaretPosition) { TextContainsAndAssertCaretPosition(expectedText); } else { var editorText = _textViewWindow.GetText(); Assert.Contains(expectedText, editorText); } } private void TextContainsAndAssertCaretPosition( string expectedText) { var caretStartIndex = expectedText.IndexOf("$$"); if (caretStartIndex < 0) { throw new ArgumentException("Expected caret position to be specified with $$", nameof(expectedText)); } var caretEndIndex = caretStartIndex + "$$".Length; var expectedTextBeforeCaret = expectedText.Substring(0, caretStartIndex); var expectedTextAfterCaret = expectedText.Substring(caretEndIndex); var expectedTextWithoutCaret = expectedTextBeforeCaret + expectedTextAfterCaret; var editorText = _textViewWindow.GetText(); Assert.Contains(expectedTextWithoutCaret, editorText); var index = editorText.IndexOf(expectedTextWithoutCaret); var caretPosition = _textViewWindow.GetCaretPosition(); Assert.Equal(caretStartIndex + index, caretPosition); } public void CompletionItemDoNotExist( params string[] expectedItems) { var completionItems = _textViewWindow.GetCompletionItems(); foreach (var expectedItem in expectedItems) { Assert.DoesNotContain(expectedItem, completionItems); } } public void CurrentCompletionItem( string expectedItem) { var currentItem = _textViewWindow.GetCurrentCompletionItem(); Assert.Equal(expectedItem, currentItem); } public void VerifyCurrentSignature( Signature expectedSignature) { var currentSignature = _textViewWindow.GetCurrentSignature(); Assert.Equal(expectedSignature, currentSignature); } public void CurrentSignature(string content) { var currentSignature = _textViewWindow.GetCurrentSignature(); Assert.Equal(content, currentSignature.Content); } public void CurrentParameter( string name, string documentation) { var currentParameter = _textViewWindow.GetCurrentSignature().CurrentParameter; Contract.ThrowIfNull(currentParameter); Assert.Equal(name, currentParameter.Name); Assert.Equal(documentation, currentParameter.Documentation); } public void Parameters( params (string name, string documentation)[] parameters) { var currentParameters = _textViewWindow.GetCurrentSignature().Parameters; Contract.ThrowIfNull(currentParameters); for (var i = 0; i < parameters.Length; i++) { var (expectedName, expectedDocumentation) = parameters[i]; Assert.Equal(expectedName, currentParameters[i].Name); Assert.Equal(expectedDocumentation, currentParameters[i].Documentation); } } public void Dialog( string dialogName, bool isOpen) { _textViewWindow.VerifyDialog(dialogName, isOpen); } public void ErrorTags(params string[] expectedTags) { _instance.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles); var actualTags = _textViewWindow.GetErrorTags(); AssertEx.EqualOrDiff( string.Join(Environment.NewLine, expectedTags), string.Join(Environment.NewLine, actualTags)); } public void IsProjectItemDirty(bool expectedValue) { Assert.Equal(expectedValue, _textViewWindow._editorInProc.IsProjectItemDirty()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { /// <summary> /// Provides a means of interacting with the Visual Studio editor by remoting calls into Visual Studio. /// </summary> public partial class Editor_OutOfProc : TextViewWindow_OutOfProc { public class Verifier : Verifier<Editor_OutOfProc> { public Verifier(Editor_OutOfProc editor, VisualStudioInstance instance) : base(editor, instance) { } public void IsNotSaved() { _textViewWindow._editorInProc.VerifyNotSaved(); } public string IsSaved() { return _textViewWindow._editorInProc.VerifySaved(); } public void CurrentLineText( string expectedText, bool assertCaretPosition = false, bool trimWhitespace = true) { if (assertCaretPosition) { CurrentLineTextAndAssertCaretPosition(expectedText, trimWhitespace); } else { var lineText = _textViewWindow.GetCurrentLineText(); if (trimWhitespace) { lineText = lineText.Trim(); } Assert.Equal(expectedText, lineText); } } private void CurrentLineTextAndAssertCaretPosition( string expectedText, bool trimWhitespace) { var expectedCaretIndex = expectedText.IndexOf("$$"); if (expectedCaretIndex < 0) { throw new ArgumentException("Expected caret position to be specified with $$", nameof(expectedText)); } var expectedCaretMarkupEndIndex = expectedCaretIndex + "$$".Length; var expectedTextBeforeCaret = expectedText.Substring(0, expectedCaretIndex); var expectedTextAfterCaret = expectedText.Substring(expectedCaretMarkupEndIndex); var lineText = _textViewWindow.GetCurrentLineText(); var lineTextBeforeCaret = _textViewWindow.GetLineTextBeforeCaret(); var lineTextAfterCaret = _textViewWindow.GetLineTextAfterCaret(); // Asserts below perform separate verifications of text before and after the caret. // Depending on the position of the caret, if trimWhitespace, we trim beginning, end or both sides. if (trimWhitespace) { if (expectedCaretIndex == 0) { lineText = lineText.TrimEnd(); lineTextAfterCaret = lineTextAfterCaret.TrimEnd(); } else if (expectedCaretMarkupEndIndex == expectedText.Length) { lineText = lineText.TrimStart(); lineTextBeforeCaret = lineTextBeforeCaret.TrimStart(); } else { lineText = lineText.Trim(); lineTextBeforeCaret = lineTextBeforeCaret.TrimStart(); lineTextAfterCaret = lineTextAfterCaret.TrimEnd(); } } Assert.Equal(expectedTextBeforeCaret, lineTextBeforeCaret); Assert.Equal(expectedTextAfterCaret, lineTextAfterCaret); Assert.Equal(expectedTextBeforeCaret.Length + expectedTextAfterCaret.Length, lineText.Length); } public void TextContains( string expectedText, bool assertCaretPosition = false) { if (assertCaretPosition) { TextContainsAndAssertCaretPosition(expectedText); } else { var editorText = _textViewWindow.GetText(); Assert.Contains(expectedText, editorText); } } private void TextContainsAndAssertCaretPosition( string expectedText) { var caretStartIndex = expectedText.IndexOf("$$"); if (caretStartIndex < 0) { throw new ArgumentException("Expected caret position to be specified with $$", nameof(expectedText)); } var caretEndIndex = caretStartIndex + "$$".Length; var expectedTextBeforeCaret = expectedText.Substring(0, caretStartIndex); var expectedTextAfterCaret = expectedText.Substring(caretEndIndex); var expectedTextWithoutCaret = expectedTextBeforeCaret + expectedTextAfterCaret; var editorText = _textViewWindow.GetText(); Assert.Contains(expectedTextWithoutCaret, editorText); var index = editorText.IndexOf(expectedTextWithoutCaret); var caretPosition = _textViewWindow.GetCaretPosition(); Assert.Equal(caretStartIndex + index, caretPosition); } public void CompletionItemDoNotExist( params string[] expectedItems) { var completionItems = _textViewWindow.GetCompletionItems(); foreach (var expectedItem in expectedItems) { Assert.DoesNotContain(expectedItem, completionItems); } } public void CurrentCompletionItem( string expectedItem) { var currentItem = _textViewWindow.GetCurrentCompletionItem(); Assert.Equal(expectedItem, currentItem); } public void VerifyCurrentSignature( Signature expectedSignature) { var currentSignature = _textViewWindow.GetCurrentSignature(); Assert.Equal(expectedSignature, currentSignature); } public void CurrentSignature(string content) { var currentSignature = _textViewWindow.GetCurrentSignature(); Assert.Equal(content, currentSignature.Content); } public void CurrentParameter( string name, string documentation) { var currentParameter = _textViewWindow.GetCurrentSignature().CurrentParameter; Contract.ThrowIfNull(currentParameter); Assert.Equal(name, currentParameter.Name); Assert.Equal(documentation, currentParameter.Documentation); } public void Parameters( params (string name, string documentation)[] parameters) { var currentParameters = _textViewWindow.GetCurrentSignature().Parameters; Contract.ThrowIfNull(currentParameters); for (var i = 0; i < parameters.Length; i++) { var (expectedName, expectedDocumentation) = parameters[i]; Assert.Equal(expectedName, currentParameters[i].Name); Assert.Equal(expectedDocumentation, currentParameters[i].Documentation); } } public void Dialog( string dialogName, bool isOpen) { _textViewWindow.VerifyDialog(dialogName, isOpen); } public void ErrorTags(params string[] expectedTags) { _instance.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles); var actualTags = _textViewWindow.GetErrorTags(); AssertEx.EqualOrDiff( string.Join(Environment.NewLine, expectedTags), string.Join(Environment.NewLine, actualTags)); } public void IsProjectItemDirty(bool expectedValue) { Assert.Equal(expectedValue, _textViewWindow._editorInProc.IsProjectItemDirty()); } } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Test/Utilities/CSharp/UsesIsNullableVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { /// <summary> /// Returns the set of members that contain reference types with IsNullable set. /// </summary> internal sealed class UsesIsNullableVisitor : CSharpSymbolVisitor<bool> { private readonly ArrayBuilder<Symbol> _builder; private UsesIsNullableVisitor(ArrayBuilder<Symbol> builder) { _builder = builder; } internal static void GetUses(ArrayBuilder<Symbol> builder, Symbol symbol) { var visitor = new UsesIsNullableVisitor(builder); visitor.Visit(symbol); } private void Add(Symbol symbol) => _builder.Add(symbol); public override bool VisitNamespace(NamespaceSymbol symbol) { return VisitList(symbol.GetMembers()); } public override bool VisitNamedType(NamedTypeSymbol symbol) { if (AddIfUsesIsNullable(symbol, symbol.BaseTypeNoUseSiteDiagnostics, inProgress: null) || AddIfUsesIsNullable(symbol, symbol.InterfacesNoUseSiteDiagnostics(), inProgress: null) || AddIfUsesIsNullable(symbol, symbol.TypeParameters, inProgress: null)) { return true; } return VisitList(symbol.GetMembers()); } public override bool VisitMethod(MethodSymbol symbol) { return AddIfUsesIsNullable(symbol, symbol.TypeParameters, inProgress: null) || AddIfUsesIsNullable(symbol, symbol.ReturnTypeWithAnnotations, inProgress: null) || AddIfUsesIsNullable(symbol, symbol.Parameters, inProgress: null); } public override bool VisitProperty(PropertySymbol symbol) { return AddIfUsesIsNullable(symbol, symbol.TypeWithAnnotations, inProgress: null) || AddIfUsesIsNullable(symbol, symbol.Parameters, inProgress: null); } public override bool VisitEvent(EventSymbol symbol) { return AddIfUsesIsNullable(symbol, symbol.TypeWithAnnotations, inProgress: null); } public override bool VisitField(FieldSymbol symbol) { return AddIfUsesIsNullable(symbol, symbol.TypeWithAnnotations, inProgress: null); } private bool VisitList<TSymbol>(ImmutableArray<TSymbol> symbols) where TSymbol : Symbol { bool result = false; foreach (var symbol in symbols) { if (this.Visit(symbol)) { result = true; } } return result; } /// <summary> /// Check the parameters of a method or property, but report that method/property rather than /// the parameter itself. /// </summary> private bool AddIfUsesIsNullable(Symbol symbol, ImmutableArray<ParameterSymbol> parameters, ConsList<TypeParameterSymbol> inProgress) { foreach (var parameter in parameters) { if (UsesIsNullable(parameter.TypeWithAnnotations, inProgress)) { Add(symbol); return true; } } return false; } private bool AddIfUsesIsNullable(Symbol symbol, ImmutableArray<TypeParameterSymbol> typeParameters, ConsList<TypeParameterSymbol> inProgress) { foreach (var type in typeParameters) { if (UsesIsNullable(type, inProgress)) { Add(symbol); return true; } } return false; } private bool AddIfUsesIsNullable(Symbol symbol, ImmutableArray<NamedTypeSymbol> types, ConsList<TypeParameterSymbol> inProgress) { foreach (var type in types) { if (UsesIsNullable(type, inProgress)) { Add(symbol); return true; } } return false; } private bool AddIfUsesIsNullable(Symbol symbol, TypeWithAnnotations type, ConsList<TypeParameterSymbol> inProgress) { if (UsesIsNullable(type, inProgress)) { Add(symbol); return true; } return false; } private bool AddIfUsesIsNullable(Symbol symbol, TypeSymbol type, ConsList<TypeParameterSymbol> inProgress) { if (UsesIsNullable(type, inProgress)) { Add(symbol); return true; } return false; } private bool UsesIsNullable(TypeWithAnnotations type, ConsList<TypeParameterSymbol> inProgress) { if (!type.HasType) { return false; } var typeSymbol = type.Type; return (type.NullableAnnotation != NullableAnnotation.Oblivious && typeSymbol.IsReferenceType && !typeSymbol.IsErrorType()) || UsesIsNullable(typeSymbol, inProgress); } private bool UsesIsNullable(TypeSymbol type, ConsList<TypeParameterSymbol> inProgress) { if (type is null) { return false; } switch (type.TypeKind) { case TypeKind.Class: case TypeKind.Delegate: case TypeKind.Interface: case TypeKind.Struct: case TypeKind.Enum: if (UsesIsNullable(type.ContainingType, inProgress)) { return true; } break; } switch (type.TypeKind) { case TypeKind.Array: return UsesIsNullable(((ArrayTypeSymbol)type).ElementTypeWithAnnotations, inProgress); case TypeKind.Class: case TypeKind.Delegate: case TypeKind.Error: case TypeKind.Interface: case TypeKind.Struct: return UsesIsNullable(((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, inProgress); case TypeKind.Dynamic: case TypeKind.Enum: return false; case TypeKind.Pointer: return UsesIsNullable(((PointerTypeSymbol)type).PointedAtTypeWithAnnotations, inProgress); case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)type; if (inProgress?.ContainsReference(typeParameter) == true) { return false; } inProgress = inProgress ?? ConsList<TypeParameterSymbol>.Empty; inProgress = inProgress.Prepend(typeParameter); return UsesIsNullable(typeParameter.ConstraintTypesNoUseSiteDiagnostics, inProgress) || typeParameter.ReferenceTypeConstraintIsNullable == true; default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private bool UsesIsNullable(ImmutableArray<TypeWithAnnotations> types, ConsList<TypeParameterSymbol> inProgress) { return types.Any(t => UsesIsNullable(t, inProgress)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { /// <summary> /// Returns the set of members that contain reference types with IsNullable set. /// </summary> internal sealed class UsesIsNullableVisitor : CSharpSymbolVisitor<bool> { private readonly ArrayBuilder<Symbol> _builder; private UsesIsNullableVisitor(ArrayBuilder<Symbol> builder) { _builder = builder; } internal static void GetUses(ArrayBuilder<Symbol> builder, Symbol symbol) { var visitor = new UsesIsNullableVisitor(builder); visitor.Visit(symbol); } private void Add(Symbol symbol) => _builder.Add(symbol); public override bool VisitNamespace(NamespaceSymbol symbol) { return VisitList(symbol.GetMembers()); } public override bool VisitNamedType(NamedTypeSymbol symbol) { if (AddIfUsesIsNullable(symbol, symbol.BaseTypeNoUseSiteDiagnostics, inProgress: null) || AddIfUsesIsNullable(symbol, symbol.InterfacesNoUseSiteDiagnostics(), inProgress: null) || AddIfUsesIsNullable(symbol, symbol.TypeParameters, inProgress: null)) { return true; } return VisitList(symbol.GetMembers()); } public override bool VisitMethod(MethodSymbol symbol) { return AddIfUsesIsNullable(symbol, symbol.TypeParameters, inProgress: null) || AddIfUsesIsNullable(symbol, symbol.ReturnTypeWithAnnotations, inProgress: null) || AddIfUsesIsNullable(symbol, symbol.Parameters, inProgress: null); } public override bool VisitProperty(PropertySymbol symbol) { return AddIfUsesIsNullable(symbol, symbol.TypeWithAnnotations, inProgress: null) || AddIfUsesIsNullable(symbol, symbol.Parameters, inProgress: null); } public override bool VisitEvent(EventSymbol symbol) { return AddIfUsesIsNullable(symbol, symbol.TypeWithAnnotations, inProgress: null); } public override bool VisitField(FieldSymbol symbol) { return AddIfUsesIsNullable(symbol, symbol.TypeWithAnnotations, inProgress: null); } private bool VisitList<TSymbol>(ImmutableArray<TSymbol> symbols) where TSymbol : Symbol { bool result = false; foreach (var symbol in symbols) { if (this.Visit(symbol)) { result = true; } } return result; } /// <summary> /// Check the parameters of a method or property, but report that method/property rather than /// the parameter itself. /// </summary> private bool AddIfUsesIsNullable(Symbol symbol, ImmutableArray<ParameterSymbol> parameters, ConsList<TypeParameterSymbol> inProgress) { foreach (var parameter in parameters) { if (UsesIsNullable(parameter.TypeWithAnnotations, inProgress)) { Add(symbol); return true; } } return false; } private bool AddIfUsesIsNullable(Symbol symbol, ImmutableArray<TypeParameterSymbol> typeParameters, ConsList<TypeParameterSymbol> inProgress) { foreach (var type in typeParameters) { if (UsesIsNullable(type, inProgress)) { Add(symbol); return true; } } return false; } private bool AddIfUsesIsNullable(Symbol symbol, ImmutableArray<NamedTypeSymbol> types, ConsList<TypeParameterSymbol> inProgress) { foreach (var type in types) { if (UsesIsNullable(type, inProgress)) { Add(symbol); return true; } } return false; } private bool AddIfUsesIsNullable(Symbol symbol, TypeWithAnnotations type, ConsList<TypeParameterSymbol> inProgress) { if (UsesIsNullable(type, inProgress)) { Add(symbol); return true; } return false; } private bool AddIfUsesIsNullable(Symbol symbol, TypeSymbol type, ConsList<TypeParameterSymbol> inProgress) { if (UsesIsNullable(type, inProgress)) { Add(symbol); return true; } return false; } private bool UsesIsNullable(TypeWithAnnotations type, ConsList<TypeParameterSymbol> inProgress) { if (!type.HasType) { return false; } var typeSymbol = type.Type; return (type.NullableAnnotation != NullableAnnotation.Oblivious && typeSymbol.IsReferenceType && !typeSymbol.IsErrorType()) || UsesIsNullable(typeSymbol, inProgress); } private bool UsesIsNullable(TypeSymbol type, ConsList<TypeParameterSymbol> inProgress) { if (type is null) { return false; } switch (type.TypeKind) { case TypeKind.Class: case TypeKind.Delegate: case TypeKind.Interface: case TypeKind.Struct: case TypeKind.Enum: if (UsesIsNullable(type.ContainingType, inProgress)) { return true; } break; } switch (type.TypeKind) { case TypeKind.Array: return UsesIsNullable(((ArrayTypeSymbol)type).ElementTypeWithAnnotations, inProgress); case TypeKind.Class: case TypeKind.Delegate: case TypeKind.Error: case TypeKind.Interface: case TypeKind.Struct: return UsesIsNullable(((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, inProgress); case TypeKind.Dynamic: case TypeKind.Enum: return false; case TypeKind.Pointer: return UsesIsNullable(((PointerTypeSymbol)type).PointedAtTypeWithAnnotations, inProgress); case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)type; if (inProgress?.ContainsReference(typeParameter) == true) { return false; } inProgress = inProgress ?? ConsList<TypeParameterSymbol>.Empty; inProgress = inProgress.Prepend(typeParameter); return UsesIsNullable(typeParameter.ConstraintTypesNoUseSiteDiagnostics, inProgress) || typeParameter.ReferenceTypeConstraintIsNullable == true; default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private bool UsesIsNullable(ImmutableArray<TypeWithAnnotations> types, ConsList<TypeParameterSymbol> inProgress) { return types.Any(t => UsesIsNullable(t, inProgress)); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/Core/Portable/Completion/CompletionItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// One of many possible completions used to form the completion list presented to the user. /// </summary> [DebuggerDisplay("{DisplayText}")] public sealed class CompletionItem : IComparable<CompletionItem> { private readonly string _filterText; /// <summary> /// The text that is displayed to the user. /// </summary> public string DisplayText { get; } /// <summary> /// An optional prefix to be displayed prepended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextPrefix { get; } /// <summary> /// An optional suffix to be displayed appended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextSuffix { get; } /// <summary> /// The text used to determine if the item matches the filter and is show in the list. /// This is often the same as <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string FilterText => _filterText ?? DisplayText; internal bool HasDifferentFilterText => _filterText != null; /// <summary> /// The text used to determine the order that the item appears in the list. /// This is often the same as the <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string SortText { get; } /// <summary> /// Descriptive text to place after <see cref="DisplayText"/> in the display layer. Should /// be short as it will show up in the UI. Display will present this in a way to distinguish /// this from the normal text (for example, by fading out and right-aligning). /// </summary> public string InlineDescription { get; } /// <summary> /// The span of the syntax element associated with this item. /// /// The span identifies the text in the document that is used to filter the initial list presented to the user, /// and typically represents the region of the document that will be changed if this item is committed. /// </summary> public TextSpan Span { get; internal set; } /// <summary> /// Additional information attached to a completion item by it creator. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Descriptive tags from <see cref="Tags.WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Rules that declare how this item should behave. /// </summary> public CompletionItemRules Rules { get; } /// <summary> /// Returns true if this item's text edit requires complex resolution that /// may impact performance. For example, an edit may be complex if it needs /// to format or type check the resulting code, or make complex non-local /// changes to other parts of the file. /// Complex resolution is used so we only do the minimum amount of work /// needed to display completion items. It is performed only for the /// committed item just prior to commit. Thus, it is ideal for any expensive /// completion work that does not affect the display of the item in the /// completion list, but is necessary for committing the item. /// An example of an item type requiring complex resolution is C#/VB /// override completion. /// </summary> public bool IsComplexTextEdit { get; } /// <summary> /// The name of the <see cref="CompletionProvider"/> that created this /// <see cref="CompletionItem"/>. Not available to clients. Only used by /// the Completion subsystem itself for things like getting description text /// and making additional change during commit. /// </summary> internal string ProviderName { get; set; } /// <summary> /// The automation text to use when narrating the completion item. If set to /// null, narration will use the <see cref="DisplayText"/> instead. /// </summary> internal string AutomationText { get; set; } internal CompletionItemFlags Flags { get; set; } private CompletionItem( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription, bool isComplexTextEdit) { DisplayText = displayText ?? ""; DisplayTextPrefix = displayTextPrefix ?? ""; DisplayTextSuffix = displayTextSuffix ?? ""; SortText = sortText ?? DisplayText; InlineDescription = inlineDescription ?? ""; Span = span; Properties = properties ?? ImmutableDictionary<string, string>.Empty; Tags = tags.NullToEmpty(); Rules = rules ?? CompletionItemRules.Default; IsComplexTextEdit = isComplexTextEdit; if (!DisplayText.Equals(filterText, StringComparison.Ordinal)) { _filterText = filterText; } } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix: null, displayTextSuffix: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) { return Create( displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription, isComplexTextEdit: false); } public static CompletionItem Create( string displayText, string filterText = null, string sortText = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null, bool isComplexTextEdit = false) { return new CompletionItem( span: default, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: displayTextPrefix, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit); } /// <summary> /// Creates a new <see cref="CompletionItem"/> /// </summary> /// <param name="displayText">The text that is displayed to the user.</param> /// <param name="filterText">The text used to determine if the item matches the filter and is show in the list.</param> /// <param name="sortText">The text used to determine the order that the item appears in the list.</param> /// <param name="span">The span of the syntax element in the document associated with this item.</param> /// <param name="properties">Additional information.</param> /// <param name="tags">Descriptive tags that may influence how the item is displayed.</param> /// <param name="rules">The rules that declare how this item should behave.</param> /// <returns></returns> [Obsolete("Use the Create overload that does not take a span", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static CompletionItem Create( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return new CompletionItem( span: span, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: null, displayTextSuffix: null, inlineDescription: null, isComplexTextEdit: false); } private CompletionItem With( Optional<TextSpan> span = default, Optional<string> displayText = default, Optional<string> filterText = default, Optional<string> sortText = default, Optional<ImmutableDictionary<string, string>> properties = default, Optional<ImmutableArray<string>> tags = default, Optional<CompletionItemRules> rules = default, Optional<string> displayTextPrefix = default, Optional<string> displayTextSuffix = default, Optional<string> inlineDescription = default, Optional<bool> isComplexTextEdit = default) { var newSpan = span.HasValue ? span.Value : Span; var newDisplayText = displayText.HasValue ? displayText.Value : DisplayText; var newFilterText = filterText.HasValue ? filterText.Value : FilterText; var newSortText = sortText.HasValue ? sortText.Value : SortText; var newInlineDescription = inlineDescription.HasValue ? inlineDescription.Value : InlineDescription; var newProperties = properties.HasValue ? properties.Value : Properties; var newTags = tags.HasValue ? tags.Value : Tags; var newRules = rules.HasValue ? rules.Value : Rules; var newDisplayTextPrefix = displayTextPrefix.HasValue ? displayTextPrefix.Value : DisplayTextPrefix; var newDisplayTextSuffix = displayTextSuffix.HasValue ? displayTextSuffix.Value : DisplayTextSuffix; var newIsComplexTextEdit = isComplexTextEdit.HasValue ? isComplexTextEdit.Value : IsComplexTextEdit; if (newSpan == Span && newDisplayText == DisplayText && newFilterText == FilterText && newSortText == SortText && newProperties == Properties && newTags == Tags && newRules == Rules && newDisplayTextPrefix == DisplayTextPrefix && newDisplayTextSuffix == DisplayTextSuffix && newInlineDescription == InlineDescription && newIsComplexTextEdit == IsComplexTextEdit) { return this; } return new CompletionItem( displayText: newDisplayText, filterText: newFilterText, span: newSpan, sortText: newSortText, properties: newProperties, tags: newTags, rules: newRules, displayTextPrefix: newDisplayTextPrefix, displayTextSuffix: newDisplayTextSuffix, inlineDescription: newInlineDescription, isComplexTextEdit: newIsComplexTextEdit) { AutomationText = AutomationText, ProviderName = ProviderName, Flags = Flags, }; } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Span"/> property changed. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used to control the span used for filtering.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public CompletionItem WithSpan(TextSpan span) => this; /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayText"/> property changed. /// </summary> public CompletionItem WithDisplayText(string text) => With(displayText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextPrefix"/> property changed. /// </summary> public CompletionItem WithDisplayTextPrefix(string displayTextPrefix) => With(displayTextPrefix: displayTextPrefix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextSuffix"/> property changed. /// </summary> public CompletionItem WithDisplayTextSuffix(string displayTextSuffix) => With(displayTextSuffix: displayTextSuffix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="FilterText"/> property changed. /// </summary> public CompletionItem WithFilterText(string text) => With(filterText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="SortText"/> property changed. /// </summary> public CompletionItem WithSortText(string text) => With(sortText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Properties"/> property changed. /// </summary> public CompletionItem WithProperties(ImmutableDictionary<string, string> properties) => With(properties: properties); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a property added to the <see cref="Properties"/> collection. /// </summary> public CompletionItem AddProperty(string name, string value) => With(properties: Properties.Add(name, value)); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Tags"/> property changed. /// </summary> public CompletionItem WithTags(ImmutableArray<string> tags) => With(tags: tags); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a tag added to the <see cref="Tags"/> collection. /// </summary> public CompletionItem AddTag(string tag) { if (tag == null) { throw new ArgumentNullException(nameof(tag)); } if (Tags.Contains(tag)) { return this; } else { return With(tags: Tags.Add(tag)); } } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionItem WithRules(CompletionItemRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="IsComplexTextEdit"/> property changed. /// </summary> public CompletionItem WithIsComplexTextEdit(bool isComplexTextEdit) => With(isComplexTextEdit: isComplexTextEdit); private string _entireDisplayText; int IComparable<CompletionItem>.CompareTo(CompletionItem other) { // Make sure expanded items are listed after non-expanded ones var thisIsExpandItem = Flags.IsExpanded(); var otherIsExpandItem = other.Flags.IsExpanded(); if (thisIsExpandItem == otherIsExpandItem) { var result = StringComparer.OrdinalIgnoreCase.Compare(SortText, other.SortText); if (result == 0) { result = StringComparer.OrdinalIgnoreCase.Compare(GetEntireDisplayText(), other.GetEntireDisplayText()); } return result; } else if (thisIsExpandItem) { return 1; } else { return -1; } } internal string GetEntireDisplayText() { if (_entireDisplayText == null) { _entireDisplayText = DisplayTextPrefix + DisplayText + DisplayTextSuffix; } return _entireDisplayText; } public override string ToString() => GetEntireDisplayText(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// One of many possible completions used to form the completion list presented to the user. /// </summary> [DebuggerDisplay("{DisplayText}")] public sealed class CompletionItem : IComparable<CompletionItem> { private readonly string _filterText; /// <summary> /// The text that is displayed to the user. /// </summary> public string DisplayText { get; } /// <summary> /// An optional prefix to be displayed prepended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextPrefix { get; } /// <summary> /// An optional suffix to be displayed appended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextSuffix { get; } /// <summary> /// The text used to determine if the item matches the filter and is show in the list. /// This is often the same as <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string FilterText => _filterText ?? DisplayText; internal bool HasDifferentFilterText => _filterText != null; /// <summary> /// The text used to determine the order that the item appears in the list. /// This is often the same as the <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string SortText { get; } /// <summary> /// Descriptive text to place after <see cref="DisplayText"/> in the display layer. Should /// be short as it will show up in the UI. Display will present this in a way to distinguish /// this from the normal text (for example, by fading out and right-aligning). /// </summary> public string InlineDescription { get; } /// <summary> /// The span of the syntax element associated with this item. /// /// The span identifies the text in the document that is used to filter the initial list presented to the user, /// and typically represents the region of the document that will be changed if this item is committed. /// </summary> public TextSpan Span { get; internal set; } /// <summary> /// Additional information attached to a completion item by it creator. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Descriptive tags from <see cref="Tags.WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Rules that declare how this item should behave. /// </summary> public CompletionItemRules Rules { get; } /// <summary> /// Returns true if this item's text edit requires complex resolution that /// may impact performance. For example, an edit may be complex if it needs /// to format or type check the resulting code, or make complex non-local /// changes to other parts of the file. /// Complex resolution is used so we only do the minimum amount of work /// needed to display completion items. It is performed only for the /// committed item just prior to commit. Thus, it is ideal for any expensive /// completion work that does not affect the display of the item in the /// completion list, but is necessary for committing the item. /// An example of an item type requiring complex resolution is C#/VB /// override completion. /// </summary> public bool IsComplexTextEdit { get; } /// <summary> /// The name of the <see cref="CompletionProvider"/> that created this /// <see cref="CompletionItem"/>. Not available to clients. Only used by /// the Completion subsystem itself for things like getting description text /// and making additional change during commit. /// </summary> internal string ProviderName { get; set; } /// <summary> /// The automation text to use when narrating the completion item. If set to /// null, narration will use the <see cref="DisplayText"/> instead. /// </summary> internal string AutomationText { get; set; } internal CompletionItemFlags Flags { get; set; } private CompletionItem( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription, bool isComplexTextEdit) { DisplayText = displayText ?? ""; DisplayTextPrefix = displayTextPrefix ?? ""; DisplayTextSuffix = displayTextSuffix ?? ""; SortText = sortText ?? DisplayText; InlineDescription = inlineDescription ?? ""; Span = span; Properties = properties ?? ImmutableDictionary<string, string>.Empty; Tags = tags.NullToEmpty(); Rules = rules ?? CompletionItemRules.Default; IsComplexTextEdit = isComplexTextEdit; if (!DisplayText.Equals(filterText, StringComparison.Ordinal)) { _filterText = filterText; } } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix: null, displayTextSuffix: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) { return Create( displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription, isComplexTextEdit: false); } public static CompletionItem Create( string displayText, string filterText = null, string sortText = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null, bool isComplexTextEdit = false) { return new CompletionItem( span: default, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: displayTextPrefix, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit); } /// <summary> /// Creates a new <see cref="CompletionItem"/> /// </summary> /// <param name="displayText">The text that is displayed to the user.</param> /// <param name="filterText">The text used to determine if the item matches the filter and is show in the list.</param> /// <param name="sortText">The text used to determine the order that the item appears in the list.</param> /// <param name="span">The span of the syntax element in the document associated with this item.</param> /// <param name="properties">Additional information.</param> /// <param name="tags">Descriptive tags that may influence how the item is displayed.</param> /// <param name="rules">The rules that declare how this item should behave.</param> /// <returns></returns> [Obsolete("Use the Create overload that does not take a span", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static CompletionItem Create( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return new CompletionItem( span: span, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: null, displayTextSuffix: null, inlineDescription: null, isComplexTextEdit: false); } private CompletionItem With( Optional<TextSpan> span = default, Optional<string> displayText = default, Optional<string> filterText = default, Optional<string> sortText = default, Optional<ImmutableDictionary<string, string>> properties = default, Optional<ImmutableArray<string>> tags = default, Optional<CompletionItemRules> rules = default, Optional<string> displayTextPrefix = default, Optional<string> displayTextSuffix = default, Optional<string> inlineDescription = default, Optional<bool> isComplexTextEdit = default) { var newSpan = span.HasValue ? span.Value : Span; var newDisplayText = displayText.HasValue ? displayText.Value : DisplayText; var newFilterText = filterText.HasValue ? filterText.Value : FilterText; var newSortText = sortText.HasValue ? sortText.Value : SortText; var newInlineDescription = inlineDescription.HasValue ? inlineDescription.Value : InlineDescription; var newProperties = properties.HasValue ? properties.Value : Properties; var newTags = tags.HasValue ? tags.Value : Tags; var newRules = rules.HasValue ? rules.Value : Rules; var newDisplayTextPrefix = displayTextPrefix.HasValue ? displayTextPrefix.Value : DisplayTextPrefix; var newDisplayTextSuffix = displayTextSuffix.HasValue ? displayTextSuffix.Value : DisplayTextSuffix; var newIsComplexTextEdit = isComplexTextEdit.HasValue ? isComplexTextEdit.Value : IsComplexTextEdit; if (newSpan == Span && newDisplayText == DisplayText && newFilterText == FilterText && newSortText == SortText && newProperties == Properties && newTags == Tags && newRules == Rules && newDisplayTextPrefix == DisplayTextPrefix && newDisplayTextSuffix == DisplayTextSuffix && newInlineDescription == InlineDescription && newIsComplexTextEdit == IsComplexTextEdit) { return this; } return new CompletionItem( displayText: newDisplayText, filterText: newFilterText, span: newSpan, sortText: newSortText, properties: newProperties, tags: newTags, rules: newRules, displayTextPrefix: newDisplayTextPrefix, displayTextSuffix: newDisplayTextSuffix, inlineDescription: newInlineDescription, isComplexTextEdit: newIsComplexTextEdit) { AutomationText = AutomationText, ProviderName = ProviderName, Flags = Flags, }; } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Span"/> property changed. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used to control the span used for filtering.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public CompletionItem WithSpan(TextSpan span) => this; /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayText"/> property changed. /// </summary> public CompletionItem WithDisplayText(string text) => With(displayText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextPrefix"/> property changed. /// </summary> public CompletionItem WithDisplayTextPrefix(string displayTextPrefix) => With(displayTextPrefix: displayTextPrefix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextSuffix"/> property changed. /// </summary> public CompletionItem WithDisplayTextSuffix(string displayTextSuffix) => With(displayTextSuffix: displayTextSuffix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="FilterText"/> property changed. /// </summary> public CompletionItem WithFilterText(string text) => With(filterText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="SortText"/> property changed. /// </summary> public CompletionItem WithSortText(string text) => With(sortText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Properties"/> property changed. /// </summary> public CompletionItem WithProperties(ImmutableDictionary<string, string> properties) => With(properties: properties); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a property added to the <see cref="Properties"/> collection. /// </summary> public CompletionItem AddProperty(string name, string value) => With(properties: Properties.Add(name, value)); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Tags"/> property changed. /// </summary> public CompletionItem WithTags(ImmutableArray<string> tags) => With(tags: tags); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a tag added to the <see cref="Tags"/> collection. /// </summary> public CompletionItem AddTag(string tag) { if (tag == null) { throw new ArgumentNullException(nameof(tag)); } if (Tags.Contains(tag)) { return this; } else { return With(tags: Tags.Add(tag)); } } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionItem WithRules(CompletionItemRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="IsComplexTextEdit"/> property changed. /// </summary> public CompletionItem WithIsComplexTextEdit(bool isComplexTextEdit) => With(isComplexTextEdit: isComplexTextEdit); private string _entireDisplayText; int IComparable<CompletionItem>.CompareTo(CompletionItem other) { // Make sure expanded items are listed after non-expanded ones var thisIsExpandItem = Flags.IsExpanded(); var otherIsExpandItem = other.Flags.IsExpanded(); if (thisIsExpandItem == otherIsExpandItem) { var result = StringComparer.OrdinalIgnoreCase.Compare(SortText, other.SortText); if (result == 0) { result = StringComparer.OrdinalIgnoreCase.Compare(GetEntireDisplayText(), other.GetEntireDisplayText()); } return result; } else if (thisIsExpandItem) { return 1; } else { return -1; } } internal string GetEntireDisplayText() { if (_entireDisplayText == null) { _entireDisplayText = DisplayTextPrefix + DisplayText + DisplayTextSuffix; } return _entireDisplayText; } public override string ToString() => GetEntireDisplayText(); } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicEscapingReducer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicEscapingReducer Inherits AbstractVisualBasicReducer Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) = New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool)) Public Sub New() MyBase.New(s_pool) End Sub #Disable Warning IDE0060 ' Remove unused parameter - False positive, used as a delegate in a nested type. ' https://github.com/dotnet/roslyn/issues/44226 Private Shared Function TryUnescapeToken(identifier As SyntaxToken, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken) As SyntaxToken #Enable Warning IDE0060 ' Remove unused parameter If Not identifier.IsBracketed Then Return identifier End If Dim unescapedIdentifier = identifier.ValueText ' 1. handle keywords ' REM should always be escaped ' e.g. ' Dim [Rem] = 23 ' Call Goo.[Rem]() If SyntaxFacts.GetKeywordKind(unescapedIdentifier) = SyntaxKind.REMKeyword Then Return identifier End If Dim parent = identifier.Parent ' this identifier is a keyword If SyntaxFacts.GetKeywordKind(unescapedIdentifier) <> SyntaxKind.None Then ' Always escape keywords as identifier if they are not part of a qualified name or member access ' e.g. Class [Class] If Not TypeOf (parent) Is ExpressionSyntax Then Return identifier Else ' always escape keywords on the left side of a dot If Not DirectCast(parent, ExpressionSyntax).IsRightSideOfDot() Then Return identifier End If End If End If ' 2. Handle contextual keywords ' Escape the Await Identifier if within the Single Line Lambda & Multi Line Context ' Dim y = Async Function() [Await]() but not Dim y = Async Function() Await() ' Same behavior for Multi Line Lambda If SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) = SyntaxKind.AwaitKeyword Then Dim enclosingSingleLineLambda = parent.GetAncestor(Of LambdaExpressionSyntax)() If enclosingSingleLineLambda IsNot Nothing AndAlso enclosingSingleLineLambda.SubOrFunctionHeader.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.AsyncKeyword) Then Return identifier End If Dim enclosingMethodBlock = parent.GetAncestor(Of MethodBlockBaseSyntax)() If enclosingMethodBlock IsNot Nothing AndAlso enclosingMethodBlock.BlockStatement.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.AsyncKeyword) Then Return identifier End If End If ' escape the identifier "preserve" if it's inside of a redim statement If TypeOf parent Is SimpleNameSyntax AndAlso IsPreserveInReDim(DirectCast(parent, SimpleNameSyntax)) Then Return identifier End If ' handle "Mid" identifier that is not part of an Mid assignment statement which must be escaped if the containing statement ' starts with the "Mid" identifier token. If SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) = SyntaxKind.MidKeyword Then Dim enclosingStatement = parent.GetAncestor(Of StatementSyntax)() If enclosingStatement.Kind <> SyntaxKind.MidAssignmentStatement Then If enclosingStatement.GetFirstToken() = identifier Then Return identifier End If End If End If ' handle new identifier If SyntaxFacts.GetKeywordKind(unescapedIdentifier) = SyntaxKind.NewKeyword Then Dim typedParent = TryCast(parent, ExpressionSyntax) If typedParent IsNot Nothing Then Dim symbol = semanticModel.GetSymbolInfo(typedParent, cancellationToken).Symbol If symbol IsNot Nothing AndAlso symbol.Kind = SymbolKind.Method AndAlso Not DirectCast(symbol, IMethodSymbol).IsConstructor Then If symbol.ContainingType IsNot Nothing Then Dim type = symbol.ContainingType If type.TypeKind <> TypeKind.Interface AndAlso type.TypeKind <> TypeKind.Enum Then Return identifier End If End If End If End If End If ' handle identifier Group in a function aggregation If SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) = SyntaxKind.GroupKeyword Then If parent.Kind = SyntaxKind.FunctionAggregation AndAlso parent.GetFirstToken() = identifier Then Return identifier End If End If Dim lastTokenOfQuery As SyntaxToken = Nothing Dim firstTokenAfterQueryExpression As SyntaxToken = Nothing ' escape contextual query keywords if they are the first token after a query expression ' and on the following line Dim previousToken = identifier.GetPreviousToken(False, False, True, True) Dim queryAncestorOfPrevious = previousToken.GetAncestors(Of QueryExpressionSyntax).FirstOrDefault() If queryAncestorOfPrevious IsNot Nothing AndAlso queryAncestorOfPrevious.GetLastToken() = previousToken Then lastTokenOfQuery = previousToken Dim checkQueryToken = False Select Case SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) Case SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.FromKeyword, SyntaxKind.GroupKeyword, SyntaxKind.IntoKeyword, SyntaxKind.JoinKeyword, SyntaxKind.OrderKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.WhereKeyword checkQueryToken = True Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword checkQueryToken = lastTokenOfQuery.HasAncestor(Of OrderByClauseSyntax)() End Select If checkQueryToken Then Dim text = parent.SyntaxTree.GetText(cancellationToken) Dim endLineOfQuery = text.Lines.GetLineFromPosition(lastTokenOfQuery.Span.End).LineNumber Dim startLineOfCurrentToken = text.Lines.GetLineFromPosition(identifier.SpanStart).LineNumber ' Easy out: if the current token starts the line after the query, we can't escape. If startLineOfCurrentToken = endLineOfQuery + 1 Then Return identifier End If ' if this token is part of a XmlDocument, all trailing whitespace is part of the XmlDocument ' so all line breaks actually will not help. ' see VB spec #11.23.3 If previousToken.GetAncestors(Of XmlDocumentSyntax).FirstOrDefault() IsNot Nothing Then Return identifier End If ' If there are more lines between the query and the next token, we check to see if any ' of them are blank lines. If a blank line is encountered, we can assume that the ' identifier can be unescaped. Otherwise, we'll end up incorrectly unescaping in ' code like so. ' ' Dim q = From x in "" ' _ ' _ ' [Take]() If startLineOfCurrentToken > endLineOfQuery + 1 Then Dim unescape = False For i = endLineOfQuery + 1 To startLineOfCurrentToken - 1 If text.Lines(i).IsEmptyOrWhitespace() Then unescape = True Exit For End If Next If Not unescape Then Return identifier End If End If End If End If ' build new unescaped identifier token Dim newIdentifier = CreateNewIdentifierTokenFromToken(identifier, False) Dim parentAsSimpleName = TryCast(parent, SimpleNameSyntax) If parentAsSimpleName IsNot Nothing Then ' try if unescaped identifier is valid in this context If ExpressionSyntaxExtensions.IsReservedNameInAttribute(parentAsSimpleName, parentAsSimpleName.WithIdentifier(newIdentifier)) Then Return identifier End If End If ' safe to return an unescaped identifier Return newIdentifier End Function Private Shared Function CreateNewIdentifierTokenFromToken(originalToken As SyntaxToken, escape As Boolean) As SyntaxToken Return If(escape, originalToken.CopyAnnotationsTo(SyntaxFactory.BracketedIdentifier(originalToken.LeadingTrivia, originalToken.ValueText, originalToken.TrailingTrivia)), originalToken.CopyAnnotationsTo(SyntaxFactory.Identifier(originalToken.LeadingTrivia, originalToken.ValueText, originalToken.TrailingTrivia))) End Function Private Shared Function IsPreserveInReDim(node As SimpleNameSyntax) As Boolean Dim redimStatement = node.GetAncestor(Of ReDimStatementSyntax)() If redimStatement IsNot Nothing AndAlso SyntaxFacts.GetContextualKeywordKind(node.Identifier.GetIdentifierText()) = SyntaxKind.PreserveKeyword AndAlso redimStatement.Clauses.Count > 0 AndAlso redimStatement.Clauses.First().GetFirstToken() = node.GetFirstToken() Then Return True End If Return False End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicEscapingReducer Inherits AbstractVisualBasicReducer Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) = New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool)) Public Sub New() MyBase.New(s_pool) End Sub #Disable Warning IDE0060 ' Remove unused parameter - False positive, used as a delegate in a nested type. ' https://github.com/dotnet/roslyn/issues/44226 Private Shared Function TryUnescapeToken(identifier As SyntaxToken, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken) As SyntaxToken #Enable Warning IDE0060 ' Remove unused parameter If Not identifier.IsBracketed Then Return identifier End If Dim unescapedIdentifier = identifier.ValueText ' 1. handle keywords ' REM should always be escaped ' e.g. ' Dim [Rem] = 23 ' Call Goo.[Rem]() If SyntaxFacts.GetKeywordKind(unescapedIdentifier) = SyntaxKind.REMKeyword Then Return identifier End If Dim parent = identifier.Parent ' this identifier is a keyword If SyntaxFacts.GetKeywordKind(unescapedIdentifier) <> SyntaxKind.None Then ' Always escape keywords as identifier if they are not part of a qualified name or member access ' e.g. Class [Class] If Not TypeOf (parent) Is ExpressionSyntax Then Return identifier Else ' always escape keywords on the left side of a dot If Not DirectCast(parent, ExpressionSyntax).IsRightSideOfDot() Then Return identifier End If End If End If ' 2. Handle contextual keywords ' Escape the Await Identifier if within the Single Line Lambda & Multi Line Context ' Dim y = Async Function() [Await]() but not Dim y = Async Function() Await() ' Same behavior for Multi Line Lambda If SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) = SyntaxKind.AwaitKeyword Then Dim enclosingSingleLineLambda = parent.GetAncestor(Of LambdaExpressionSyntax)() If enclosingSingleLineLambda IsNot Nothing AndAlso enclosingSingleLineLambda.SubOrFunctionHeader.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.AsyncKeyword) Then Return identifier End If Dim enclosingMethodBlock = parent.GetAncestor(Of MethodBlockBaseSyntax)() If enclosingMethodBlock IsNot Nothing AndAlso enclosingMethodBlock.BlockStatement.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.AsyncKeyword) Then Return identifier End If End If ' escape the identifier "preserve" if it's inside of a redim statement If TypeOf parent Is SimpleNameSyntax AndAlso IsPreserveInReDim(DirectCast(parent, SimpleNameSyntax)) Then Return identifier End If ' handle "Mid" identifier that is not part of an Mid assignment statement which must be escaped if the containing statement ' starts with the "Mid" identifier token. If SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) = SyntaxKind.MidKeyword Then Dim enclosingStatement = parent.GetAncestor(Of StatementSyntax)() If enclosingStatement.Kind <> SyntaxKind.MidAssignmentStatement Then If enclosingStatement.GetFirstToken() = identifier Then Return identifier End If End If End If ' handle new identifier If SyntaxFacts.GetKeywordKind(unescapedIdentifier) = SyntaxKind.NewKeyword Then Dim typedParent = TryCast(parent, ExpressionSyntax) If typedParent IsNot Nothing Then Dim symbol = semanticModel.GetSymbolInfo(typedParent, cancellationToken).Symbol If symbol IsNot Nothing AndAlso symbol.Kind = SymbolKind.Method AndAlso Not DirectCast(symbol, IMethodSymbol).IsConstructor Then If symbol.ContainingType IsNot Nothing Then Dim type = symbol.ContainingType If type.TypeKind <> TypeKind.Interface AndAlso type.TypeKind <> TypeKind.Enum Then Return identifier End If End If End If End If End If ' handle identifier Group in a function aggregation If SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) = SyntaxKind.GroupKeyword Then If parent.Kind = SyntaxKind.FunctionAggregation AndAlso parent.GetFirstToken() = identifier Then Return identifier End If End If Dim lastTokenOfQuery As SyntaxToken = Nothing Dim firstTokenAfterQueryExpression As SyntaxToken = Nothing ' escape contextual query keywords if they are the first token after a query expression ' and on the following line Dim previousToken = identifier.GetPreviousToken(False, False, True, True) Dim queryAncestorOfPrevious = previousToken.GetAncestors(Of QueryExpressionSyntax).FirstOrDefault() If queryAncestorOfPrevious IsNot Nothing AndAlso queryAncestorOfPrevious.GetLastToken() = previousToken Then lastTokenOfQuery = previousToken Dim checkQueryToken = False Select Case SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) Case SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.FromKeyword, SyntaxKind.GroupKeyword, SyntaxKind.IntoKeyword, SyntaxKind.JoinKeyword, SyntaxKind.OrderKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.WhereKeyword checkQueryToken = True Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword checkQueryToken = lastTokenOfQuery.HasAncestor(Of OrderByClauseSyntax)() End Select If checkQueryToken Then Dim text = parent.SyntaxTree.GetText(cancellationToken) Dim endLineOfQuery = text.Lines.GetLineFromPosition(lastTokenOfQuery.Span.End).LineNumber Dim startLineOfCurrentToken = text.Lines.GetLineFromPosition(identifier.SpanStart).LineNumber ' Easy out: if the current token starts the line after the query, we can't escape. If startLineOfCurrentToken = endLineOfQuery + 1 Then Return identifier End If ' if this token is part of a XmlDocument, all trailing whitespace is part of the XmlDocument ' so all line breaks actually will not help. ' see VB spec #11.23.3 If previousToken.GetAncestors(Of XmlDocumentSyntax).FirstOrDefault() IsNot Nothing Then Return identifier End If ' If there are more lines between the query and the next token, we check to see if any ' of them are blank lines. If a blank line is encountered, we can assume that the ' identifier can be unescaped. Otherwise, we'll end up incorrectly unescaping in ' code like so. ' ' Dim q = From x in "" ' _ ' _ ' [Take]() If startLineOfCurrentToken > endLineOfQuery + 1 Then Dim unescape = False For i = endLineOfQuery + 1 To startLineOfCurrentToken - 1 If text.Lines(i).IsEmptyOrWhitespace() Then unescape = True Exit For End If Next If Not unescape Then Return identifier End If End If End If End If ' build new unescaped identifier token Dim newIdentifier = CreateNewIdentifierTokenFromToken(identifier, False) Dim parentAsSimpleName = TryCast(parent, SimpleNameSyntax) If parentAsSimpleName IsNot Nothing Then ' try if unescaped identifier is valid in this context If ExpressionSyntaxExtensions.IsReservedNameInAttribute(parentAsSimpleName, parentAsSimpleName.WithIdentifier(newIdentifier)) Then Return identifier End If End If ' safe to return an unescaped identifier Return newIdentifier End Function Private Shared Function CreateNewIdentifierTokenFromToken(originalToken As SyntaxToken, escape As Boolean) As SyntaxToken Return If(escape, originalToken.CopyAnnotationsTo(SyntaxFactory.BracketedIdentifier(originalToken.LeadingTrivia, originalToken.ValueText, originalToken.TrailingTrivia)), originalToken.CopyAnnotationsTo(SyntaxFactory.Identifier(originalToken.LeadingTrivia, originalToken.ValueText, originalToken.TrailingTrivia))) End Function Private Shared Function IsPreserveInReDim(node As SimpleNameSyntax) As Boolean Dim redimStatement = node.GetAncestor(Of ReDimStatementSyntax)() If redimStatement IsNot Nothing AndAlso SyntaxFacts.GetContextualKeywordKind(node.Identifier.GetIdentifierText()) = SyntaxKind.PreserveKeyword AndAlso redimStatement.Clauses.Count > 0 AndAlso redimStatement.Clauses.First().GetFirstToken() = node.GetFirstToken() Then Return True End If Return False End Function End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Test/Resources/Core/WinRt/WinMDPrefixing.ildump
.assembly extern mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 .assembly extern Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime .assembly extern System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a .assembly extern System.Runtime.InteropServices.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a .assembly extern System.ObjectModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a .assembly extern System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 .assembly extern System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 .assembly extern System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a .class private auto ansi <Module> { } .class private auto ansi import windowsruntime sealed beforefieldinit WinMDPrefixing.<WinRT>TestClass extends object implements WinMDPrefixing.TestInterface { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .custom public hidebysig specialname rtspecialname instance void System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() cil managed = () .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.ActivatableAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .method public hidebysig specialname rtspecialname instance void .ctor() runtime managed internalcall } .class public auto ansi sealed beforefieldinit WinMDPrefixing.TestClass extends object implements WinMDPrefixing.TestInterface { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.ActivatableAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed } .class public auto ansi windowsruntime sealed WinMDPrefixing.TestDelegate extends System.MulticastDelegate { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.GuidAttribute::.ctor([in] uint a, [in] ushort b, [in] ushort c, [in] byte d, [in] byte e, [in] byte f, [in] byte g, [in] byte h, [in] byte i, [in] byte j, [in] byte k) runtime managed internalcall = (1338053136, 62160, 23065, 93, 128, 84, 115, 135, 159, 103, 15) .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .method public hidebysig specialname rtspecialname instance void .ctor(object object, System.IntPtr method) runtime managed .method public hidebysig newslot specialname virtual instance void Invoke() runtime managed } .class interface public abstract auto ansi windowsruntime WinMDPrefixing.TestInterface { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.GuidAttribute::.ctor([in] uint a, [in] ushort b, [in] ushort c, [in] byte d, [in] byte e, [in] byte f, [in] byte g, [in] byte h, [in] byte i, [in] byte j, [in] byte k) runtime managed internalcall = (3446420809, 22319, 24492, 71, 113, 62, 123, 69, 227, 199, 250) .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) } .class public sequential ansi windowsruntime sealed beforefieldinit WinMDPrefixing.TestStruct extends System.ValueType { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .field public instance int TestField }
.assembly extern mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 .assembly extern Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime .assembly extern System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a .assembly extern System.Runtime.InteropServices.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a .assembly extern System.ObjectModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a .assembly extern System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 .assembly extern System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 .assembly extern System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a .class private auto ansi <Module> { } .class private auto ansi import windowsruntime sealed beforefieldinit WinMDPrefixing.<WinRT>TestClass extends object implements WinMDPrefixing.TestInterface { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .custom public hidebysig specialname rtspecialname instance void System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() cil managed = () .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.ActivatableAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .method public hidebysig specialname rtspecialname instance void .ctor() runtime managed internalcall } .class public auto ansi sealed beforefieldinit WinMDPrefixing.TestClass extends object implements WinMDPrefixing.TestInterface { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.ActivatableAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed } .class public auto ansi windowsruntime sealed WinMDPrefixing.TestDelegate extends System.MulticastDelegate { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.GuidAttribute::.ctor([in] uint a, [in] ushort b, [in] ushort c, [in] byte d, [in] byte e, [in] byte f, [in] byte g, [in] byte h, [in] byte i, [in] byte j, [in] byte k) runtime managed internalcall = (1338053136, 62160, 23065, 93, 128, 84, 115, 135, 159, 103, 15) .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .method public hidebysig specialname rtspecialname instance void .ctor(object object, System.IntPtr method) runtime managed .method public hidebysig newslot specialname virtual instance void Invoke() runtime managed } .class interface public abstract auto ansi windowsruntime WinMDPrefixing.TestInterface { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.GuidAttribute::.ctor([in] uint a, [in] ushort b, [in] ushort c, [in] byte d, [in] byte e, [in] byte f, [in] byte g, [in] byte h, [in] byte i, [in] byte j, [in] byte k) runtime managed internalcall = (3446420809, 22319, 24492, 71, 113, 62, 123, 69, 227, 199, 250) .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) } .class public sequential ansi windowsruntime sealed beforefieldinit WinMDPrefixing.TestStruct extends System.ValueType { .custom public hidebysig specialname rtspecialname instance void Windows.Foundation.Metadata.VersionAttribute::.ctor([in] uint version) runtime managed internalcall = (0) .field public instance int TestField }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicQuickInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicQuickInfo : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicQuickInfo(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicQuickInfo)) { } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.QuickInfo)] public void QuickInfo1() { SetUpEditor(@" ''' <summary>Hello!</summary> Class Program Sub Main(ByVal args As String$$()) End Sub End Class"); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal("Class System.String\r\nRepresents text as a sequence of UTF-16 code units.To browse the .NET Framework source code for this type, see the Reference Source.", VisualStudio.Editor.GetQuickInfo()); } [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public void International() { SetUpEditor(@" ''' <summary> ''' This is an XML doc comment defined in code. ''' </summary> Class العربية123 Shared Sub Goo() Dim goo as العربية123$$ End Sub End Class"); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal(@"Class TestProj.العربية123 This is an XML doc comment defined in code.", VisualStudio.Editor.GetQuickInfo()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicQuickInfo : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicQuickInfo(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicQuickInfo)) { } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.QuickInfo)] public void QuickInfo1() { SetUpEditor(@" ''' <summary>Hello!</summary> Class Program Sub Main(ByVal args As String$$()) End Sub End Class"); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal("Class System.String\r\nRepresents text as a sequence of UTF-16 code units.To browse the .NET Framework source code for this type, see the Reference Source.", VisualStudio.Editor.GetQuickInfo()); } [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public void International() { SetUpEditor(@" ''' <summary> ''' This is an XML doc comment defined in code. ''' </summary> Class العربية123 Shared Sub Goo() Dim goo as العربية123$$ End Sub End Class"); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal(@"Class TestProj.العربية123 This is an XML doc comment defined in code.", VisualStudio.Editor.GetQuickInfo()); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/Core/Portable/CodeFixes/CodeFixContextExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeActions; namespace Microsoft.CodeAnalysis.CodeFixes { internal static class CodeFixContextExtensions { /// <summary> /// Use this helper to register multiple fixes (<paramref name="actions"/>) each of which addresses / fixes the same supplied <paramref name="diagnostic"/>. /// </summary> internal static void RegisterFixes(this CodeFixContext context, IEnumerable<CodeAction> actions, Diagnostic diagnostic) { foreach (var action in actions) { context.RegisterCodeFix(action, diagnostic); } } /// <summary> /// Use this helper to register multiple fixes (<paramref name="actions"/>) each of which addresses / fixes the same set of supplied <paramref name="diagnostics"/>. /// </summary> internal static void RegisterFixes(this CodeFixContext context, IEnumerable<CodeAction> actions, ImmutableArray<Diagnostic> diagnostics) { if (actions != null) { foreach (var action in actions) { context.RegisterCodeFix(action, 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 Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.CodeFixes { internal static class CodeFixContextExtensions { /// <summary> /// Use this helper to register multiple fixes (<paramref name="actions"/>) each of which addresses / fixes the same supplied <paramref name="diagnostic"/>. /// </summary> internal static void RegisterFixes(this CodeFixContext context, IEnumerable<CodeAction> actions, Diagnostic diagnostic) { foreach (var action in actions) { context.RegisterCodeFix(action, diagnostic); } } /// <summary> /// Use this helper to register multiple fixes (<paramref name="actions"/>) each of which addresses / fixes the same set of supplied <paramref name="diagnostics"/>. /// </summary> internal static void RegisterFixes(this CodeFixContext context, IEnumerable<CodeAction> actions, ImmutableArray<Diagnostic> diagnostics) { if (actions != null) { foreach (var action in actions) { context.RegisterCodeFix(action, diagnostics); } } } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItem.AbstractGenerateCodeItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.NavigationBar { internal abstract partial class RoslynNavigationBarItem { public abstract class AbstractGenerateCodeItem : RoslynNavigationBarItem, IEquatable<AbstractGenerateCodeItem> { public readonly SymbolKey DestinationTypeSymbolKey; protected AbstractGenerateCodeItem(RoslynNavigationBarItemKind kind, string text, Glyph glyph, SymbolKey destinationTypeSymbolKey) : base(kind, text, glyph, bolded: false, grayed: false, indent: 0, childItems: default) { DestinationTypeSymbolKey = destinationTypeSymbolKey; } public abstract override bool Equals(object? obj); public abstract override int GetHashCode(); public bool Equals(AbstractGenerateCodeItem? other) => base.Equals(other) && DestinationTypeSymbolKey.Equals(other.DestinationTypeSymbolKey); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.NavigationBar { internal abstract partial class RoslynNavigationBarItem { public abstract class AbstractGenerateCodeItem : RoslynNavigationBarItem, IEquatable<AbstractGenerateCodeItem> { public readonly SymbolKey DestinationTypeSymbolKey; protected AbstractGenerateCodeItem(RoslynNavigationBarItemKind kind, string text, Glyph glyph, SymbolKey destinationTypeSymbolKey) : base(kind, text, glyph, bolded: false, grayed: false, indent: 0, childItems: default) { DestinationTypeSymbolKey = destinationTypeSymbolKey; } public abstract override bool Equals(object? obj); public abstract override int GetHashCode(); public bool Equals(AbstractGenerateCodeItem? other) => base.Equals(other) && DestinationTypeSymbolKey.Equals(other.DestinationTypeSymbolKey); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/Portable/Compilation/GeneratedKind.cs
// Licensed to the .NET Foundation under one or more 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 { public enum GeneratedKind { /// <summary> /// It is unknown if the <see cref="SyntaxTree"/> is automatically generated. /// </summary> Unknown, /// <summary> /// The <see cref="SyntaxTree"/> is not automatically generated. /// </summary> NotGenerated, /// <summary> /// The <see cref="SyntaxTree"/> is marked as automatically generated. /// </summary> MarkedGenerated } }
// Licensed to the .NET Foundation under one or more 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 { public enum GeneratedKind { /// <summary> /// It is unknown if the <see cref="SyntaxTree"/> is automatically generated. /// </summary> Unknown, /// <summary> /// The <see cref="SyntaxTree"/> is not automatically generated. /// </summary> NotGenerated, /// <summary> /// The <see cref="SyntaxTree"/> is marked as automatically generated. /// </summary> MarkedGenerated } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Tools/ExternalAccess/OmniSharp/ImplementType/OmniSharpImplementTypeOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.ImplementType; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ImplementType { internal static class OmniSharpImplementTypeOptions { public static OmniSharpImplementTypeInsertionBehavior GetInsertionBehavior(OptionSet options, string language) => (OmniSharpImplementTypeInsertionBehavior)options.GetOption(ImplementTypeOptions.InsertionBehavior, language); public static OptionSet SetInsertionBehavior(OptionSet options, string language, OmniSharpImplementTypeInsertionBehavior value) => options.WithChangedOption(ImplementTypeOptions.InsertionBehavior, language, (ImplementTypeInsertionBehavior)value); public static OmniSharpImplementTypePropertyGenerationBehavior GetPropertyGenerationBehavior(OptionSet options, string language) => (OmniSharpImplementTypePropertyGenerationBehavior)options.GetOption(ImplementTypeOptions.PropertyGenerationBehavior, language); public static OptionSet SetPropertyGenerationBehavior(OptionSet options, string language, OmniSharpImplementTypePropertyGenerationBehavior value) => options.WithChangedOption(ImplementTypeOptions.PropertyGenerationBehavior, language, (ImplementTypePropertyGenerationBehavior)value); } internal enum OmniSharpImplementTypeInsertionBehavior { WithOtherMembersOfTheSameKind = ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, AtTheEnd = ImplementTypeInsertionBehavior.AtTheEnd, } internal enum OmniSharpImplementTypePropertyGenerationBehavior { PreferThrowingProperties = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, PreferAutoProperties = ImplementTypePropertyGenerationBehavior.PreferAutoProperties, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ImplementType { internal static class OmniSharpImplementTypeOptions { public static OmniSharpImplementTypeInsertionBehavior GetInsertionBehavior(OptionSet options, string language) => (OmniSharpImplementTypeInsertionBehavior)options.GetOption(ImplementTypeOptions.InsertionBehavior, language); public static OptionSet SetInsertionBehavior(OptionSet options, string language, OmniSharpImplementTypeInsertionBehavior value) => options.WithChangedOption(ImplementTypeOptions.InsertionBehavior, language, (ImplementTypeInsertionBehavior)value); public static OmniSharpImplementTypePropertyGenerationBehavior GetPropertyGenerationBehavior(OptionSet options, string language) => (OmniSharpImplementTypePropertyGenerationBehavior)options.GetOption(ImplementTypeOptions.PropertyGenerationBehavior, language); public static OptionSet SetPropertyGenerationBehavior(OptionSet options, string language, OmniSharpImplementTypePropertyGenerationBehavior value) => options.WithChangedOption(ImplementTypeOptions.PropertyGenerationBehavior, language, (ImplementTypePropertyGenerationBehavior)value); } internal enum OmniSharpImplementTypeInsertionBehavior { WithOtherMembersOfTheSameKind = ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, AtTheEnd = ImplementTypeInsertionBehavior.AtTheEnd, } internal enum OmniSharpImplementTypePropertyGenerationBehavior { PreferThrowingProperties = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, PreferAutoProperties = ImplementTypePropertyGenerationBehavior.PreferAutoProperties, } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IInstanceReferenceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IInstanceReferenceTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInstanceReferenceExpression_SimpleBaseReference() { string source = @" using System; public class C1 { public virtual void M1() { } } public class C2 : C1 { public override void M1() { /*<bind>*/base/*</bind>*/.M1(); } } "; string expectedOperationTree = @" IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1) (Syntax: 'base') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BaseExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInstanceReferenceExpression_BaseNoMemberReference() { string source = @" using System; public class C1 { public virtual void M1() { /*<bind>*/base/*</bind>*/.M1(); } } "; string expectedOperationTree = @" IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object) (Syntax: 'base') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0117: 'object' does not contain a definition for 'M1' // /*<bind>*/base/*</bind>*/.M1(); Diagnostic(ErrorCode.ERR_NoSuchMember, "M1").WithArguments("object", "M1").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<BaseExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IInstanceReferenceTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInstanceReferenceExpression_SimpleBaseReference() { string source = @" using System; public class C1 { public virtual void M1() { } } public class C2 : C1 { public override void M1() { /*<bind>*/base/*</bind>*/.M1(); } } "; string expectedOperationTree = @" IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1) (Syntax: 'base') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BaseExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInstanceReferenceExpression_BaseNoMemberReference() { string source = @" using System; public class C1 { public virtual void M1() { /*<bind>*/base/*</bind>*/.M1(); } } "; string expectedOperationTree = @" IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object) (Syntax: 'base') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0117: 'object' does not contain a definition for 'M1' // /*<bind>*/base/*</bind>*/.M1(); Diagnostic(ErrorCode.ERR_NoSuchMember, "M1").WithArguments("object", "M1").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<BaseExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.Fixing.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeStyle { // This part contains all the logic for hooking up the CodeFixProvider to the CodeStyleProvider. // All the code in this part is an implementation detail and is intentionally private so that // subclasses cannot change anything. All code relevant to subclasses relating to fixing is // contained in AbstractCodeStyleProvider.cs internal abstract partial class AbstractCodeStyleProvider<TOptionKind, TCodeStyleProvider> { private async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics[0]; var cancellationToken = context.CancellationToken; var codeFixes = await ComputeCodeActionsAsync( document, diagnostic, cancellationToken).ConfigureAwait(false); context.RegisterFixes(codeFixes, context.Diagnostics); } public abstract class CodeFixProvider : SyntaxEditorBasedCodeFixProvider { public readonly TCodeStyleProvider _codeStyleProvider; protected CodeFixProvider() { _codeStyleProvider = new TCodeStyleProvider(); FixableDiagnosticIds = ImmutableArray.Create(_codeStyleProvider._descriptorId); } internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) => _codeStyleProvider.RegisterCodeFixesAsync(context); protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) => _codeStyleProvider.FixAllAsync(document, diagnostics, editor, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeStyle { // This part contains all the logic for hooking up the CodeFixProvider to the CodeStyleProvider. // All the code in this part is an implementation detail and is intentionally private so that // subclasses cannot change anything. All code relevant to subclasses relating to fixing is // contained in AbstractCodeStyleProvider.cs internal abstract partial class AbstractCodeStyleProvider<TOptionKind, TCodeStyleProvider> { private async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics[0]; var cancellationToken = context.CancellationToken; var codeFixes = await ComputeCodeActionsAsync( document, diagnostic, cancellationToken).ConfigureAwait(false); context.RegisterFixes(codeFixes, context.Diagnostics); } public abstract class CodeFixProvider : SyntaxEditorBasedCodeFixProvider { public readonly TCodeStyleProvider _codeStyleProvider; protected CodeFixProvider() { _codeStyleProvider = new TCodeStyleProvider(); FixableDiagnosticIds = ImmutableArray.Create(_codeStyleProvider._descriptorId); } internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) => _codeStyleProvider.RegisterCodeFixesAsync(context); protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) => _codeStyleProvider.FixAllAsync(document, diagnostics, editor, cancellationToken); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpLambdaSyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Emit; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal class CSharpLambdaSyntaxFacts : LambdaSyntaxFacts { public static readonly LambdaSyntaxFacts Instance = new CSharpLambdaSyntaxFacts(); private CSharpLambdaSyntaxFacts() { } public override SyntaxNode GetLambda(SyntaxNode lambdaOrLambdaBodySyntax) => LambdaUtilities.GetLambda(lambdaOrLambdaBodySyntax); public override SyntaxNode? TryGetCorrespondingLambdaBody(SyntaxNode previousLambdaSyntax, SyntaxNode lambdaOrLambdaBodySyntax) => LambdaUtilities.TryGetCorrespondingLambdaBody(lambdaOrLambdaBodySyntax, previousLambdaSyntax); public override int GetDeclaratorPosition(SyntaxNode node) => LambdaUtilities.GetDeclaratorPosition(node); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal class CSharpLambdaSyntaxFacts : LambdaSyntaxFacts { public static readonly LambdaSyntaxFacts Instance = new CSharpLambdaSyntaxFacts(); private CSharpLambdaSyntaxFacts() { } public override SyntaxNode GetLambda(SyntaxNode lambdaOrLambdaBodySyntax) => LambdaUtilities.GetLambda(lambdaOrLambdaBodySyntax); public override SyntaxNode? TryGetCorrespondingLambdaBody(SyntaxNode previousLambdaSyntax, SyntaxNode lambdaOrLambdaBodySyntax) => LambdaUtilities.TryGetCorrespondingLambdaBody(lambdaOrLambdaBodySyntax, previousLambdaSyntax); public override int GetDeclaratorPosition(SyntaxNode node) => LambdaUtilities.GetDeclaratorPosition(node); } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { /// <summary> /// For the purpose of escape verification we operate with the depth of local scopes. /// The depth is a uint, with smaller number representing shallower/wider scopes. /// The 0 and 1 are special scopes - /// 0 is the "external" or "return" scope that is outside of the containing method/lambda. /// If something can escape to scope 0, it can escape to any scope in a given method or can be returned. /// 1 is the "parameter" or "top" scope that is just inside the containing method/lambda. /// If something can escape to scope 1, it can escape to any scope in a given method, but cannot be returned. /// n + 1 corresponds to scopes immediately inside a scope of depth n. /// Since sibling scopes do not intersect and a value cannot escape from one to another without /// escaping to a wider scope, we can use simple depth numbering without ambiguity. /// </summary> internal const uint ExternalScope = 0; internal const uint TopLevelScope = 1; // Some value kinds are semantically the same and the only distinction is how errors are reported // for those purposes we reserve lowest 2 bits private const int ValueKindInsignificantBits = 2; private const BindValueKind ValueKindSignificantBitsMask = unchecked((BindValueKind)~((1 << ValueKindInsignificantBits) - 1)); /// <summary> /// Expression capabilities and requirements. /// </summary> [Flags] internal enum BindValueKind : ushort { /////////////////// // All expressions can be classified according to the following 4 capabilities: // /// <summary> /// Expression can be an RHS of an assignment operation. /// </summary> /// <remarks> /// The following are rvalues: values, variables, null literals, properties /// and indexers with getters, events. /// /// The following are not rvalues: /// namespaces, types, method groups, anonymous functions. /// </remarks> RValue = 1 << ValueKindInsignificantBits, /// <summary> /// Expression can be the LHS of a simple assignment operation. /// Example: /// property with a setter /// </summary> Assignable = 2 << ValueKindInsignificantBits, /// <summary> /// Expression represents a location. Often referred as a "variable" /// Examples: /// local variable, parameter, field /// </summary> RefersToLocation = 4 << ValueKindInsignificantBits, /// <summary> /// Expression can be the LHS of a ref-assign operation. /// Example: /// ref local, ref parameter, out parameter /// </summary> RefAssignable = 8 << ValueKindInsignificantBits, /////////////////// // The rest are just combinations of the above. // /// <summary> /// Expression is the RHS of an assignment operation /// and may be a method group. /// Basically an RValue, but could be treated differently for the purpose of error reporting /// </summary> RValueOrMethodGroup = RValue + 1, /// <summary> /// Expression can be an LHS of a compound assignment /// operation (such as +=). /// </summary> CompoundAssignment = RValue | Assignable, /// <summary> /// Expression can be the operand of an increment or decrement operation. /// Same as CompoundAssignment, the distinction is really just for error reporting. /// </summary> IncrementDecrement = CompoundAssignment + 1, /// <summary> /// Expression is a r/o reference. /// </summary> ReadonlyRef = RefersToLocation | RValue, /// <summary> /// Expression can be the operand of an address-of operation (&amp;). /// Same as ReadonlyRef. The difference is just for error reporting. /// </summary> AddressOf = ReadonlyRef + 1, /// <summary> /// Expression is the receiver of a fixed buffer field access /// Same as ReadonlyRef. The difference is just for error reporting. /// </summary> FixedReceiver = ReadonlyRef + 2, /// <summary> /// Expression is passed as a ref or out parameter or assigned to a byref variable. /// </summary> RefOrOut = RefersToLocation | RValue | Assignable, /// <summary> /// Expression is returned by an ordinary r/w reference. /// Same as RefOrOut. The difference is just for error reporting. /// </summary> RefReturn = RefOrOut + 1, } private static bool RequiresRValueOnly(BindValueKind kind) { return (kind & ValueKindSignificantBitsMask) == BindValueKind.RValue; } private static bool RequiresAssignmentOnly(BindValueKind kind) { return (kind & ValueKindSignificantBitsMask) == BindValueKind.Assignable; } private static bool RequiresVariable(BindValueKind kind) { return !RequiresRValueOnly(kind); } private static bool RequiresReferenceToLocation(BindValueKind kind) { return (kind & BindValueKind.RefersToLocation) != 0; } private static bool RequiresAssignableVariable(BindValueKind kind) { return (kind & BindValueKind.Assignable) != 0; } private static bool RequiresRefAssignableVariable(BindValueKind kind) { return (kind & BindValueKind.RefAssignable) != 0; } private static bool RequiresRefOrOut(BindValueKind kind) { return (kind & BindValueKind.RefOrOut) == BindValueKind.RefOrOut; } #nullable enable private BoundIndexerAccess BindIndexerDefaultArguments(BoundIndexerAccess indexerAccess, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { var useSetAccessor = valueKind == BindValueKind.Assignable && !indexerAccess.Indexer.ReturnsByRef; var accessorForDefaultArguments = useSetAccessor ? indexerAccess.Indexer.GetOwnOrInheritedSetMethod() : indexerAccess.Indexer.GetOwnOrInheritedGetMethod(); if (accessorForDefaultArguments is not null) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(accessorForDefaultArguments.ParameterCount); argumentsBuilder.AddRange(indexerAccess.Arguments); ArrayBuilder<RefKind>? refKindsBuilderOpt; if (!indexerAccess.ArgumentRefKindsOpt.IsDefaultOrEmpty) { refKindsBuilderOpt = ArrayBuilder<RefKind>.GetInstance(accessorForDefaultArguments.ParameterCount); refKindsBuilderOpt.AddRange(indexerAccess.ArgumentRefKindsOpt); } else { refKindsBuilderOpt = null; } var argsToParams = indexerAccess.ArgsToParamsOpt; // It is possible for the indexer 'value' parameter from metadata to have a default value, but the compiler will not use it. // However, we may still use any default values from the preceding parameters. var parameters = accessorForDefaultArguments.Parameters; if (useSetAccessor) { parameters = parameters.RemoveAt(parameters.Length - 1); } BitVector defaultArguments = default; Debug.Assert(parameters.Length == indexerAccess.Indexer.Parameters.Length); // If OriginalIndexersOpt is set, there was an overload resolution failure, and we don't want to make guesses about the default // arguments that will end up being reflected in the SemanticModel/IOperation if (indexerAccess.OriginalIndexersOpt.IsDefault) { BindDefaultArguments(indexerAccess.Syntax, parameters, argumentsBuilder, refKindsBuilderOpt, ref argsToParams, out defaultArguments, indexerAccess.Expanded, enableCallerInfo: true, diagnostics); } indexerAccess = indexerAccess.Update( indexerAccess.ReceiverOpt, indexerAccess.Indexer, argumentsBuilder.ToImmutableAndFree(), indexerAccess.ArgumentNamesOpt, refKindsBuilderOpt?.ToImmutableOrNull() ?? default, indexerAccess.Expanded, argsToParams, defaultArguments, indexerAccess.Type); refKindsBuilderOpt?.Free(); } return indexerAccess; } #nullable disable /// <summary> /// Check the expression is of the required lvalue and rvalue specified by valueKind. /// The method returns the original expression if the expression is of the required /// type. Otherwise, an appropriate error is added to the diagnostics bag and the /// method returns a BoundBadExpression node. The method returns the original /// expression without generating any error if the expression has errors. /// </summary> private BoundExpression CheckValue(BoundExpression expr, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { switch (expr.Kind) { case BoundKind.PropertyGroup: expr = BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics); if (expr is BoundIndexerAccess indexerAccess) { expr = BindIndexerDefaultArguments(indexerAccess, valueKind, diagnostics); } break; case BoundKind.Local: Debug.Assert(expr.Syntax.Kind() != SyntaxKind.Argument || valueKind == BindValueKind.RefOrOut); break; case BoundKind.OutVariablePendingInference: case BoundKind.OutDeconstructVarPendingInference: Debug.Assert(valueKind == BindValueKind.RefOrOut); return expr; case BoundKind.DiscardExpression: Debug.Assert(valueKind == BindValueKind.Assignable || valueKind == BindValueKind.RefOrOut || diagnostics.DiagnosticBag is null || diagnostics.HasAnyResolvedErrors()); return expr; case BoundKind.IndexerAccess: expr = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics); break; case BoundKind.UnconvertedObjectCreationExpression: if (valueKind == BindValueKind.RValue) { return expr; } break; case BoundKind.PointerIndirectionOperator: if ((valueKind & BindValueKind.RefersToLocation) == BindValueKind.RefersToLocation) { var pointerIndirection = (BoundPointerIndirectionOperator)expr; expr = pointerIndirection.Update(pointerIndirection.Operand, refersToLocation: true, pointerIndirection.Type); } break; case BoundKind.PointerElementAccess: if ((valueKind & BindValueKind.RefersToLocation) == BindValueKind.RefersToLocation) { var elementAccess = (BoundPointerElementAccess)expr; expr = elementAccess.Update(elementAccess.Expression, elementAccess.Index, elementAccess.Checked, refersToLocation: true, elementAccess.Type); } break; } bool hasResolutionErrors = false; // If this a MethodGroup where an rvalue is not expected or where the caller will not explicitly handle // (and resolve) MethodGroups (in short, cases where valueKind != BindValueKind.RValueOrMethodGroup), // resolve the MethodGroup here to generate the appropriate errors, otherwise resolution errors (such as // "member is inaccessible") will be dropped. if (expr.Kind == BoundKind.MethodGroup && valueKind != BindValueKind.RValueOrMethodGroup) { var methodGroup = (BoundMethodGroup)expr; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); Symbol otherSymbol = null; bool resolvedToMethodGroup = resolution.MethodGroup != null; if (!expr.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading. hasResolutionErrors = resolution.HasAnyErrors; if (hasResolutionErrors) { otherSymbol = resolution.OtherSymbol; } resolution.Free(); // It's possible the method group is not a method group at all, but simply a // delayed lookup that resolved to a non-method member (perhaps an inaccessible // field or property), or nothing at all. In those cases, the member should not be exposed as a // method group, not even within a BoundBadExpression. Instead, the // BoundBadExpression simply refers to the receiver and the resolved symbol (if any). if (!resolvedToMethodGroup) { Debug.Assert(methodGroup.ResultKind != LookupResultKind.Viable); var receiver = methodGroup.ReceiverOpt; if ((object)otherSymbol != null && receiver?.Kind == BoundKind.TypeOrValueExpression) { // Since we're not accessing a method, this can't be a Color Color case, so TypeOrValueExpression should not have been used. // CAVEAT: otherSymbol could be invalid in some way (e.g. inaccessible), in which case we would have fallen back on a // method group lookup (to allow for extension methods), which would have required a TypeOrValueExpression. Debug.Assert(methodGroup.LookupError != null); // Since we have a concrete member in hand, we can resolve the receiver. var typeOrValue = (BoundTypeOrValueExpression)receiver; receiver = otherSymbol.RequiresInstanceReceiver() ? typeOrValue.Data.ValueExpression : null; // no receiver required } return new BoundBadExpression( expr.Syntax, methodGroup.ResultKind, (object)otherSymbol == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(otherSymbol), receiver == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(receiver), GetNonMethodMemberType(otherSymbol)); } } if (!hasResolutionErrors && CheckValueKind(expr.Syntax, expr, valueKind, checkingReceiver: false, diagnostics: diagnostics) || expr.HasAnyErrors && valueKind == BindValueKind.RValueOrMethodGroup) { return expr; } var resultKind = (valueKind == BindValueKind.RValue || valueKind == BindValueKind.RValueOrMethodGroup) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable; return ToBadExpression(expr, resultKind); } internal static bool IsTypeOrValueExpression(BoundExpression expression) { switch (expression?.Kind) { case BoundKind.TypeOrValueExpression: case BoundKind.QueryClause when ((BoundQueryClause)expression).Value.Kind == BoundKind.TypeOrValueExpression: return true; default: return false; } } /// <summary> /// The purpose of this method is to determine if the expression satisfies desired capabilities. /// If it is not then this code gives an appropriate error message. /// /// To determine the appropriate error message we need to know two things: /// /// (1) What capabilities we need - increment it, assign, return as a readonly reference, . . . ? /// /// (2) Are we trying to determine if the left hand side of a dot is a variable in order /// to determine if the field or property on the right hand side of a dot is assignable? /// /// (3) The syntax of the expression that started the analysis. (for error reporting purposes). /// </summary> internal bool CheckValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter()); if (expr.HasAnyErrors) { return false; } switch (expr.Kind) { // we need to handle properties and event in a special way even in an RValue case because of getters case BoundKind.PropertyAccess: case BoundKind.IndexerAccess: return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = ((BoundIndexOrRangePatternIndexerAccess)expr); if (patternIndexer.PatternSymbol.Kind == SymbolKind.Property) { // If this is an Index indexer, PatternSymbol should be a property, pointing to the // pattern indexer. If it's a Range access, it will be a method, pointing to a Slice method // and it's handled below as part of invocations. return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics); } Debug.Assert(patternIndexer.PatternSymbol.Kind == SymbolKind.Method); break; case BoundKind.EventAccess: return CheckEventValueKind((BoundEventAccess)expr, valueKind, diagnostics); } // easy out for a very common RValue case. if (RequiresRValueOnly(valueKind)) { return CheckNotNamespaceOrType(expr, diagnostics); } // constants/literals are strictly RValues // void is not even an RValue if ((expr.ConstantValue != null) || (expr.Type.GetSpecialTypeSafe() == SpecialType.System_Void)) { Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } switch (expr.Kind) { case BoundKind.NamespaceExpression: var ns = (BoundNamespaceExpression)expr; Error(diagnostics, ErrorCode.ERR_BadSKknown, node, ns.NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); return false; case BoundKind.TypeExpression: var type = (BoundTypeExpression)expr; Error(diagnostics, ErrorCode.ERR_BadSKknown, node, type.Type, MessageID.IDS_SK_TYPE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); return false; case BoundKind.Lambda: case BoundKind.UnboundLambda: // lambdas can only be used as RValues Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; case BoundKind.UnconvertedAddressOfOperator: var unconvertedAddressOf = (BoundUnconvertedAddressOfOperator)expr; Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, unconvertedAddressOf.Operand.Name, MessageID.IDS_AddressOfMethodGroup.Localize()); return false; case BoundKind.MethodGroup when valueKind == BindValueKind.AddressOf: // If the addressof operator is used not as an rvalue, that will get flagged when CheckValue // is called on the parent BoundUnconvertedAddressOf node. return true; case BoundKind.MethodGroup: // method groups can only be used as RValues except when taking the address of one var methodGroup = (BoundMethodGroup)expr; Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, methodGroup.Name, MessageID.IDS_MethodGroup.Localize()); return false; case BoundKind.RangeVariable: // range variables can only be used as RValues var queryref = (BoundRangeVariable)expr; Error(diagnostics, GetRangeLvalueError(valueKind), node, queryref.RangeVariableSymbol.Name); return false; case BoundKind.Conversion: var conversion = (BoundConversion)expr; // conversions are strict RValues, but unboxing has a specific error if (conversion.ConversionKind == ConversionKind.Unboxing) { Error(diagnostics, ErrorCode.ERR_UnboxNotLValue, node); return false; } break; // array access is readwrite variable if the indexing expression is not System.Range case BoundKind.ArrayAccess: { if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } var boundAccess = (BoundArrayAccess)expr; if (boundAccess.Indices.Length == 1 && TypeSymbol.Equals( boundAccess.Indices[0].Type, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)) { // Range indexer is an rvalue Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } return true; } // pointer dereferencing is a readwrite variable case BoundKind.PointerIndirectionOperator: // The undocumented __refvalue(tr, T) expression results in a variable of type T. case BoundKind.RefValueOperator: // dynamic expressions are readwrite, and can even be passed by ref (which is implemented via a temp) case BoundKind.DynamicMemberAccess: case BoundKind.DynamicIndexerAccess: { if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } // These are readwrite variables return true; } case BoundKind.PointerElementAccess: { if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } var receiver = ((BoundPointerElementAccess)expr).Expression; if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { return CheckValueKind(node, fieldAccess.ReceiverOpt, valueKind, checkingReceiver: true, diagnostics); } return true; } case BoundKind.Parameter: var parameter = (BoundParameter)expr; return CheckParameterValueKind(node, parameter, valueKind, checkingReceiver, diagnostics); case BoundKind.Local: var local = (BoundLocal)expr; return CheckLocalValueKind(node, local, valueKind, checkingReceiver, diagnostics); case BoundKind.ThisReference: // `this` is never ref assignable if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } // We will already have given an error for "this" used outside of a constructor, // instance method, or instance accessor. Assume that "this" is a variable if it is in a struct. // SPEC: when this is used in a primary-expression within an instance constructor of a struct, // SPEC: it is classified as a variable. // SPEC: When this is used in a primary-expression within an instance method or instance accessor // SPEC: of a struct, it is classified as a variable. // Note: RValueOnly is checked at the beginning of this method. Since we are here we need more than readable. // "this" is readonly in members marked "readonly" and in members of readonly structs, unless we are in a constructor. var isValueType = ((BoundThisReference)expr).Type.IsValueType; if (!isValueType || (RequiresAssignableVariable(valueKind) && (this.ContainingMemberOrLambda as MethodSymbol)?.IsEffectivelyReadOnly == true)) { Error(diagnostics, GetThisLvalueError(valueKind, isValueType), node, node); return false; } return true; case BoundKind.ImplicitReceiver: case BoundKind.ObjectOrCollectionValuePlaceholder: Debug.Assert(!RequiresRefAssignableVariable(valueKind)); return true; case BoundKind.Call: var call = (BoundCall)expr; return CheckCallValueKind(call, node, valueKind, checkingReceiver, diagnostics); case BoundKind.FunctionPointerInvocation: return CheckMethodReturnValueKind(((BoundFunctionPointerInvocation)expr).FunctionPointer.Signature, expr.Syntax, node, valueKind, checkingReceiver, diagnostics); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; // If we got here this should be a pattern indexer taking a Range, // meaning that the pattern symbol must be a method (either Slice or Substring) return CheckMethodReturnValueKind( (MethodSymbol)patternIndexer.PatternSymbol, patternIndexer.Syntax, node, valueKind, checkingReceiver, diagnostics); case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expr; // byref conditional defers to its operands if (conditional.IsRef && (CheckValueKind(conditional.Consequence.Syntax, conditional.Consequence, valueKind, checkingReceiver: false, diagnostics: diagnostics) & CheckValueKind(conditional.Alternative.Syntax, conditional.Alternative, valueKind, checkingReceiver: false, diagnostics: diagnostics))) { return true; } // report standard lvalue error break; case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; return CheckFieldValueKind(node, fieldAccess, valueKind, checkingReceiver, diagnostics); } case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expr; return CheckSimpleAssignmentValueKind(node, assignment, valueKind, diagnostics); } // At this point we should have covered all the possible cases for anything that is not a strict RValue. Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } private static bool CheckNotNamespaceOrType(BoundExpression expr, BindingDiagnosticBag diagnostics) { switch (expr.Kind) { case BoundKind.NamespaceExpression: Error(diagnostics, ErrorCode.ERR_BadSKknown, expr.Syntax, ((BoundNamespaceExpression)expr).NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); return false; case BoundKind.TypeExpression: Error(diagnostics, ErrorCode.ERR_BadSKunknown, expr.Syntax, expr.Type, MessageID.IDS_SK_TYPE.Localize()); return false; default: return true; } } private bool CheckLocalValueKind(SyntaxNode node, BoundLocal local, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { // Local constants are never variables. Local variables are sometimes // not to be treated as variables, if they are fixed, declared in a using, // or declared in a foreach. LocalSymbol localSymbol = local.LocalSymbol; if (RequiresAssignableVariable(valueKind)) { if (this.LockedOrDisposedVariables.Contains(localSymbol)) { diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, local.Syntax.Location, localSymbol); } // IsWritable means the variable is writable. If this is a ref variable, IsWritable // does not imply anything about the storage location if (localSymbol.RefKind == RefKind.RefReadOnly || (localSymbol.RefKind == RefKind.None && !localSymbol.IsWritableVariable)) { ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics); return false; } } else if (RequiresRefAssignableVariable(valueKind)) { if (localSymbol.RefKind == RefKind.None) { diagnostics.Add(ErrorCode.ERR_RefLocalOrParamExpected, node.Location, localSymbol); return false; } else if (!localSymbol.IsWritableVariable) { ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics); return false; } } return true; } private static bool CheckLocalRefEscape(SyntaxNode node, BoundLocal local, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) { LocalSymbol localSymbol = local.LocalSymbol; // if local symbol can escape to the same or wider/shallower scope then escapeTo // then it is all ok, otherwise it is an error. if (localSymbol.RefEscapeScope <= escapeTo) { return true; } if (escapeTo == Binder.ExternalScope) { if (localSymbol.RefKind == RefKind.None) { if (checkingReceiver) { Error(diagnostics, ErrorCode.ERR_RefReturnLocal2, local.Syntax, localSymbol); } else { Error(diagnostics, ErrorCode.ERR_RefReturnLocal, node, localSymbol); } return false; } if (checkingReceiver) { Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal2, local.Syntax, localSymbol); } else { Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal, node, localSymbol); } return false; } Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol); return false; } private bool CheckParameterValueKind(SyntaxNode node, BoundParameter parameter, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { ParameterSymbol parameterSymbol = parameter.ParameterSymbol; // all parameters can be passed by ref/out or assigned to // except "in" parameters, which are readonly if (parameterSymbol.RefKind == RefKind.In && RequiresAssignableVariable(valueKind)) { ReportReadOnlyError(parameterSymbol, node, valueKind, checkingReceiver, diagnostics); return false; } else if (parameterSymbol.RefKind == RefKind.None && RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } if (this.LockedOrDisposedVariables.Contains(parameterSymbol)) { // Consider: It would be more conventional to pass "symbol" rather than "symbol.Name". // The issue is that the error SymbolDisplayFormat doesn't display parameter // names - only their types - which works great in signatures, but not at all // at the top level. diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, parameter.Syntax.Location, parameterSymbol.Name); } return true; } private static bool CheckParameterRefEscape(SyntaxNode node, BoundParameter parameter, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) { ParameterSymbol parameterSymbol = parameter.ParameterSymbol; // byval parameters can escape to method's top level. Others can escape further. // NOTE: "method" here means nearest containing method, lambda or local function. if (escapeTo == Binder.ExternalScope && parameterSymbol.RefKind == RefKind.None) { if (checkingReceiver) { Error(diagnostics, ErrorCode.ERR_RefReturnParameter2, parameter.Syntax, parameterSymbol.Name); } else { Error(diagnostics, ErrorCode.ERR_RefReturnParameter, node, parameterSymbol.Name); } return false; } // can ref-escape to any scope otherwise return true; } private bool CheckFieldValueKind(SyntaxNode node, BoundFieldAccess fieldAccess, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { var fieldSymbol = fieldAccess.FieldSymbol; var fieldIsStatic = fieldSymbol.IsStatic; if (RequiresAssignableVariable(valueKind)) { // A field is writeable unless // (1) it is readonly and we are not in a constructor or field initializer // (2) the receiver of the field is of value type and is not a variable or object creation expression. // For example, if you have a class C with readonly field f of type S, and // S has a mutable field x, then c.f.x is not a variable because c.f is not // writable. if (fieldSymbol.IsReadOnly) { var canModifyReadonly = false; Symbol containing = this.ContainingMemberOrLambda; if ((object)containing != null && fieldIsStatic == containing.IsStatic && (fieldIsStatic || fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference) && (Compilation.FeatureStrictEnabled ? TypeSymbol.Equals(fieldSymbol.ContainingType, containing.ContainingType, TypeCompareKind.ConsiderEverything2) // We duplicate a bug in the native compiler for compatibility in non-strict mode : TypeSymbol.Equals(fieldSymbol.ContainingType.OriginalDefinition, containing.ContainingType.OriginalDefinition, TypeCompareKind.ConsiderEverything2))) { if (containing.Kind == SymbolKind.Method) { MethodSymbol containingMethod = (MethodSymbol)containing; MethodKind desiredMethodKind = fieldIsStatic ? MethodKind.StaticConstructor : MethodKind.Constructor; canModifyReadonly = (containingMethod.MethodKind == desiredMethodKind) || isAssignedFromInitOnlySetterOnThis(fieldAccess.ReceiverOpt); } else if (containing.Kind == SymbolKind.Field) { canModifyReadonly = true; } } if (!canModifyReadonly) { ReportReadOnlyFieldError(fieldSymbol, node, valueKind, checkingReceiver, diagnostics); return false; } } if (fieldSymbol.IsFixedSizeBuffer) { Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } } if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } // r/w fields that are static or belong to reference types are writeable and returnable if (fieldIsStatic || fieldSymbol.ContainingType.IsReferenceType) { return true; } // for other fields defer to the receiver. return CheckIsValidReceiverForVariable(node, fieldAccess.ReceiverOpt, valueKind, diagnostics); bool isAssignedFromInitOnlySetterOnThis(BoundExpression receiver) { // bad: other.readonlyField = ... // bad: base.readonlyField = ... if (!(receiver is BoundThisReference)) { return false; } if (!(ContainingMemberOrLambda is MethodSymbol method)) { return false; } return method.IsInitOnly; } } private bool CheckSimpleAssignmentValueKind(SyntaxNode node, BoundAssignmentOperator assignment, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { // Only ref-assigns produce LValues if (assignment.IsRef) { return CheckValueKind(node, assignment.Left, valueKind, checkingReceiver: false, diagnostics); } Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } private static bool CheckFieldRefEscape(SyntaxNode node, BoundFieldAccess fieldAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { var fieldSymbol = fieldAccess.FieldSymbol; // fields that are static or belong to reference types can ref escape anywhere if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType) { return true; } // for other fields defer to the receiver. return CheckRefEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics); } private static bool CheckFieldLikeEventRefEscape(SyntaxNode node, BoundEventAccess eventAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { var eventSymbol = eventAccess.EventSymbol; // field-like events that are static or belong to reference types can ref escape anywhere if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType) { return true; } // for other events defer to the receiver. return CheckRefEscape(node, eventAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics); } private bool CheckEventValueKind(BoundEventAccess boundEvent, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { // Compound assignment (actually "event assignment") is allowed "everywhere", subject to the restrictions of // accessibility, use site errors, and receiver variable-ness (for structs). // Other operations are allowed only for field-like events and only where the backing field is accessible // (i.e. in the declaring type) - subject to use site errors and receiver variable-ness. BoundExpression receiver = boundEvent.ReceiverOpt; SyntaxNode eventSyntax = GetEventName(boundEvent); //does not include receiver EventSymbol eventSymbol = boundEvent.EventSymbol; if (valueKind == BindValueKind.CompoundAssignment) { // NOTE: accessibility has already been checked by lookup. // NOTE: availability of well-known members is checked in BindEventAssignment because // we don't have the context to determine whether addition or subtraction is being performed. if (ReportUseSite(eventSymbol, diagnostics, eventSyntax)) { // NOTE: BindEventAssignment checks use site errors on the specific accessor // (since we don't know which is being used). return false; } Debug.Assert(!RequiresVariableReceiver(receiver, eventSymbol)); return true; } else { if (!boundEvent.IsUsableAsField) { // Dev10 reports this in addition to ERR_BadAccess, but we won't even reach this point if the event isn't accessible (caught by lookup). Error(diagnostics, GetBadEventUsageDiagnosticInfo(eventSymbol), eventSyntax); return false; } else if (ReportUseSite(eventSymbol, diagnostics, eventSyntax)) { if (!CheckIsValidReceiverForVariable(eventSyntax, receiver, BindValueKind.Assignable, diagnostics)) { return false; } } else if (RequiresVariable(valueKind)) { if (eventSymbol.IsWindowsRuntimeEvent && valueKind != BindValueKind.Assignable) { // NOTE: Dev11 reports ERR_RefProperty, as if this were a property access (since that's how it will be lowered). // Roslyn reports a new, more specific, error code. ErrorCode errorCode = valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_WinRtEventPassedByRef : GetStandardLvalueError(valueKind); Error(diagnostics, errorCode, eventSyntax, eventSymbol); return false; } else if (RequiresVariableReceiver(receiver, eventSymbol.AssociatedField) && // NOTE: using field, not event !CheckIsValidReceiverForVariable(eventSyntax, receiver, valueKind, diagnostics)) { return false; } } return true; } } private bool CheckIsValidReceiverForVariable(SyntaxNode node, BoundExpression receiver, BindValueKind kind, BindingDiagnosticBag diagnostics) { Debug.Assert(receiver != null); return Flags.Includes(BinderFlags.ObjectInitializerMember) && receiver.Kind == BoundKind.ObjectOrCollectionValuePlaceholder || CheckValueKind(node, receiver, kind, true, diagnostics); } /// <summary> /// SPEC: When a property or indexer declared in a struct-type is the target of an /// SPEC: assignment, the instance expression associated with the property or indexer /// SPEC: access must be classified as a variable. If the instance expression is /// SPEC: classified as a value, a compile-time error occurs. Because of 7.6.4, /// SPEC: the same rule also applies to fields. /// </summary> /// <remarks> /// NOTE: The spec fails to impose the restriction that the event receiver must be classified /// as a variable (unlike for properties - 7.17.1). This seems like a bug, but we have /// production code that won't build with the restriction in place (see DevDiv #15674). /// </remarks> private static bool RequiresVariableReceiver(BoundExpression receiver, Symbol symbol) { return symbol.RequiresInstanceReceiver() && symbol.Kind != SymbolKind.Event && receiver?.Type?.IsValueType == true; } private bool CheckCallValueKind(BoundCall call, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) => CheckMethodReturnValueKind(call.Method, call.Syntax, node, valueKind, checkingReceiver, diagnostics); protected bool CheckMethodReturnValueKind( MethodSymbol methodSymbol, SyntaxNode callSyntaxOpt, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { // A call can only be a variable if it returns by reference. If this is the case, // whether or not it is a valid variable depends on whether or not the call is the // RHS of a return or an assign by reference: // - If call is used in a context demanding ref-returnable reference all of its ref // inputs must be ref-returnable if (RequiresVariable(valueKind) && methodSymbol.RefKind == RefKind.None) { if (checkingReceiver) { // Error is associated with expression, not node which may be distinct. Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, callSyntaxOpt, methodSymbol); } else { Error(diagnostics, GetStandardLvalueError(valueKind), node); } return false; } if (RequiresAssignableVariable(valueKind) && methodSymbol.RefKind == RefKind.RefReadOnly) { ReportReadOnlyError(methodSymbol, node, valueKind, checkingReceiver, diagnostics); return false; } if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } return true; } private bool CheckPropertyValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { // SPEC: If the left operand is a property or indexer access, the property or indexer must // SPEC: have a set accessor. If this is not the case, a compile-time error occurs. // Addendum: Assignment is also allowed for get-only autoprops in their constructor BoundExpression receiver; SyntaxNode propertySyntax; var propertySymbol = GetPropertySymbol(expr, out receiver, out propertySyntax); Debug.Assert((object)propertySymbol != null); Debug.Assert(propertySyntax != null); if ((RequiresReferenceToLocation(valueKind) || checkingReceiver) && propertySymbol.RefKind == RefKind.None) { if (checkingReceiver) { // Error is associated with expression, not node which may be distinct. // This error is reported for all values types. That is a breaking // change from Dev10 which reports this error for struct types only, // not for type parameters constrained to "struct". Debug.Assert(propertySymbol.TypeWithAnnotations.HasType); Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, expr.Syntax, propertySymbol); } else { Error(diagnostics, valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_RefProperty : GetStandardLvalueError(valueKind), node, propertySymbol); } return false; } if (RequiresAssignableVariable(valueKind) && propertySymbol.RefKind == RefKind.RefReadOnly) { ReportReadOnlyError(propertySymbol, node, valueKind, checkingReceiver, diagnostics); return false; } var requiresSet = RequiresAssignableVariable(valueKind) && propertySymbol.RefKind == RefKind.None; if (requiresSet) { var setMethod = propertySymbol.GetOwnOrInheritedSetMethod(); if (setMethod is null) { var containing = this.ContainingMemberOrLambda; if (!AccessingAutoPropertyFromConstructor(receiver, propertySymbol, containing) && !isAllowedDespiteReadonly(receiver)) { Error(diagnostics, ErrorCode.ERR_AssgReadonlyProp, node, propertySymbol); return false; } } else { if (setMethod.IsInitOnly) { if (!isAllowedInitOnlySet(receiver)) { Error(diagnostics, ErrorCode.ERR_AssignmentInitOnly, node, propertySymbol); return false; } if (setMethod.DeclaringCompilation != this.Compilation) { // an error would have already been reported on declaring an init-only setter CheckFeatureAvailability(node, MessageID.IDS_FeatureInitOnlySetters, diagnostics); } } var accessThroughType = this.GetAccessThroughType(receiver); bool failedThroughTypeCheck; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsAccessible(setMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { if (failedThroughTypeCheck) { Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, node, propertySymbol, accessThroughType, this.ContainingType); } else { Error(diagnostics, ErrorCode.ERR_InaccessibleSetter, node, propertySymbol); } return false; } ReportDiagnosticsIfObsolete(diagnostics, setMethod, node, receiver?.Kind == BoundKind.BaseReference); var setValueKind = setMethod.IsEffectivelyReadOnly ? BindValueKind.RValue : BindValueKind.Assignable; if (RequiresVariableReceiver(receiver, setMethod) && !CheckIsValidReceiverForVariable(node, receiver, setValueKind, diagnostics)) { return false; } if (IsBadBaseAccess(node, receiver, setMethod, diagnostics, propertySymbol) || reportUseSite(setMethod)) { return false; } CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, setMethod, diagnostics); } } var requiresGet = !RequiresAssignmentOnly(valueKind) || propertySymbol.RefKind != RefKind.None; if (requiresGet) { var getMethod = propertySymbol.GetOwnOrInheritedGetMethod(); if ((object)getMethod == null) { Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, node, propertySymbol); return false; } else { var accessThroughType = this.GetAccessThroughType(receiver); bool failedThroughTypeCheck; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsAccessible(getMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { if (failedThroughTypeCheck) { Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, node, propertySymbol, accessThroughType, this.ContainingType); } else { Error(diagnostics, ErrorCode.ERR_InaccessibleGetter, node, propertySymbol); } return false; } CheckImplicitThisCopyInReadOnlyMember(receiver, getMethod, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, getMethod, node, receiver?.Kind == BoundKind.BaseReference); if (IsBadBaseAccess(node, receiver, getMethod, diagnostics, propertySymbol) || reportUseSite(getMethod)) { return false; } CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, getMethod, diagnostics); } } if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } return true; bool reportUseSite(MethodSymbol accessor) { UseSiteInfo<AssemblySymbol> useSiteInfo = accessor.GetUseSiteInfo(); if (!object.Equals(useSiteInfo.DiagnosticInfo, propertySymbol.GetUseSiteInfo().DiagnosticInfo)) { return diagnostics.Add(useSiteInfo, propertySyntax); } else { diagnostics.AddDependencies(useSiteInfo); } return false; } static bool isAllowedDespiteReadonly(BoundExpression receiver) { // ok: anonymousType with { Property = ... } if (receiver is BoundObjectOrCollectionValuePlaceholder && receiver.Type.IsAnonymousType) { return true; } return false; } bool isAllowedInitOnlySet(BoundExpression receiver) { // ok: new C() { InitOnlyProperty = ... } // bad: { ... = { InitOnlyProperty = ... } } if (receiver is BoundObjectOrCollectionValuePlaceholder placeholder) { return placeholder.IsNewInstance; } // bad: other.InitOnlyProperty = ... if (!(receiver is BoundThisReference || receiver is BoundBaseReference)) { return false; } var containingMember = ContainingMemberOrLambda; if (!(containingMember is MethodSymbol method)) { return false; } if (method.MethodKind == MethodKind.Constructor || method.IsInitOnly) { // ok: setting on `this` or `base` from an instance constructor or init-only setter return true; } return false; } } private bool IsBadBaseAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol member, BindingDiagnosticBag diagnostics, Symbol propertyOrEventSymbolOpt = null) { Debug.Assert(member.Kind != SymbolKind.Property); Debug.Assert(member.Kind != SymbolKind.Event); if (receiverOpt?.Kind == BoundKind.BaseReference && member.IsAbstract) { Error(diagnostics, ErrorCode.ERR_AbstractBaseCall, node, propertyOrEventSymbolOpt ?? member); return true; } return false; } internal static uint GetInterpolatedStringHandlerConversionEscapeScope( InterpolatedStringHandlerData data, uint scopeOfTheContainingExpression) => GetValEscape(data.Construction, scopeOfTheContainingExpression); /// <summary> /// Computes the scope to which the given invocation can escape /// NOTE: the escape scope for ref and val escapes is the same for invocations except for trivial cases (ordinary type returned by val) /// where escape is known otherwise. Therefore we do not have two ref/val variants of this. /// /// NOTE: we need scopeOfTheContainingExpression as some expressions such as optional <c>in</c> parameters or <c>ref dynamic</c> behave as /// local variables declared at the scope of the invocation. /// </summary> internal static uint GetInvocationEscapeScope( Symbol symbol, BoundExpression receiverOpt, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<BoundExpression> argsOpt, ImmutableArray<RefKind> argRefKindsOpt, ImmutableArray<int> argsToParamsOpt, uint scopeOfTheContainingExpression, bool isRefEscape ) { // SPEC: (also applies to the CheckInvocationEscape counterpart) // // An lvalue resulting from a ref-returning method invocation e1.M(e2, ...) is ref-safe - to - escape the smallest of the following scopes: //• The entire enclosing method //• the ref-safe-to-escape of all ref/out/in argument expressions(excluding the receiver) //• the safe-to - escape of all argument expressions(including the receiver) // // An rvalue resulting from a method invocation e1.M(e2, ...) is safe - to - escape from the smallest of the following scopes: //• The entire enclosing method //• the safe-to-escape of all argument expressions(including the receiver) // if (!symbol.RequiresInstanceReceiver()) { // ignore receiver when symbol is static receiverOpt = null; } //by default it is safe to escape uint escapeScope = Binder.ExternalScope; ArrayBuilder<bool> inParametersMatchedWithArgs = null; if (!argsOpt.IsDefault) { moreArguments: for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++) { var argument = argsOpt[argIndex]; if (argument.Kind == BoundKind.ArgListOperator) { Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last"); var argList = (BoundArgListOperator)argument; // unwrap varargs and process as more arguments argsOpt = argList.Arguments; // ref kinds of varargs are not interesting here. // __refvalue is not ref-returnable, so ref varargs can't come back from a call argRefKindsOpt = default; parameters = ImmutableArray<ParameterSymbol>.Empty; argsToParamsOpt = default; goto moreArguments; } RefKind effectiveRefKind = GetEffectiveRefKindAndMarkMatchedInParameter(argIndex, argRefKindsOpt, parameters, argsToParamsOpt, ref inParametersMatchedWithArgs); // ref escape scope is the narrowest of // - ref escape of all byref arguments // - val escape of all byval arguments (ref-like values can be unwrapped into refs, so treat val escape of values as possible ref escape of the result) // // val escape scope is the narrowest of // - val escape of all byval arguments (refs cannot be wrapped into values, so their ref escape is irrelevant, only use val escapes) var argEscape = effectiveRefKind != RefKind.None && isRefEscape ? GetRefEscape(argument, scopeOfTheContainingExpression) : GetValEscape(argument, scopeOfTheContainingExpression); escapeScope = Math.Max(escapeScope, argEscape); if (escapeScope >= scopeOfTheContainingExpression) { // no longer needed inParametersMatchedWithArgs?.Free(); // can't get any worse return escapeScope; } } } // handle omitted optional "in" parameters if there are any ParameterSymbol unmatchedInParameter = TryGetunmatchedInParameterAndFreeMatchedArgs(parameters, ref inParametersMatchedWithArgs); // unmatched "in" parameter is the same as a literal, its ref escape is scopeOfTheContainingExpression (can't get any worse) // its val escape is ExternalScope (does not affect overall result) if (unmatchedInParameter != null && isRefEscape) { return scopeOfTheContainingExpression; } // check receiver if ref-like if (receiverOpt?.Type?.IsRefLikeType == true) { escapeScope = Math.Max(escapeScope, GetValEscape(receiverOpt, scopeOfTheContainingExpression)); } return escapeScope; } /// <summary> /// Validates whether given invocation can allow its results to escape from <paramref name="escapeFrom"/> level to <paramref name="escapeTo"/> level. /// The result indicates whether the escape is possible. /// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure. /// /// NOTE: we need scopeOfTheContainingExpression as some expressions such as optional <c>in</c> parameters or <c>ref dynamic</c> behave as /// local variables declared at the scope of the invocation. /// </summary> private static bool CheckInvocationEscape( SyntaxNode syntax, Symbol symbol, BoundExpression receiverOpt, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<BoundExpression> argsOpt, ImmutableArray<RefKind> argRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool checkingReceiver, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics, bool isRefEscape ) { // SPEC: // In a method invocation, the following constraints apply: //• If there is a ref or out argument to a ref struct type (including the receiver), with safe-to-escape E1, then // o no ref or out argument(excluding the receiver and arguments of ref-like types) may have a narrower ref-safe-to-escape than E1; and // o no argument(including the receiver) may have a narrower safe-to-escape than E1. if (!symbol.RequiresInstanceReceiver()) { // ignore receiver when symbol is static receiverOpt = null; } ArrayBuilder<bool> inParametersMatchedWithArgs = null; if (!argsOpt.IsDefault) { moreArguments: for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++) { var argument = argsOpt[argIndex]; if (argument.Kind == BoundKind.ArgListOperator) { Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last"); var argList = (BoundArgListOperator)argument; // unwrap varargs and process as more arguments argsOpt = argList.Arguments; // ref kinds of varargs are not interesting here. // __refvalue is not ref-returnable, so ref varargs can't come back from a call argRefKindsOpt = default; parameters = ImmutableArray<ParameterSymbol>.Empty; argsToParamsOpt = default; goto moreArguments; } RefKind effectiveRefKind = GetEffectiveRefKindAndMarkMatchedInParameter(argIndex, argRefKindsOpt, parameters, argsToParamsOpt, ref inParametersMatchedWithArgs); // ref escape scope is the narrowest of // - ref escape of all byref arguments // - val escape of all byval arguments (ref-like values can be unwrapped into refs, so treat val escape of values as possible ref escape of the result) // // val escape scope is the narrowest of // - val escape of all byval arguments (refs cannot be wrapped into values, so their ref escape is irrelevant, only use val escapes) var valid = effectiveRefKind != RefKind.None && isRefEscape ? CheckRefEscape(argument.Syntax, argument, escapeFrom, escapeTo, false, diagnostics) : CheckValEscape(argument.Syntax, argument, escapeFrom, escapeTo, false, diagnostics); if (!valid) { // no longer needed inParametersMatchedWithArgs?.Free(); ErrorCode errorCode = GetStandardCallEscapeError(checkingReceiver); string parameterName; if (parameters.Length > 0) { var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex]; parameterName = parameters[paramIndex].Name; if (string.IsNullOrEmpty(parameterName)) { parameterName = paramIndex.ToString(); } } else { parameterName = "__arglist"; } Error(diagnostics, errorCode, syntax, symbol, parameterName); return false; } } } // handle omitted optional "in" parameters if there are any ParameterSymbol unmatchedInParameter = TryGetunmatchedInParameterAndFreeMatchedArgs(parameters, ref inParametersMatchedWithArgs); // unmatched "in" parameter is the same as a literal, its ref escape is scopeOfTheContainingExpression (can't get any worse) // its val escape is ExternalScope (does not affect overall result) if (unmatchedInParameter != null && isRefEscape) { var parameterName = unmatchedInParameter.Name; if (string.IsNullOrEmpty(parameterName)) { parameterName = unmatchedInParameter.Ordinal.ToString(); } Error(diagnostics, GetStandardCallEscapeError(checkingReceiver), syntax, symbol, parameterName); return false; } // check receiver if ref-like if (receiverOpt?.Type?.IsRefLikeType == true) { return CheckValEscape(receiverOpt.Syntax, receiverOpt, escapeFrom, escapeTo, false, diagnostics); } return true; } /// <summary> /// Validates whether the invocation is valid per no-mixing rules. /// Returns <see langword="false"/> when it is not valid and produces diagnostics (possibly more than one recursively) that helps to figure the reason. /// </summary> private static bool CheckInvocationArgMixing( SyntaxNode syntax, Symbol symbol, BoundExpression receiverOpt, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<BoundExpression> argsOpt, ImmutableArray<int> argsToParamsOpt, uint scopeOfTheContainingExpression, BindingDiagnosticBag diagnostics) { // SPEC: // In a method invocation, the following constraints apply: // - If there is a ref or out argument of a ref struct type (including the receiver), with safe-to-escape E1, then // - no argument (including the receiver) may have a narrower safe-to-escape than E1. if (!symbol.RequiresInstanceReceiver()) { // ignore receiver when symbol is static receiverOpt = null; } // widest possible escape via writeable ref-like receiver or ref/out argument. uint escapeTo = scopeOfTheContainingExpression; // collect all writeable ref-like arguments, including receiver var receiverType = receiverOpt?.Type; if (receiverType?.IsRefLikeType == true && !isReceiverRefReadOnly(symbol)) { escapeTo = GetValEscape(receiverOpt, scopeOfTheContainingExpression); } if (!argsOpt.IsDefault) { BoundArgListOperator argList = null; for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++) { var argument = argsOpt[argIndex]; if (argument.Kind == BoundKind.ArgListOperator) { Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last"); argList = (BoundArgListOperator)argument; break; } var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex]; if (parameters[paramIndex].RefKind.IsWritableReference() && argument.Type?.IsRefLikeType == true) { escapeTo = Math.Min(escapeTo, GetValEscape(argument, scopeOfTheContainingExpression)); } } if (argList != null) { var argListArgs = argList.Arguments; var argListRefKindsOpt = argList.ArgumentRefKindsOpt; for (var argIndex = 0; argIndex < argListArgs.Length; argIndex++) { var argument = argListArgs[argIndex]; var refKind = argListRefKindsOpt.IsDefault ? RefKind.None : argListRefKindsOpt[argIndex]; if (refKind.IsWritableReference() && argument.Type?.IsRefLikeType == true) { escapeTo = Math.Min(escapeTo, GetValEscape(argument, scopeOfTheContainingExpression)); } } } } if (escapeTo == scopeOfTheContainingExpression) { // cannot fail. common case. return true; } if (!argsOpt.IsDefault) { moreArguments: for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++) { // check val escape of all arguments var argument = argsOpt[argIndex]; if (argument.Kind == BoundKind.ArgListOperator) { Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last"); var argList = (BoundArgListOperator)argument; // unwrap varargs and process as more arguments argsOpt = argList.Arguments; parameters = ImmutableArray<ParameterSymbol>.Empty; argsToParamsOpt = default; goto moreArguments; } var valid = CheckValEscape(argument.Syntax, argument, scopeOfTheContainingExpression, escapeTo, false, diagnostics); if (!valid) { string parameterName; if (parameters.Length > 0) { var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex]; parameterName = parameters[paramIndex].Name; } else { parameterName = "__arglist"; } Error(diagnostics, ErrorCode.ERR_CallArgMixing, syntax, symbol, parameterName); return false; } } } //NB: we do not care about unmatched "in" parameters here. // They have "outer" val escape, so cannot be worse than escapeTo. // check val escape of receiver if ref-like if (receiverOpt?.Type?.IsRefLikeType == true) { return CheckValEscape(receiverOpt.Syntax, receiverOpt, scopeOfTheContainingExpression, escapeTo, false, diagnostics); } return true; static bool isReceiverRefReadOnly(Symbol methodOrPropertySymbol) => methodOrPropertySymbol switch { MethodSymbol m => m.IsEffectivelyReadOnly, // TODO: val escape checks should be skipped for property accesses when // we can determine the only accessors being called are readonly. // For now we are pessimistic and check escape if any accessor is non-readonly. // Tracking in https://github.com/dotnet/roslyn/issues/35606 PropertySymbol p => p.GetMethod?.IsEffectivelyReadOnly != false && p.SetMethod?.IsEffectivelyReadOnly != false, _ => throw ExceptionUtilities.UnexpectedValue(methodOrPropertySymbol) }; } /// <summary> /// Gets "effective" ref kind of an argument. /// If the ref kind is 'in', marks that that corresponding parameter was matched with a value /// We need that to detect when there were optional 'in' parameters for which values were not supplied. /// /// NOTE: Generally we know if a formal argument is passed as ref/out/in by looking at the call site. /// However, 'in' may also be passed as an ordinary val argument so we need to take a look at corresponding parameter, if such exists. /// There are cases like params/vararg, when a corresponding parameter may not exist, then val cannot become 'in'. /// </summary> private static RefKind GetEffectiveRefKindAndMarkMatchedInParameter( int argIndex, ImmutableArray<RefKind> argRefKindsOpt, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt, ref ArrayBuilder<bool> inParametersMatchedWithArgs) { var effectiveRefKind = argRefKindsOpt.IsDefault ? RefKind.None : argRefKindsOpt[argIndex]; if ((effectiveRefKind == RefKind.None || effectiveRefKind == RefKind.In) && argIndex < parameters.Length) { var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex]; if (parameters[paramIndex].RefKind == RefKind.In) { effectiveRefKind = RefKind.In; inParametersMatchedWithArgs = inParametersMatchedWithArgs ?? ArrayBuilder<bool>.GetInstance(parameters.Length, fillWithValue: false); inParametersMatchedWithArgs[paramIndex] = true; } } return effectiveRefKind; } /// <summary> /// Gets a "in" parameter for which there is no argument supplied, if such exists. /// That indicates an optional "in" parameter. We treat it as an RValue passed by reference via a temporary. /// The effective scope of such variable is the immediately containing scope. /// </summary> private static ParameterSymbol TryGetunmatchedInParameterAndFreeMatchedArgs(ImmutableArray<ParameterSymbol> parameters, ref ArrayBuilder<bool> inParametersMatchedWithArgs) { try { if (!parameters.IsDefault) { for (int i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; if (parameter.IsParams) { break; } if (parameter.RefKind == RefKind.In && inParametersMatchedWithArgs?[i] != true && parameter.Type.IsRefLikeType == false) { return parameter; } } } return null; } finally { inParametersMatchedWithArgs?.Free(); // make sure noone uses it after. inParametersMatchedWithArgs = null; } } private static ErrorCode GetStandardCallEscapeError(bool checkingReceiver) { return checkingReceiver ? ErrorCode.ERR_EscapeCall2 : ErrorCode.ERR_EscapeCall; } private static void ReportReadonlyLocalError(SyntaxNode node, LocalSymbol local, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert((object)local != null); Debug.Assert(kind != BindValueKind.RValue); MessageID cause; if (local.IsForEach) { cause = MessageID.IDS_FOREACHLOCAL; } else if (local.IsUsing) { cause = MessageID.IDS_USINGLOCAL; } else if (local.IsFixed) { cause = MessageID.IDS_FIXEDLOCAL; } else { Error(diagnostics, GetStandardLvalueError(kind), node); return; } ErrorCode[] ReadOnlyLocalErrors = { ErrorCode.ERR_RefReadonlyLocalCause, ErrorCode.ERR_AssgReadonlyLocalCause, ErrorCode.ERR_RefReadonlyLocal2Cause, ErrorCode.ERR_AssgReadonlyLocal2Cause }; int index = (checkingReceiver ? 2 : 0) + (RequiresRefOrOut(kind) ? 0 : 1); Error(diagnostics, ReadOnlyLocalErrors[index], node, local, cause.Localize()); } private static ErrorCode GetThisLvalueError(BindValueKind kind, bool isValueType) { switch (kind) { case BindValueKind.CompoundAssignment: case BindValueKind.Assignable: return ErrorCode.ERR_AssgReadonlyLocal; case BindValueKind.RefOrOut: return ErrorCode.ERR_RefReadonlyLocal; case BindValueKind.AddressOf: return ErrorCode.ERR_InvalidAddrOp; case BindValueKind.IncrementDecrement: return isValueType ? ErrorCode.ERR_AssgReadonlyLocal : ErrorCode.ERR_IncrementLvalueExpected; case BindValueKind.RefReturn: case BindValueKind.ReadonlyRef: return ErrorCode.ERR_RefReturnThis; case BindValueKind.RefAssignable: return ErrorCode.ERR_RefLocalOrParamExpected; } if (RequiresReferenceToLocation(kind)) { return ErrorCode.ERR_RefLvalueExpected; } throw ExceptionUtilities.UnexpectedValue(kind); } private static ErrorCode GetRangeLvalueError(BindValueKind kind) { switch (kind) { case BindValueKind.Assignable: case BindValueKind.CompoundAssignment: case BindValueKind.IncrementDecrement: return ErrorCode.ERR_QueryRangeVariableReadOnly; case BindValueKind.AddressOf: return ErrorCode.ERR_InvalidAddrOp; case BindValueKind.RefReturn: case BindValueKind.ReadonlyRef: return ErrorCode.ERR_RefReturnRangeVariable; case BindValueKind.RefAssignable: return ErrorCode.ERR_RefLocalOrParamExpected; } if (RequiresReferenceToLocation(kind)) { return ErrorCode.ERR_QueryOutRefRangeVariable; } throw ExceptionUtilities.UnexpectedValue(kind); } private static ErrorCode GetMethodGroupOrFunctionPointerLvalueError(BindValueKind valueKind) { if (RequiresReferenceToLocation(valueKind)) { return ErrorCode.ERR_RefReadonlyLocalCause; } // Cannot assign to 'W' because it is a 'method group' return ErrorCode.ERR_AssgReadonlyLocalCause; } private static ErrorCode GetStandardLvalueError(BindValueKind kind) { switch (kind) { case BindValueKind.CompoundAssignment: case BindValueKind.Assignable: return ErrorCode.ERR_AssgLvalueExpected; case BindValueKind.AddressOf: return ErrorCode.ERR_InvalidAddrOp; case BindValueKind.IncrementDecrement: return ErrorCode.ERR_IncrementLvalueExpected; case BindValueKind.FixedReceiver: return ErrorCode.ERR_FixedNeedsLvalue; case BindValueKind.RefReturn: case BindValueKind.ReadonlyRef: return ErrorCode.ERR_RefReturnLvalueExpected; case BindValueKind.RefAssignable: return ErrorCode.ERR_RefLocalOrParamExpected; } if (RequiresReferenceToLocation(kind)) { return ErrorCode.ERR_RefLvalueExpected; } throw ExceptionUtilities.UnexpectedValue(kind); } private static ErrorCode GetStandardRValueRefEscapeError(uint escapeTo) { if (escapeTo == Binder.ExternalScope) { return ErrorCode.ERR_RefReturnLvalueExpected; } return ErrorCode.ERR_EscapeOther; } private static void ReportReadOnlyFieldError(FieldSymbol field, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert((object)field != null); Debug.Assert(RequiresAssignableVariable(kind)); Debug.Assert(field.Type != (object)null); // It's clearer to say that the address can't be taken than to say that the field can't be modified // (even though the latter message gives more explanation of why). if (kind == BindValueKind.AddressOf) { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, node); return; } ErrorCode[] ReadOnlyErrors = { ErrorCode.ERR_RefReturnReadonly, ErrorCode.ERR_RefReadonly, ErrorCode.ERR_AssgReadonly, ErrorCode.ERR_RefReturnReadonlyStatic, ErrorCode.ERR_RefReadonlyStatic, ErrorCode.ERR_AssgReadonlyStatic, ErrorCode.ERR_RefReturnReadonly2, ErrorCode.ERR_RefReadonly2, ErrorCode.ERR_AssgReadonly2, ErrorCode.ERR_RefReturnReadonlyStatic2, ErrorCode.ERR_RefReadonlyStatic2, ErrorCode.ERR_AssgReadonlyStatic2 }; int index = (checkingReceiver ? 6 : 0) + (field.IsStatic ? 3 : 0) + (kind == BindValueKind.RefReturn ? 0 : (RequiresRefOrOut(kind) ? 1 : 2)); if (checkingReceiver) { Error(diagnostics, ReadOnlyErrors[index], node, field); } else { Error(diagnostics, ReadOnlyErrors[index], node); } } private static void ReportReadOnlyError(Symbol symbol, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert((object)symbol != null); Debug.Assert(RequiresAssignableVariable(kind)); // It's clearer to say that the address can't be taken than to say that the parameter can't be modified // (even though the latter message gives more explanation of why). if (kind == BindValueKind.AddressOf) { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, node); return; } var symbolKind = symbol.Kind.Localize(); ErrorCode[] ReadOnlyErrors = { ErrorCode.ERR_RefReturnReadonlyNotField, ErrorCode.ERR_RefReadonlyNotField, ErrorCode.ERR_AssignReadonlyNotField, ErrorCode.ERR_RefReturnReadonlyNotField2, ErrorCode.ERR_RefReadonlyNotField2, ErrorCode.ERR_AssignReadonlyNotField2, }; int index = (checkingReceiver ? 3 : 0) + (kind == BindValueKind.RefReturn ? 0 : (RequiresRefOrOut(kind) ? 1 : 2)); Error(diagnostics, ReadOnlyErrors[index], node, symbolKind, symbol); } /// <summary> /// Checks whether given expression can escape from the current scope to the <paramref name="escapeTo"/> /// In a case if it cannot a bad expression is returned and diagnostics is produced. /// </summary> internal BoundExpression ValidateEscape(BoundExpression expr, uint escapeTo, bool isByRef, BindingDiagnosticBag diagnostics) { if (isByRef) { if (CheckRefEscape(expr.Syntax, expr, this.LocalScopeDepth, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return expr; } } else { if (CheckValEscape(expr.Syntax, expr, this.LocalScopeDepth, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return expr; } } return ToBadExpression(expr); } /// <summary> /// Computes the widest scope depth to which the given expression can escape by reference. /// /// NOTE: in a case if expression cannot be passed by an alias (RValue and similar), the ref-escape is scopeOfTheContainingExpression /// There are few cases where RValues are permitted to be passed by reference which implies that a temporary local proxy is passed instead. /// We reflect such behavior by constraining the escape value to the narrowest scope possible. /// </summary> internal static uint GetRefEscape(BoundExpression expr, uint scopeOfTheContainingExpression) { // cannot infer anything from errors if (expr.HasAnyErrors) { return Binder.ExternalScope; } // cannot infer anything from Void (broken code) if (expr.Type?.GetSpecialTypeSafe() == SpecialType.System_Void) { return Binder.ExternalScope; } // constants/literals cannot ref-escape current scope if (expr.ConstantValue != null) { return scopeOfTheContainingExpression; } // cover case that cannot refer to local state // otherwise default to current scope (RValues, etc) switch (expr.Kind) { case BoundKind.ArrayAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: // array elements and pointer dereferencing are readwrite variables return Binder.ExternalScope; case BoundKind.RefValueOperator: // The undocumented __refvalue(tr, T) expression results in an lvalue of type T. // for compat reasons it is not ref-returnable (since TypedReference is not val-returnable) // it can, however, ref-escape to any other level (since TypedReference can val-escape to any other level) return Binder.TopLevelScope; case BoundKind.DiscardExpression: // same as write-only byval local break; case BoundKind.DynamicMemberAccess: case BoundKind.DynamicIndexerAccess: // dynamic expressions can be read and written to // can even be passed by reference (which is implemented via a temp) // it is not valid to escape them by reference though, so treat them as RValues here break; case BoundKind.Parameter: var parameter = ((BoundParameter)expr).ParameterSymbol; // byval parameters can escape to method's top level. Others can escape further. // NOTE: "method" here means nearest containing method, lambda or local function. return parameter.RefKind == RefKind.None ? Binder.TopLevelScope : Binder.ExternalScope; case BoundKind.Local: return ((BoundLocal)expr).LocalSymbol.RefEscapeScope; case BoundKind.ThisReference: var thisref = (BoundThisReference)expr; // "this" is an RValue, unless in a struct. if (!thisref.Type.IsValueType) { break; } //"this" is not returnable by reference in a struct. // can ref escape to any other level return Binder.TopLevelScope; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expr; if (conditional.IsRef) { // ref conditional defers to its operands return Math.Max(GetRefEscape(conditional.Consequence, scopeOfTheContainingExpression), GetRefEscape(conditional.Alternative, scopeOfTheContainingExpression)); } // otherwise it is an RValue break; case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; // fields that are static or belong to reference types can ref escape anywhere if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType) { return Binder.ExternalScope; } // for other fields defer to the receiver. return GetRefEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression); case BoundKind.EventAccess: var eventAccess = (BoundEventAccess)expr; if (!eventAccess.IsUsableAsField) { // not field-like events are RValues break; } var eventSymbol = eventAccess.EventSymbol; // field-like events that are static or belong to reference types can ref escape anywhere if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType) { return Binder.ExternalScope; } // for other events defer to the receiver. return GetRefEscape(eventAccess.ReceiverOpt, scopeOfTheContainingExpression); case BoundKind.Call: var call = (BoundCall)expr; var methodSymbol = call.Method; if (methodSymbol.RefKind == RefKind.None) { break; } return GetInvocationEscapeScope( call.Method, call.ReceiverOpt, methodSymbol.Parameters, call.Arguments, call.ArgumentRefKindsOpt, call.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: true); case BoundKind.FunctionPointerInvocation: var ptrInvocation = (BoundFunctionPointerInvocation)expr; methodSymbol = ptrInvocation.FunctionPointer.Signature; if (methodSymbol.RefKind == RefKind.None) { break; } return GetInvocationEscapeScope( methodSymbol, receiverOpt: null, methodSymbol.Parameters, ptrInvocation.Arguments, ptrInvocation.ArgumentRefKindsOpt, argsToParamsOpt: default, scopeOfTheContainingExpression, isRefEscape: true); case BoundKind.IndexerAccess: var indexerAccess = (BoundIndexerAccess)expr; var indexerSymbol = indexerAccess.Indexer; return GetInvocationEscapeScope( indexerSymbol, indexerAccess.ReceiverOpt, indexerSymbol.Parameters, indexerAccess.Arguments, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: true); case BoundKind.PropertyAccess: var propertyAccess = (BoundPropertyAccess)expr; // not passing any arguments/parameters return GetInvocationEscapeScope( propertyAccess.PropertySymbol, propertyAccess.ReceiverOpt, default, default, default, default, scopeOfTheContainingExpression, isRefEscape: true); case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expr; if (!assignment.IsRef) { // non-ref assignments are RValues break; } return GetRefEscape(assignment.Left, scopeOfTheContainingExpression); } // At this point we should have covered all the possible cases for anything that is not a strict RValue. return scopeOfTheContainingExpression; } /// <summary> /// A counterpart to the GetRefEscape, which validates if given escape demand can be met by the expression. /// The result indicates whether the escape is possible. /// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure. /// </summary> internal static bool CheckRefEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter()); if (escapeTo >= escapeFrom) { // escaping to same or narrower scope is ok. return true; } if (expr.HasAnyErrors) { // already an error return true; } // void references cannot escape (error should be reported somewhere) if (expr.Type?.GetSpecialTypeSafe() == SpecialType.System_Void) { return true; } // references to constants/literals cannot escape higher. if (expr.ConstantValue != null) { Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), node); return false; } switch (expr.Kind) { case BoundKind.ArrayAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: // array elements and pointer dereferencing are readwrite variables return true; case BoundKind.RefValueOperator: // The undocumented __refvalue(tr, T) expression results in an lvalue of type T. // for compat reasons it is not ref-returnable (since TypedReference is not val-returnable) if (escapeTo == Binder.ExternalScope) { break; } // it can, however, ref-escape to any other level (since TypedReference can val-escape to any other level) return true; case BoundKind.DiscardExpression: // same as write-only byval local break; case BoundKind.DynamicMemberAccess: case BoundKind.DynamicIndexerAccess: // dynamic expressions can be read and written to // can even be passed by reference (which is implemented via a temp) // it is not valid to escape them by reference though. break; case BoundKind.Parameter: var parameter = (BoundParameter)expr; return CheckParameterRefEscape(node, parameter, escapeTo, checkingReceiver, diagnostics); case BoundKind.Local: var local = (BoundLocal)expr; return CheckLocalRefEscape(node, local, escapeTo, checkingReceiver, diagnostics); case BoundKind.ThisReference: var thisref = (BoundThisReference)expr; // "this" is an RValue, unless in a struct. if (!thisref.Type.IsValueType) { break; } //"this" is not returnable by reference in a struct. if (escapeTo == Binder.ExternalScope) { Error(diagnostics, ErrorCode.ERR_RefReturnStructThis, node, ThisParameterSymbol.SymbolName); return false; } // can ref escape to any other level return true; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expr; if (conditional.IsRef) { return CheckRefEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckRefEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); } // report standard lvalue error break; case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; return CheckFieldRefEscape(node, fieldAccess, escapeFrom, escapeTo, diagnostics); case BoundKind.EventAccess: var eventAccess = (BoundEventAccess)expr; if (!eventAccess.IsUsableAsField) { // not field-like events are RValues break; } return CheckFieldLikeEventRefEscape(node, eventAccess, escapeFrom, escapeTo, diagnostics); case BoundKind.Call: var call = (BoundCall)expr; var methodSymbol = call.Method; if (methodSymbol.RefKind == RefKind.None) { break; } return CheckInvocationEscape( call.Syntax, methodSymbol, call.ReceiverOpt, methodSymbol.Parameters, call.Arguments, call.ArgumentRefKindsOpt, call.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.IndexerAccess: var indexerAccess = (BoundIndexerAccess)expr; var indexerSymbol = indexerAccess.Indexer; if (indexerSymbol.RefKind == RefKind.None) { break; } return CheckInvocationEscape( indexerAccess.Syntax, indexerSymbol, indexerAccess.ReceiverOpt, indexerSymbol.Parameters, indexerAccess.Arguments, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; RefKind refKind; ImmutableArray<ParameterSymbol> parameters; switch (patternIndexer.PatternSymbol) { case PropertySymbol p: refKind = p.RefKind; parameters = p.Parameters; break; case MethodSymbol m: refKind = m.RefKind; parameters = m.Parameters; break; default: throw ExceptionUtilities.Unreachable; } if (refKind == RefKind.None) { break; } return CheckInvocationEscape( patternIndexer.Syntax, patternIndexer.PatternSymbol, patternIndexer.Receiver, parameters, ImmutableArray.Create<BoundExpression>(patternIndexer.Argument), default, default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.FunctionPointerInvocation: var functionPointerInvocation = (BoundFunctionPointerInvocation)expr; FunctionPointerMethodSymbol signature = functionPointerInvocation.FunctionPointer.Signature; if (signature.RefKind == RefKind.None) { break; } return CheckInvocationEscape( functionPointerInvocation.Syntax, signature, functionPointerInvocation.InvokedExpression, signature.Parameters, functionPointerInvocation.Arguments, functionPointerInvocation.ArgumentRefKindsOpt, argsToParamsOpt: default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.PropertyAccess: var propertyAccess = (BoundPropertyAccess)expr; var propertySymbol = propertyAccess.PropertySymbol; if (propertySymbol.RefKind == RefKind.None) { break; } // not passing any arguments/parameters return CheckInvocationEscape( propertyAccess.Syntax, propertySymbol, propertyAccess.ReceiverOpt, default, default, default, default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expr; // Only ref-assignments can be LValues if (!assignment.IsRef) { break; } return CheckRefEscape( node, assignment.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); } // At this point we should have covered all the possible cases for anything that is not a strict RValue. Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), node); return false; } internal static uint GetBroadestValEscape(BoundTupleExpression expr, uint scopeOfTheContainingExpression) { uint broadest = scopeOfTheContainingExpression; foreach (var element in expr.Arguments) { uint valEscape; if (element is BoundTupleExpression te) { valEscape = GetBroadestValEscape(te, scopeOfTheContainingExpression); } else { valEscape = GetValEscape(element, scopeOfTheContainingExpression); } broadest = Math.Min(broadest, valEscape); } return broadest; } /// <summary> /// Computes the widest scope depth to which the given expression can escape by value. /// /// NOTE: unless the type of expression is ref-like, the result is Binder.ExternalScope since ordinary values can always be returned from methods. /// </summary> internal static uint GetValEscape(BoundExpression expr, uint scopeOfTheContainingExpression) { // cannot infer anything from errors if (expr.HasAnyErrors) { return Binder.ExternalScope; } // constants/literals cannot refer to local state if (expr.ConstantValue != null) { return Binder.ExternalScope; } // to have local-referring values an expression must have a ref-like type if (expr.Type?.IsRefLikeType != true) { return Binder.ExternalScope; } // cover case that can refer to local state // otherwise default to ExternalScope (ordinary values) switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Parameter: case BoundKind.ThisReference: // always returnable return Binder.ExternalScope; case BoundKind.FromEndIndexExpression: // We are going to call a constructor that takes an integer and a bool. Cannot leak any references through them. // always returnable return Binder.ExternalScope; case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: var tupleLiteral = (BoundTupleExpression)expr; return GetTupleValEscape(tupleLiteral.Arguments, scopeOfTheContainingExpression); case BoundKind.MakeRefOperator: case BoundKind.RefValueOperator: // for compat reasons // NB: it also means can`t assign stackalloc spans to a __refvalue // we are ok with that. return Binder.ExternalScope; case BoundKind.DiscardExpression: return ((BoundDiscardExpression)expr).ValEscape; case BoundKind.DeconstructValuePlaceholder: return ((BoundDeconstructValuePlaceholder)expr).ValEscape; case BoundKind.Local: return ((BoundLocal)expr).LocalSymbol.ValEscapeScope; case BoundKind.StackAllocArrayCreation: case BoundKind.ConvertedStackAllocExpression: return Binder.TopLevelScope; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expr; var consEscape = GetValEscape(conditional.Consequence, scopeOfTheContainingExpression); if (conditional.IsRef) { // ref conditional defers to one operand. // the other one is the same or we will be reporting errors anyways. return consEscape; } // val conditional gets narrowest of its operands return Math.Max(consEscape, GetValEscape(conditional.Alternative, scopeOfTheContainingExpression)); case BoundKind.NullCoalescingOperator: var coalescingOp = (BoundNullCoalescingOperator)expr; return Math.Max(GetValEscape(coalescingOp.LeftOperand, scopeOfTheContainingExpression), GetValEscape(coalescingOp.RightOperand, scopeOfTheContainingExpression)); case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType) { // Already an error state. return Binder.ExternalScope; } // for ref-like fields defer to the receiver. return GetValEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression); case BoundKind.Call: var call = (BoundCall)expr; return GetInvocationEscapeScope( call.Method, call.ReceiverOpt, call.Method.Parameters, call.Arguments, call.ArgumentRefKindsOpt, call.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.FunctionPointerInvocation: var ptrInvocation = (BoundFunctionPointerInvocation)expr; var ptrSymbol = ptrInvocation.FunctionPointer.Signature; return GetInvocationEscapeScope( ptrSymbol, receiverOpt: null, ptrSymbol.Parameters, ptrInvocation.Arguments, ptrInvocation.ArgumentRefKindsOpt, argsToParamsOpt: default, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.IndexerAccess: var indexerAccess = (BoundIndexerAccess)expr; var indexerSymbol = indexerAccess.Indexer; return GetInvocationEscapeScope( indexerSymbol, indexerAccess.ReceiverOpt, indexerSymbol.Parameters, indexerAccess.Arguments, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; var parameters = patternIndexer.PatternSymbol switch { PropertySymbol p => p.Parameters, MethodSymbol m => m.Parameters, _ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol) }; return GetInvocationEscapeScope( patternIndexer.PatternSymbol, patternIndexer.Receiver, parameters, default, default, default, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.PropertyAccess: var propertyAccess = (BoundPropertyAccess)expr; // not passing any arguments/parameters return GetInvocationEscapeScope( propertyAccess.PropertySymbol, propertyAccess.ReceiverOpt, default, default, default, default, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.ObjectCreationExpression: var objectCreation = (BoundObjectCreationExpression)expr; var constructorSymbol = objectCreation.Constructor; var escape = GetInvocationEscapeScope( constructorSymbol, null, constructorSymbol.Parameters, objectCreation.Arguments, objectCreation.ArgumentRefKindsOpt, objectCreation.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); var initializerOpt = objectCreation.InitializerExpressionOpt; if (initializerOpt != null) { escape = Math.Max(escape, GetValEscape(initializerOpt, scopeOfTheContainingExpression)); } return escape; case BoundKind.WithExpression: var withExpression = (BoundWithExpression)expr; return Math.Max(GetValEscape(withExpression.Receiver, scopeOfTheContainingExpression), GetValEscape(withExpression.InitializerExpression, scopeOfTheContainingExpression)); case BoundKind.UnaryOperator: return GetValEscape(((BoundUnaryOperator)expr).Operand, scopeOfTheContainingExpression); case BoundKind.Conversion: var conversion = (BoundConversion)expr; Debug.Assert(conversion.ConversionKind != ConversionKind.StackAllocToSpanType, "StackAllocToSpanType unexpected"); if (conversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { var data = conversion.Operand switch { BoundInterpolatedString { InterpolationData: { } d } => d, BoundBinaryOperator { InterpolatedStringHandlerData: { } d } => d, _ => throw ExceptionUtilities.UnexpectedValue(conversion.Operand.Kind) }; return GetInterpolatedStringHandlerConversionEscapeScope(data, scopeOfTheContainingExpression); } return GetValEscape(conversion.Operand, scopeOfTheContainingExpression); case BoundKind.AssignmentOperator: return GetValEscape(((BoundAssignmentOperator)expr).Right, scopeOfTheContainingExpression); case BoundKind.IncrementOperator: return GetValEscape(((BoundIncrementOperator)expr).Operand, scopeOfTheContainingExpression); case BoundKind.CompoundAssignmentOperator: var compound = (BoundCompoundAssignmentOperator)expr; return Math.Max(GetValEscape(compound.Left, scopeOfTheContainingExpression), GetValEscape(compound.Right, scopeOfTheContainingExpression)); case BoundKind.BinaryOperator: var binary = (BoundBinaryOperator)expr; return Math.Max(GetValEscape(binary.Left, scopeOfTheContainingExpression), GetValEscape(binary.Right, scopeOfTheContainingExpression)); case BoundKind.RangeExpression: var range = (BoundRangeExpression)expr; return Math.Max((range.LeftOperandOpt is { } left ? GetValEscape(left, scopeOfTheContainingExpression) : Binder.ExternalScope), (range.RightOperandOpt is { } right ? GetValEscape(right, scopeOfTheContainingExpression) : Binder.ExternalScope)); case BoundKind.UserDefinedConditionalLogicalOperator: var uo = (BoundUserDefinedConditionalLogicalOperator)expr; return Math.Max(GetValEscape(uo.Left, scopeOfTheContainingExpression), GetValEscape(uo.Right, scopeOfTheContainingExpression)); case BoundKind.QueryClause: return GetValEscape(((BoundQueryClause)expr).Value, scopeOfTheContainingExpression); case BoundKind.RangeVariable: return GetValEscape(((BoundRangeVariable)expr).Value, scopeOfTheContainingExpression); case BoundKind.ObjectInitializerExpression: var initExpr = (BoundObjectInitializerExpression)expr; return GetValEscapeOfObjectInitializer(initExpr, scopeOfTheContainingExpression); case BoundKind.CollectionInitializerExpression: var colExpr = (BoundCollectionInitializerExpression)expr; return GetValEscape(colExpr.Initializers, scopeOfTheContainingExpression); case BoundKind.CollectionElementInitializer: var colElement = (BoundCollectionElementInitializer)expr; return GetValEscape(colElement.Arguments, scopeOfTheContainingExpression); case BoundKind.ObjectInitializerMember: // this node generally makes no sense outside of the context of containing initializer // however binder uses it as a placeholder when binding assignments inside an object initializer // just say it does not escape anywhere, so that we do not get false errors. return scopeOfTheContainingExpression; case BoundKind.ImplicitReceiver: case BoundKind.ObjectOrCollectionValuePlaceholder: // binder uses this as a placeholder when binding members inside an object initializer // just say it does not escape anywhere, so that we do not get false errors. return scopeOfTheContainingExpression; case BoundKind.InterpolatedStringHandlerPlaceholder: // The handler placeholder cannot escape out of the current expression, as it's a compiler-synthesized // location. return scopeOfTheContainingExpression; case BoundKind.InterpolatedStringArgumentPlaceholder: // We saved off the safe-to-escape of the argument when we did binding return ((BoundInterpolatedStringArgumentPlaceholder)expr).ValSafeToEscape; case BoundKind.DisposableValuePlaceholder: // Disposable value placeholder is only ever used to lookup a pattern dispose method // then immediately discarded. The actual expression will be generated during lowering return scopeOfTheContainingExpression; case BoundKind.AwaitableValuePlaceholder: return ((BoundAwaitableValuePlaceholder)expr).ValEscape; case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: // Unsafe code will always be allowed to escape. return Binder.ExternalScope; case BoundKind.AsOperator: case BoundKind.AwaitExpression: case BoundKind.ConditionalAccess: case BoundKind.ArrayAccess: // only possible in error cases (if possible at all) return scopeOfTheContainingExpression; case BoundKind.ConvertedSwitchExpression: case BoundKind.UnconvertedSwitchExpression: var switchExpr = (BoundSwitchExpression)expr; return GetValEscape(switchExpr.SwitchArms.SelectAsArray(a => a.Value), scopeOfTheContainingExpression); default: // in error situations some unexpected nodes could make here // returning "scopeOfTheContainingExpression" seems safer than throwing. // we will still assert to make sure that all nodes are accounted for. Debug.Assert(false, $"{expr.Kind} expression of {expr.Type} type"); return scopeOfTheContainingExpression; } } private static uint GetTupleValEscape(ImmutableArray<BoundExpression> elements, uint scopeOfTheContainingExpression) { uint narrowestScope = scopeOfTheContainingExpression; foreach (var element in elements) { narrowestScope = Math.Max(narrowestScope, GetValEscape(element, scopeOfTheContainingExpression)); } return narrowestScope; } private static uint GetValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint scopeOfTheContainingExpression) { var result = Binder.ExternalScope; foreach (var expression in initExpr.Initializers) { if (expression.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expression; result = Math.Max(result, GetValEscape(assignment.Right, scopeOfTheContainingExpression)); var left = (BoundObjectInitializerMember)assignment.Left; result = Math.Max(result, GetValEscape(left.Arguments, scopeOfTheContainingExpression)); } else { result = Math.Max(result, GetValEscape(expression, scopeOfTheContainingExpression)); } } return result; } private static uint GetValEscape(ImmutableArray<BoundExpression> expressions, uint scopeOfTheContainingExpression) { var result = Binder.ExternalScope; foreach (var expression in expressions) { result = Math.Max(result, GetValEscape(expression, scopeOfTheContainingExpression)); } return result; } /// <summary> /// A counterpart to the GetValEscape, which validates if given escape demand can be met by the expression. /// The result indicates whether the escape is possible. /// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure. /// </summary> internal static bool CheckValEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter()); if (escapeTo >= escapeFrom) { // escaping to same or narrower scope is ok. return true; } // cannot infer anything from errors if (expr.HasAnyErrors) { return true; } // constants/literals cannot refer to local state if (expr.ConstantValue != null) { return true; } // to have local-referring values an expression must have a ref-like type if (expr.Type?.IsRefLikeType != true) { return true; } switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Parameter: case BoundKind.ThisReference: // always returnable return true; case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: var tupleLiteral = (BoundTupleExpression)expr; return CheckTupleValEscape(tupleLiteral.Arguments, escapeFrom, escapeTo, diagnostics); case BoundKind.MakeRefOperator: case BoundKind.RefValueOperator: // for compat reasons return true; case BoundKind.DiscardExpression: // same as uninitialized local return true; case BoundKind.DeconstructValuePlaceholder: if (((BoundDeconstructValuePlaceholder)expr).ValEscape > escapeTo) { Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax); return false; } return true; case BoundKind.AwaitableValuePlaceholder: if (((BoundAwaitableValuePlaceholder)expr).ValEscape > escapeTo) { Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax); return false; } return true; case BoundKind.InterpolatedStringArgumentPlaceholder: if (((BoundInterpolatedStringArgumentPlaceholder)expr).ValSafeToEscape > escapeTo) { Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax); return false; } return true; case BoundKind.Local: var localSymbol = ((BoundLocal)expr).LocalSymbol; if (localSymbol.ValEscapeScope > escapeTo) { Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol); return false; } return true; case BoundKind.StackAllocArrayCreation: case BoundKind.ConvertedStackAllocExpression: if (escapeTo < Binder.TopLevelScope) { Error(diagnostics, ErrorCode.ERR_EscapeStackAlloc, node, expr.Type); return false; } return true; case BoundKind.UnconvertedConditionalOperator: { var conditional = (BoundUnconvertedConditionalOperator)expr; return CheckValEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckValEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); } case BoundKind.ConditionalOperator: { var conditional = (BoundConditionalOperator)expr; var consValid = CheckValEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); if (!consValid || conditional.IsRef) { // ref conditional defers to one operand. // the other one is the same or we will be reporting errors anyways. return consValid; } return CheckValEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); } case BoundKind.NullCoalescingOperator: var coalescingOp = (BoundNullCoalescingOperator)expr; return CheckValEscape(coalescingOp.LeftOperand.Syntax, coalescingOp.LeftOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics) && CheckValEscape(coalescingOp.RightOperand.Syntax, coalescingOp.RightOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics); case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType) { // Already an error state. return true; } // for ref-like fields defer to the receiver. return CheckValEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, true, diagnostics); case BoundKind.Call: var call = (BoundCall)expr; var methodSymbol = call.Method; return CheckInvocationEscape( call.Syntax, methodSymbol, call.ReceiverOpt, methodSymbol.Parameters, call.Arguments, call.ArgumentRefKindsOpt, call.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.FunctionPointerInvocation: var ptrInvocation = (BoundFunctionPointerInvocation)expr; var ptrSymbol = ptrInvocation.FunctionPointer.Signature; return CheckInvocationEscape( ptrInvocation.Syntax, ptrSymbol, receiverOpt: null, ptrSymbol.Parameters, ptrInvocation.Arguments, ptrInvocation.ArgumentRefKindsOpt, argsToParamsOpt: default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.IndexerAccess: var indexerAccess = (BoundIndexerAccess)expr; var indexerSymbol = indexerAccess.Indexer; return CheckInvocationEscape( indexerAccess.Syntax, indexerSymbol, indexerAccess.ReceiverOpt, indexerSymbol.Parameters, indexerAccess.Arguments, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; var patternSymbol = patternIndexer.PatternSymbol; var parameters = patternSymbol switch { PropertySymbol p => p.Parameters, MethodSymbol m => m.Parameters, _ => throw ExceptionUtilities.Unreachable, }; return CheckInvocationEscape( patternIndexer.Syntax, patternSymbol, patternIndexer.Receiver, parameters, ImmutableArray.Create(patternIndexer.Argument), default, default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.PropertyAccess: var propertyAccess = (BoundPropertyAccess)expr; // not passing any arguments/parameters return CheckInvocationEscape( propertyAccess.Syntax, propertyAccess.PropertySymbol, propertyAccess.ReceiverOpt, default, default, default, default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.ObjectCreationExpression: { var objectCreation = (BoundObjectCreationExpression)expr; var constructorSymbol = objectCreation.Constructor; var escape = CheckInvocationEscape( objectCreation.Syntax, constructorSymbol, null, constructorSymbol.Parameters, objectCreation.Arguments, objectCreation.ArgumentRefKindsOpt, objectCreation.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); var initializerExpr = objectCreation.InitializerExpressionOpt; if (initializerExpr != null) { escape = escape && CheckValEscape( initializerExpr.Syntax, initializerExpr, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); } return escape; } case BoundKind.WithExpression: { var withExpr = (BoundWithExpression)expr; var escape = CheckValEscape(node, withExpr.Receiver, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); var initializerExpr = withExpr.InitializerExpression; escape = escape && CheckValEscape(initializerExpr.Syntax, initializerExpr, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); return escape; } case BoundKind.UnaryOperator: var unary = (BoundUnaryOperator)expr; return CheckValEscape(node, unary.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.FromEndIndexExpression: // We are going to call a constructor that takes an integer and a bool. Cannot leak any references through them. return true; case BoundKind.Conversion: var conversion = (BoundConversion)expr; Debug.Assert(conversion.ConversionKind != ConversionKind.StackAllocToSpanType, "StackAllocToSpanType unexpected"); if (conversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { return CheckInterpolatedStringHandlerConversionEscape(conversion.Operand, escapeFrom, escapeTo, diagnostics); } return CheckValEscape(node, conversion.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expr; return CheckValEscape(node, assignment.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.IncrementOperator: var increment = (BoundIncrementOperator)expr; return CheckValEscape(node, increment.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.CompoundAssignmentOperator: var compound = (BoundCompoundAssignmentOperator)expr; return CheckValEscape(compound.Left.Syntax, compound.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckValEscape(compound.Right.Syntax, compound.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.BinaryOperator: var binary = (BoundBinaryOperator)expr; return CheckValEscape(binary.Left.Syntax, binary.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckValEscape(binary.Right.Syntax, binary.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.RangeExpression: var range = (BoundRangeExpression)expr; if (range.LeftOperandOpt is { } left && !CheckValEscape(left.Syntax, left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } return !(range.RightOperandOpt is { } right && !CheckValEscape(right.Syntax, right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)); case BoundKind.UserDefinedConditionalLogicalOperator: var uo = (BoundUserDefinedConditionalLogicalOperator)expr; return CheckValEscape(uo.Left.Syntax, uo.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckValEscape(uo.Right.Syntax, uo.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.QueryClause: var clauseValue = ((BoundQueryClause)expr).Value; return CheckValEscape(clauseValue.Syntax, clauseValue, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.RangeVariable: var variableValue = ((BoundRangeVariable)expr).Value; return CheckValEscape(variableValue.Syntax, variableValue, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.ObjectInitializerExpression: var initExpr = (BoundObjectInitializerExpression)expr; return CheckValEscapeOfObjectInitializer(initExpr, escapeFrom, escapeTo, diagnostics); // this would be correct implementation for CollectionInitializerExpression // however it is unclear if it is reachable since the initialized type must implement IEnumerable case BoundKind.CollectionInitializerExpression: var colExpr = (BoundCollectionInitializerExpression)expr; return CheckValEscape(colExpr.Initializers, escapeFrom, escapeTo, diagnostics); // this would be correct implementation for CollectionElementInitializer // however it is unclear if it is reachable since the initialized type must implement IEnumerable case BoundKind.CollectionElementInitializer: var colElement = (BoundCollectionElementInitializer)expr; return CheckValEscape(colElement.Arguments, escapeFrom, escapeTo, diagnostics); case BoundKind.PointerElementAccess: var accessedExpression = ((BoundPointerElementAccess)expr).Expression; return CheckValEscape(accessedExpression.Syntax, accessedExpression, escapeFrom, escapeTo, checkingReceiver, diagnostics); case BoundKind.PointerIndirectionOperator: var operandExpression = ((BoundPointerIndirectionOperator)expr).Operand; return CheckValEscape(operandExpression.Syntax, operandExpression, escapeFrom, escapeTo, checkingReceiver, diagnostics); case BoundKind.AsOperator: case BoundKind.AwaitExpression: case BoundKind.ConditionalAccess: case BoundKind.ArrayAccess: // only possible in error cases (if possible at all) return false; case BoundKind.UnconvertedSwitchExpression: case BoundKind.ConvertedSwitchExpression: foreach (var arm in ((BoundSwitchExpression)expr).SwitchArms) { var result = arm.Value; if (!CheckValEscape(result.Syntax, result, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) return false; } return true; default: // in error situations some unexpected nodes could make here // returning "false" seems safer than throwing. // we will still assert to make sure that all nodes are accounted for. Debug.Assert(false, $"{expr.Kind} expression of {expr.Type} type"); diagnostics.Add(ErrorCode.ERR_InternalError, node.Location); return false; #region "cannot produce ref-like values" // case BoundKind.ThrowExpression: // case BoundKind.ArgListOperator: // case BoundKind.ArgList: // case BoundKind.RefTypeOperator: // case BoundKind.AddressOfOperator: // case BoundKind.TypeOfOperator: // case BoundKind.IsOperator: // case BoundKind.SizeOfOperator: // case BoundKind.DynamicMemberAccess: // case BoundKind.DynamicInvocation: // case BoundKind.NewT: // case BoundKind.DelegateCreationExpression: // case BoundKind.ArrayCreation: // case BoundKind.AnonymousObjectCreationExpression: // case BoundKind.NameOfOperator: // case BoundKind.InterpolatedString: // case BoundKind.StringInsert: // case BoundKind.DynamicIndexerAccess: // case BoundKind.Lambda: // case BoundKind.DynamicObjectCreationExpression: // case BoundKind.NoPiaObjectCreationExpression: // case BoundKind.BaseReference: // case BoundKind.Literal: // case BoundKind.IsPatternExpression: // case BoundKind.DeconstructionAssignmentOperator: // case BoundKind.EventAccess: #endregion #region "not expression that can produce a value" // case BoundKind.FieldEqualsValue: // case BoundKind.PropertyEqualsValue: // case BoundKind.ParameterEqualsValue: // case BoundKind.NamespaceExpression: // case BoundKind.TypeExpression: // case BoundKind.BadStatement: // case BoundKind.MethodDefIndex: // case BoundKind.SourceDocumentIndex: // case BoundKind.ArgList: // case BoundKind.ArgListOperator: // case BoundKind.Block: // case BoundKind.Scope: // case BoundKind.NoOpStatement: // case BoundKind.ReturnStatement: // case BoundKind.YieldReturnStatement: // case BoundKind.YieldBreakStatement: // case BoundKind.ThrowStatement: // case BoundKind.ExpressionStatement: // case BoundKind.SwitchStatement: // case BoundKind.SwitchSection: // case BoundKind.SwitchLabel: // case BoundKind.BreakStatement: // case BoundKind.LocalFunctionStatement: // case BoundKind.ContinueStatement: // case BoundKind.PatternSwitchStatement: // case BoundKind.PatternSwitchSection: // case BoundKind.PatternSwitchLabel: // case BoundKind.IfStatement: // case BoundKind.DoStatement: // case BoundKind.WhileStatement: // case BoundKind.ForStatement: // case BoundKind.ForEachStatement: // case BoundKind.ForEachDeconstructStep: // case BoundKind.UsingStatement: // case BoundKind.FixedStatement: // case BoundKind.LockStatement: // case BoundKind.TryStatement: // case BoundKind.CatchBlock: // case BoundKind.LabelStatement: // case BoundKind.GotoStatement: // case BoundKind.LabeledStatement: // case BoundKind.Label: // case BoundKind.StatementList: // case BoundKind.ConditionalGoto: // case BoundKind.LocalDeclaration: // case BoundKind.MultipleLocalDeclarations: // case BoundKind.ArrayInitialization: // case BoundKind.AnonymousPropertyDeclaration: // case BoundKind.MethodGroup: // case BoundKind.PropertyGroup: // case BoundKind.EventAssignmentOperator: // case BoundKind.Attribute: // case BoundKind.FixedLocalCollectionInitializer: // case BoundKind.DynamicObjectInitializerMember: // case BoundKind.DynamicCollectionElementInitializer: // case BoundKind.ImplicitReceiver: // case BoundKind.FieldInitializer: // case BoundKind.GlobalStatementInitializer: // case BoundKind.TypeOrInstanceInitializers: // case BoundKind.DeclarationPattern: // case BoundKind.ConstantPattern: // case BoundKind.WildcardPattern: #endregion #region "not found as an operand in no-error unlowered bound tree" // case BoundKind.MaximumMethodDefIndex: // case BoundKind.InstrumentationPayloadRoot: // case BoundKind.ModuleVersionId: // case BoundKind.ModuleVersionIdString: // case BoundKind.Dup: // case BoundKind.TypeOrValueExpression: // case BoundKind.BadExpression: // case BoundKind.ArrayLength: // case BoundKind.MethodInfo: // case BoundKind.FieldInfo: // case BoundKind.SequencePoint: // case BoundKind.SequencePointExpression: // case BoundKind.SequencePointWithSpan: // case BoundKind.StateMachineScope: // case BoundKind.ConditionalReceiver: // case BoundKind.ComplexConditionalReceiver: // case BoundKind.PreviousSubmissionReference: // case BoundKind.HostObjectMemberReference: // case BoundKind.UnboundLambda: // case BoundKind.LoweredConditionalAccess: // case BoundKind.Sequence: // case BoundKind.HoistedFieldAccess: // case BoundKind.OutVariablePendingInference: // case BoundKind.DeconstructionVariablePendingInference: // case BoundKind.OutDeconstructVarPendingInference: // case BoundKind.PseudoVariable: #endregion } } private static bool CheckTupleValEscape(ImmutableArray<BoundExpression> elements, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { foreach (var element in elements) { if (!CheckValEscape(element.Syntax, element, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } } return true; } private static bool CheckValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { foreach (var expression in initExpr.Initializers) { if (expression.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expression; if (!CheckValEscape(expression.Syntax, assignment.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } var left = (BoundObjectInitializerMember)assignment.Left; if (!CheckValEscape(left.Arguments, escapeFrom, escapeTo, diagnostics: diagnostics)) { return false; } } else { if (!CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } } } return true; } private static bool CheckValEscape(ImmutableArray<BoundExpression> expressions, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { foreach (var expression in expressions) { if (!CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } } return true; } private static bool CheckInterpolatedStringHandlerConversionEscape(BoundExpression expression, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { var data = expression switch { BoundInterpolatedString { InterpolationData: { } d } => d, BoundBinaryOperator { InterpolatedStringHandlerData: { } d } => d, _ => throw ExceptionUtilities.UnexpectedValue(expression.Kind) }; // We need to check to see if any values could potentially escape outside the max depth via the handler type. // Consider the case where a ref-struct handler saves off the result of one call to AppendFormatted, // and then on a subsequent call it either assigns that saved value to another ref struct with a larger // escape, or does the opposite. In either case, we need to check. CheckValEscape(expression.Syntax, data.Construction, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); while (true) { switch (expression) { case BoundBinaryOperator binary: if (!checkParts((BoundInterpolatedString)binary.Right)) { return false; } expression = binary.Left; continue; case BoundInterpolatedString interpolatedString: if (!checkParts(interpolatedString)) { return false; } return true; default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } bool checkParts(BoundInterpolatedString interpolatedString) { foreach (var part in interpolatedString.Parts) { if (part is not BoundCall { Method: { Name: "AppendFormatted" } } call) { // Dynamic calls cannot have ref struct parameters, and AppendLiteral calls will always have literal // string arguments and do not require us to be concerned with escape continue; } // The interpolation component is always the first argument to the method, and it was not passed by name // so there can be no reordering. var argument = call.Arguments[0]; var success = CheckValEscape(argument.Syntax, argument, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); if (!success) { return false; } } return true; } } internal enum AddressKind { // reference may be written to Writeable, // reference itself will not be written to, but may be used for call, callvirt. // for all purposes it is the same as Writeable, except when fetching an address of an array element // where it results in a ".readonly" prefix to deal with array covariance. Constrained, // reference itself will not be written to, nor it will be used to modify fields. ReadOnly, // same as ReadOnly, but we are not supposed to get a reference to a clone // regardless of compat settings. ReadOnlyStrict, } internal static bool IsAnyReadOnly(AddressKind addressKind) => addressKind >= AddressKind.ReadOnly; /// <summary> /// Checks if expression directly or indirectly represents a value with its own home. In /// such cases it is possible to get a reference without loading into a temporary. /// </summary> internal static bool HasHome( BoundExpression expression, AddressKind addressKind, MethodSymbol method, bool peVerifyCompatEnabled, HashSet<LocalSymbol> stackLocalsOpt) { Debug.Assert(method is object); switch (expression.Kind) { case BoundKind.ArrayAccess: if (addressKind == AddressKind.ReadOnly && !expression.Type.IsValueType && peVerifyCompatEnabled) { // due to array covariance getting a reference may throw ArrayTypeMismatch when element is not a struct, // passing "readonly." prefix would prevent that, but it is unverifiable, so will make a copy in compat case return false; } return true; case BoundKind.PointerIndirectionOperator: case BoundKind.RefValueOperator: return true; case BoundKind.ThisReference: var type = expression.Type; if (type.IsReferenceType) { Debug.Assert(IsAnyReadOnly(addressKind), "`this` is readonly in classes"); return true; } if (!IsAnyReadOnly(addressKind) && method.IsEffectivelyReadOnly) { return false; } return true; case BoundKind.ThrowExpression: // vacuously this is true, we can take address of throw without temps return true; case BoundKind.Parameter: return IsAnyReadOnly(addressKind) || ((BoundParameter)expression).ParameterSymbol.RefKind != RefKind.In; case BoundKind.Local: // locals have home unless they are byval stack locals or ref-readonly // locals in a mutating call var local = ((BoundLocal)expression).LocalSymbol; return !((CodeGenerator.IsStackLocal(local, stackLocalsOpt) && local.RefKind == RefKind.None) || (!IsAnyReadOnly(addressKind) && local.RefKind == RefKind.RefReadOnly)); case BoundKind.Call: var methodRefKind = ((BoundCall)expression).Method.RefKind; return methodRefKind == RefKind.Ref || (IsAnyReadOnly(addressKind) && methodRefKind == RefKind.RefReadOnly); case BoundKind.Dup: //NB: Dup represents locals that do not need IL slot var dupRefKind = ((BoundDup)expression).RefKind; return dupRefKind == RefKind.Ref || (IsAnyReadOnly(addressKind) && dupRefKind == RefKind.RefReadOnly); case BoundKind.FieldAccess: return HasHome((BoundFieldAccess)expression, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt); case BoundKind.Sequence: return HasHome(((BoundSequence)expression).Value, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt); case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expression; if (!assignment.IsRef) { return false; } var lhsRefKind = assignment.Left.GetRefKind(); return lhsRefKind == RefKind.Ref || (IsAnyReadOnly(addressKind) && lhsRefKind == RefKind.RefReadOnly); case BoundKind.ComplexConditionalReceiver: Debug.Assert(HasHome( ((BoundComplexConditionalReceiver)expression).ValueTypeReceiver, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt)); Debug.Assert(HasHome( ((BoundComplexConditionalReceiver)expression).ReferenceTypeReceiver, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt)); goto case BoundKind.ConditionalReceiver; case BoundKind.ConditionalReceiver: //ConditionalReceiver is a noop from Emit point of view. - it represents something that has already been pushed. //We should never need a temp for it. return true; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expression; // only ref conditional may be referenced as a variable if (!conditional.IsRef) { return false; } // branch that has no home will need a temporary // if both have no home, just say whole expression has no home // so we could just use one temp for the whole thing return HasHome(conditional.Consequence, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt) && HasHome(conditional.Alternative, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt); default: return false; } } /// <summary> /// Special HasHome for fields. /// Fields have readable homes when they are not constants. /// Fields have writeable homes unless they are readonly and used outside of the constructor. /// </summary> private static bool HasHome( BoundFieldAccess fieldAccess, AddressKind addressKind, MethodSymbol method, bool peVerifyCompatEnabled, HashSet<LocalSymbol> stackLocalsOpt) { Debug.Assert(method is object); FieldSymbol field = fieldAccess.FieldSymbol; // const fields are literal values with no homes. (ex: decimal.Zero) if (field.IsConst) { return false; } // in readonly situations where ref to a copy is not allowed, consider fields as addressable if (addressKind == AddressKind.ReadOnlyStrict) { return true; } // ReadOnly references can always be taken unless we are in peverify compat mode if (addressKind == AddressKind.ReadOnly && !peVerifyCompatEnabled) { return true; } // Some field accesses must be values; values do not have homes. if (fieldAccess.IsByValue) { return false; } if (!field.IsReadOnly) { // in a case if we have a writeable struct field with a receiver that only has a readable home we would need to pass it via a temp. // it would be advantageous to make a temp for the field, not for the outer struct, since the field is smaller and we can get to is by fetching references. // NOTE: this would not be profitable if we have to satisfy verifier, since for verifiability // we would not be able to dig for the inner field using references and the outer struct will have to be copied to a temp anyways. if (!peVerifyCompatEnabled) { Debug.Assert(!IsAnyReadOnly(addressKind)); var receiver = fieldAccess.ReceiverOpt; if (receiver?.Type.IsValueType == true) { // Check receiver: // has writeable home -> return true - the whole chain has writeable home (also a more common case) // has readable home -> return false - we need to copy the field // otherwise -> return true - the copy will be made at higher level so the leaf field can have writeable home return HasHome(receiver, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt) || !HasHome(receiver, AddressKind.ReadOnly, method, peVerifyCompatEnabled, stackLocalsOpt); } } return true; } // while readonly fields have home it is not valid to refer to it when not constructing. if (!TypeSymbol.Equals(field.ContainingType, method.ContainingType, TypeCompareKind.AllIgnoreOptions)) { return false; } if (field.IsStatic) { return method.MethodKind == MethodKind.StaticConstructor; } else { return (method.MethodKind == MethodKind.Constructor || method.IsInitOnly) && fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { /// <summary> /// For the purpose of escape verification we operate with the depth of local scopes. /// The depth is a uint, with smaller number representing shallower/wider scopes. /// The 0 and 1 are special scopes - /// 0 is the "external" or "return" scope that is outside of the containing method/lambda. /// If something can escape to scope 0, it can escape to any scope in a given method or can be returned. /// 1 is the "parameter" or "top" scope that is just inside the containing method/lambda. /// If something can escape to scope 1, it can escape to any scope in a given method, but cannot be returned. /// n + 1 corresponds to scopes immediately inside a scope of depth n. /// Since sibling scopes do not intersect and a value cannot escape from one to another without /// escaping to a wider scope, we can use simple depth numbering without ambiguity. /// </summary> internal const uint ExternalScope = 0; internal const uint TopLevelScope = 1; // Some value kinds are semantically the same and the only distinction is how errors are reported // for those purposes we reserve lowest 2 bits private const int ValueKindInsignificantBits = 2; private const BindValueKind ValueKindSignificantBitsMask = unchecked((BindValueKind)~((1 << ValueKindInsignificantBits) - 1)); /// <summary> /// Expression capabilities and requirements. /// </summary> [Flags] internal enum BindValueKind : ushort { /////////////////// // All expressions can be classified according to the following 4 capabilities: // /// <summary> /// Expression can be an RHS of an assignment operation. /// </summary> /// <remarks> /// The following are rvalues: values, variables, null literals, properties /// and indexers with getters, events. /// /// The following are not rvalues: /// namespaces, types, method groups, anonymous functions. /// </remarks> RValue = 1 << ValueKindInsignificantBits, /// <summary> /// Expression can be the LHS of a simple assignment operation. /// Example: /// property with a setter /// </summary> Assignable = 2 << ValueKindInsignificantBits, /// <summary> /// Expression represents a location. Often referred as a "variable" /// Examples: /// local variable, parameter, field /// </summary> RefersToLocation = 4 << ValueKindInsignificantBits, /// <summary> /// Expression can be the LHS of a ref-assign operation. /// Example: /// ref local, ref parameter, out parameter /// </summary> RefAssignable = 8 << ValueKindInsignificantBits, /////////////////// // The rest are just combinations of the above. // /// <summary> /// Expression is the RHS of an assignment operation /// and may be a method group. /// Basically an RValue, but could be treated differently for the purpose of error reporting /// </summary> RValueOrMethodGroup = RValue + 1, /// <summary> /// Expression can be an LHS of a compound assignment /// operation (such as +=). /// </summary> CompoundAssignment = RValue | Assignable, /// <summary> /// Expression can be the operand of an increment or decrement operation. /// Same as CompoundAssignment, the distinction is really just for error reporting. /// </summary> IncrementDecrement = CompoundAssignment + 1, /// <summary> /// Expression is a r/o reference. /// </summary> ReadonlyRef = RefersToLocation | RValue, /// <summary> /// Expression can be the operand of an address-of operation (&amp;). /// Same as ReadonlyRef. The difference is just for error reporting. /// </summary> AddressOf = ReadonlyRef + 1, /// <summary> /// Expression is the receiver of a fixed buffer field access /// Same as ReadonlyRef. The difference is just for error reporting. /// </summary> FixedReceiver = ReadonlyRef + 2, /// <summary> /// Expression is passed as a ref or out parameter or assigned to a byref variable. /// </summary> RefOrOut = RefersToLocation | RValue | Assignable, /// <summary> /// Expression is returned by an ordinary r/w reference. /// Same as RefOrOut. The difference is just for error reporting. /// </summary> RefReturn = RefOrOut + 1, } private static bool RequiresRValueOnly(BindValueKind kind) { return (kind & ValueKindSignificantBitsMask) == BindValueKind.RValue; } private static bool RequiresAssignmentOnly(BindValueKind kind) { return (kind & ValueKindSignificantBitsMask) == BindValueKind.Assignable; } private static bool RequiresVariable(BindValueKind kind) { return !RequiresRValueOnly(kind); } private static bool RequiresReferenceToLocation(BindValueKind kind) { return (kind & BindValueKind.RefersToLocation) != 0; } private static bool RequiresAssignableVariable(BindValueKind kind) { return (kind & BindValueKind.Assignable) != 0; } private static bool RequiresRefAssignableVariable(BindValueKind kind) { return (kind & BindValueKind.RefAssignable) != 0; } private static bool RequiresRefOrOut(BindValueKind kind) { return (kind & BindValueKind.RefOrOut) == BindValueKind.RefOrOut; } #nullable enable private BoundIndexerAccess BindIndexerDefaultArguments(BoundIndexerAccess indexerAccess, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { var useSetAccessor = valueKind == BindValueKind.Assignable && !indexerAccess.Indexer.ReturnsByRef; var accessorForDefaultArguments = useSetAccessor ? indexerAccess.Indexer.GetOwnOrInheritedSetMethod() : indexerAccess.Indexer.GetOwnOrInheritedGetMethod(); if (accessorForDefaultArguments is not null) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(accessorForDefaultArguments.ParameterCount); argumentsBuilder.AddRange(indexerAccess.Arguments); ArrayBuilder<RefKind>? refKindsBuilderOpt; if (!indexerAccess.ArgumentRefKindsOpt.IsDefaultOrEmpty) { refKindsBuilderOpt = ArrayBuilder<RefKind>.GetInstance(accessorForDefaultArguments.ParameterCount); refKindsBuilderOpt.AddRange(indexerAccess.ArgumentRefKindsOpt); } else { refKindsBuilderOpt = null; } var argsToParams = indexerAccess.ArgsToParamsOpt; // It is possible for the indexer 'value' parameter from metadata to have a default value, but the compiler will not use it. // However, we may still use any default values from the preceding parameters. var parameters = accessorForDefaultArguments.Parameters; if (useSetAccessor) { parameters = parameters.RemoveAt(parameters.Length - 1); } BitVector defaultArguments = default; Debug.Assert(parameters.Length == indexerAccess.Indexer.Parameters.Length); // If OriginalIndexersOpt is set, there was an overload resolution failure, and we don't want to make guesses about the default // arguments that will end up being reflected in the SemanticModel/IOperation if (indexerAccess.OriginalIndexersOpt.IsDefault) { BindDefaultArguments(indexerAccess.Syntax, parameters, argumentsBuilder, refKindsBuilderOpt, ref argsToParams, out defaultArguments, indexerAccess.Expanded, enableCallerInfo: true, diagnostics); } indexerAccess = indexerAccess.Update( indexerAccess.ReceiverOpt, indexerAccess.Indexer, argumentsBuilder.ToImmutableAndFree(), indexerAccess.ArgumentNamesOpt, refKindsBuilderOpt?.ToImmutableOrNull() ?? default, indexerAccess.Expanded, argsToParams, defaultArguments, indexerAccess.Type); refKindsBuilderOpt?.Free(); } return indexerAccess; } #nullable disable /// <summary> /// Check the expression is of the required lvalue and rvalue specified by valueKind. /// The method returns the original expression if the expression is of the required /// type. Otherwise, an appropriate error is added to the diagnostics bag and the /// method returns a BoundBadExpression node. The method returns the original /// expression without generating any error if the expression has errors. /// </summary> private BoundExpression CheckValue(BoundExpression expr, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { switch (expr.Kind) { case BoundKind.PropertyGroup: expr = BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics); if (expr is BoundIndexerAccess indexerAccess) { expr = BindIndexerDefaultArguments(indexerAccess, valueKind, diagnostics); } break; case BoundKind.Local: Debug.Assert(expr.Syntax.Kind() != SyntaxKind.Argument || valueKind == BindValueKind.RefOrOut); break; case BoundKind.OutVariablePendingInference: case BoundKind.OutDeconstructVarPendingInference: Debug.Assert(valueKind == BindValueKind.RefOrOut); return expr; case BoundKind.DiscardExpression: Debug.Assert(valueKind == BindValueKind.Assignable || valueKind == BindValueKind.RefOrOut || diagnostics.DiagnosticBag is null || diagnostics.HasAnyResolvedErrors()); return expr; case BoundKind.IndexerAccess: expr = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics); break; case BoundKind.UnconvertedObjectCreationExpression: if (valueKind == BindValueKind.RValue) { return expr; } break; case BoundKind.PointerIndirectionOperator: if ((valueKind & BindValueKind.RefersToLocation) == BindValueKind.RefersToLocation) { var pointerIndirection = (BoundPointerIndirectionOperator)expr; expr = pointerIndirection.Update(pointerIndirection.Operand, refersToLocation: true, pointerIndirection.Type); } break; case BoundKind.PointerElementAccess: if ((valueKind & BindValueKind.RefersToLocation) == BindValueKind.RefersToLocation) { var elementAccess = (BoundPointerElementAccess)expr; expr = elementAccess.Update(elementAccess.Expression, elementAccess.Index, elementAccess.Checked, refersToLocation: true, elementAccess.Type); } break; } bool hasResolutionErrors = false; // If this a MethodGroup where an rvalue is not expected or where the caller will not explicitly handle // (and resolve) MethodGroups (in short, cases where valueKind != BindValueKind.RValueOrMethodGroup), // resolve the MethodGroup here to generate the appropriate errors, otherwise resolution errors (such as // "member is inaccessible") will be dropped. if (expr.Kind == BoundKind.MethodGroup && valueKind != BindValueKind.RValueOrMethodGroup) { var methodGroup = (BoundMethodGroup)expr; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); Symbol otherSymbol = null; bool resolvedToMethodGroup = resolution.MethodGroup != null; if (!expr.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading. hasResolutionErrors = resolution.HasAnyErrors; if (hasResolutionErrors) { otherSymbol = resolution.OtherSymbol; } resolution.Free(); // It's possible the method group is not a method group at all, but simply a // delayed lookup that resolved to a non-method member (perhaps an inaccessible // field or property), or nothing at all. In those cases, the member should not be exposed as a // method group, not even within a BoundBadExpression. Instead, the // BoundBadExpression simply refers to the receiver and the resolved symbol (if any). if (!resolvedToMethodGroup) { Debug.Assert(methodGroup.ResultKind != LookupResultKind.Viable); var receiver = methodGroup.ReceiverOpt; if ((object)otherSymbol != null && receiver?.Kind == BoundKind.TypeOrValueExpression) { // Since we're not accessing a method, this can't be a Color Color case, so TypeOrValueExpression should not have been used. // CAVEAT: otherSymbol could be invalid in some way (e.g. inaccessible), in which case we would have fallen back on a // method group lookup (to allow for extension methods), which would have required a TypeOrValueExpression. Debug.Assert(methodGroup.LookupError != null); // Since we have a concrete member in hand, we can resolve the receiver. var typeOrValue = (BoundTypeOrValueExpression)receiver; receiver = otherSymbol.RequiresInstanceReceiver() ? typeOrValue.Data.ValueExpression : null; // no receiver required } return new BoundBadExpression( expr.Syntax, methodGroup.ResultKind, (object)otherSymbol == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(otherSymbol), receiver == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(receiver), GetNonMethodMemberType(otherSymbol)); } } if (!hasResolutionErrors && CheckValueKind(expr.Syntax, expr, valueKind, checkingReceiver: false, diagnostics: diagnostics) || expr.HasAnyErrors && valueKind == BindValueKind.RValueOrMethodGroup) { return expr; } var resultKind = (valueKind == BindValueKind.RValue || valueKind == BindValueKind.RValueOrMethodGroup) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable; return ToBadExpression(expr, resultKind); } internal static bool IsTypeOrValueExpression(BoundExpression expression) { switch (expression?.Kind) { case BoundKind.TypeOrValueExpression: case BoundKind.QueryClause when ((BoundQueryClause)expression).Value.Kind == BoundKind.TypeOrValueExpression: return true; default: return false; } } /// <summary> /// The purpose of this method is to determine if the expression satisfies desired capabilities. /// If it is not then this code gives an appropriate error message. /// /// To determine the appropriate error message we need to know two things: /// /// (1) What capabilities we need - increment it, assign, return as a readonly reference, . . . ? /// /// (2) Are we trying to determine if the left hand side of a dot is a variable in order /// to determine if the field or property on the right hand side of a dot is assignable? /// /// (3) The syntax of the expression that started the analysis. (for error reporting purposes). /// </summary> internal bool CheckValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter()); if (expr.HasAnyErrors) { return false; } switch (expr.Kind) { // we need to handle properties and event in a special way even in an RValue case because of getters case BoundKind.PropertyAccess: case BoundKind.IndexerAccess: return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = ((BoundIndexOrRangePatternIndexerAccess)expr); if (patternIndexer.PatternSymbol.Kind == SymbolKind.Property) { // If this is an Index indexer, PatternSymbol should be a property, pointing to the // pattern indexer. If it's a Range access, it will be a method, pointing to a Slice method // and it's handled below as part of invocations. return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics); } Debug.Assert(patternIndexer.PatternSymbol.Kind == SymbolKind.Method); break; case BoundKind.EventAccess: return CheckEventValueKind((BoundEventAccess)expr, valueKind, diagnostics); } // easy out for a very common RValue case. if (RequiresRValueOnly(valueKind)) { return CheckNotNamespaceOrType(expr, diagnostics); } // constants/literals are strictly RValues // void is not even an RValue if ((expr.ConstantValue != null) || (expr.Type.GetSpecialTypeSafe() == SpecialType.System_Void)) { Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } switch (expr.Kind) { case BoundKind.NamespaceExpression: var ns = (BoundNamespaceExpression)expr; Error(diagnostics, ErrorCode.ERR_BadSKknown, node, ns.NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); return false; case BoundKind.TypeExpression: var type = (BoundTypeExpression)expr; Error(diagnostics, ErrorCode.ERR_BadSKknown, node, type.Type, MessageID.IDS_SK_TYPE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); return false; case BoundKind.Lambda: case BoundKind.UnboundLambda: // lambdas can only be used as RValues Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; case BoundKind.UnconvertedAddressOfOperator: var unconvertedAddressOf = (BoundUnconvertedAddressOfOperator)expr; Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, unconvertedAddressOf.Operand.Name, MessageID.IDS_AddressOfMethodGroup.Localize()); return false; case BoundKind.MethodGroup when valueKind == BindValueKind.AddressOf: // If the addressof operator is used not as an rvalue, that will get flagged when CheckValue // is called on the parent BoundUnconvertedAddressOf node. return true; case BoundKind.MethodGroup: // method groups can only be used as RValues except when taking the address of one var methodGroup = (BoundMethodGroup)expr; Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, methodGroup.Name, MessageID.IDS_MethodGroup.Localize()); return false; case BoundKind.RangeVariable: // range variables can only be used as RValues var queryref = (BoundRangeVariable)expr; Error(diagnostics, GetRangeLvalueError(valueKind), node, queryref.RangeVariableSymbol.Name); return false; case BoundKind.Conversion: var conversion = (BoundConversion)expr; // conversions are strict RValues, but unboxing has a specific error if (conversion.ConversionKind == ConversionKind.Unboxing) { Error(diagnostics, ErrorCode.ERR_UnboxNotLValue, node); return false; } break; // array access is readwrite variable if the indexing expression is not System.Range case BoundKind.ArrayAccess: { if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } var boundAccess = (BoundArrayAccess)expr; if (boundAccess.Indices.Length == 1 && TypeSymbol.Equals( boundAccess.Indices[0].Type, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)) { // Range indexer is an rvalue Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } return true; } // pointer dereferencing is a readwrite variable case BoundKind.PointerIndirectionOperator: // The undocumented __refvalue(tr, T) expression results in a variable of type T. case BoundKind.RefValueOperator: // dynamic expressions are readwrite, and can even be passed by ref (which is implemented via a temp) case BoundKind.DynamicMemberAccess: case BoundKind.DynamicIndexerAccess: { if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } // These are readwrite variables return true; } case BoundKind.PointerElementAccess: { if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } var receiver = ((BoundPointerElementAccess)expr).Expression; if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { return CheckValueKind(node, fieldAccess.ReceiverOpt, valueKind, checkingReceiver: true, diagnostics); } return true; } case BoundKind.Parameter: var parameter = (BoundParameter)expr; return CheckParameterValueKind(node, parameter, valueKind, checkingReceiver, diagnostics); case BoundKind.Local: var local = (BoundLocal)expr; return CheckLocalValueKind(node, local, valueKind, checkingReceiver, diagnostics); case BoundKind.ThisReference: // `this` is never ref assignable if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } // We will already have given an error for "this" used outside of a constructor, // instance method, or instance accessor. Assume that "this" is a variable if it is in a struct. // SPEC: when this is used in a primary-expression within an instance constructor of a struct, // SPEC: it is classified as a variable. // SPEC: When this is used in a primary-expression within an instance method or instance accessor // SPEC: of a struct, it is classified as a variable. // Note: RValueOnly is checked at the beginning of this method. Since we are here we need more than readable. // "this" is readonly in members marked "readonly" and in members of readonly structs, unless we are in a constructor. var isValueType = ((BoundThisReference)expr).Type.IsValueType; if (!isValueType || (RequiresAssignableVariable(valueKind) && (this.ContainingMemberOrLambda as MethodSymbol)?.IsEffectivelyReadOnly == true)) { Error(diagnostics, GetThisLvalueError(valueKind, isValueType), node, node); return false; } return true; case BoundKind.ImplicitReceiver: case BoundKind.ObjectOrCollectionValuePlaceholder: Debug.Assert(!RequiresRefAssignableVariable(valueKind)); return true; case BoundKind.Call: var call = (BoundCall)expr; return CheckCallValueKind(call, node, valueKind, checkingReceiver, diagnostics); case BoundKind.FunctionPointerInvocation: return CheckMethodReturnValueKind(((BoundFunctionPointerInvocation)expr).FunctionPointer.Signature, expr.Syntax, node, valueKind, checkingReceiver, diagnostics); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; // If we got here this should be a pattern indexer taking a Range, // meaning that the pattern symbol must be a method (either Slice or Substring) return CheckMethodReturnValueKind( (MethodSymbol)patternIndexer.PatternSymbol, patternIndexer.Syntax, node, valueKind, checkingReceiver, diagnostics); case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expr; // byref conditional defers to its operands if (conditional.IsRef && (CheckValueKind(conditional.Consequence.Syntax, conditional.Consequence, valueKind, checkingReceiver: false, diagnostics: diagnostics) & CheckValueKind(conditional.Alternative.Syntax, conditional.Alternative, valueKind, checkingReceiver: false, diagnostics: diagnostics))) { return true; } // report standard lvalue error break; case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; return CheckFieldValueKind(node, fieldAccess, valueKind, checkingReceiver, diagnostics); } case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expr; return CheckSimpleAssignmentValueKind(node, assignment, valueKind, diagnostics); } // At this point we should have covered all the possible cases for anything that is not a strict RValue. Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } private static bool CheckNotNamespaceOrType(BoundExpression expr, BindingDiagnosticBag diagnostics) { switch (expr.Kind) { case BoundKind.NamespaceExpression: Error(diagnostics, ErrorCode.ERR_BadSKknown, expr.Syntax, ((BoundNamespaceExpression)expr).NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); return false; case BoundKind.TypeExpression: Error(diagnostics, ErrorCode.ERR_BadSKunknown, expr.Syntax, expr.Type, MessageID.IDS_SK_TYPE.Localize()); return false; default: return true; } } private bool CheckLocalValueKind(SyntaxNode node, BoundLocal local, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { // Local constants are never variables. Local variables are sometimes // not to be treated as variables, if they are fixed, declared in a using, // or declared in a foreach. LocalSymbol localSymbol = local.LocalSymbol; if (RequiresAssignableVariable(valueKind)) { if (this.LockedOrDisposedVariables.Contains(localSymbol)) { diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, local.Syntax.Location, localSymbol); } // IsWritable means the variable is writable. If this is a ref variable, IsWritable // does not imply anything about the storage location if (localSymbol.RefKind == RefKind.RefReadOnly || (localSymbol.RefKind == RefKind.None && !localSymbol.IsWritableVariable)) { ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics); return false; } } else if (RequiresRefAssignableVariable(valueKind)) { if (localSymbol.RefKind == RefKind.None) { diagnostics.Add(ErrorCode.ERR_RefLocalOrParamExpected, node.Location, localSymbol); return false; } else if (!localSymbol.IsWritableVariable) { ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics); return false; } } return true; } private static bool CheckLocalRefEscape(SyntaxNode node, BoundLocal local, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) { LocalSymbol localSymbol = local.LocalSymbol; // if local symbol can escape to the same or wider/shallower scope then escapeTo // then it is all ok, otherwise it is an error. if (localSymbol.RefEscapeScope <= escapeTo) { return true; } if (escapeTo == Binder.ExternalScope) { if (localSymbol.RefKind == RefKind.None) { if (checkingReceiver) { Error(diagnostics, ErrorCode.ERR_RefReturnLocal2, local.Syntax, localSymbol); } else { Error(diagnostics, ErrorCode.ERR_RefReturnLocal, node, localSymbol); } return false; } if (checkingReceiver) { Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal2, local.Syntax, localSymbol); } else { Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal, node, localSymbol); } return false; } Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol); return false; } private bool CheckParameterValueKind(SyntaxNode node, BoundParameter parameter, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { ParameterSymbol parameterSymbol = parameter.ParameterSymbol; // all parameters can be passed by ref/out or assigned to // except "in" parameters, which are readonly if (parameterSymbol.RefKind == RefKind.In && RequiresAssignableVariable(valueKind)) { ReportReadOnlyError(parameterSymbol, node, valueKind, checkingReceiver, diagnostics); return false; } else if (parameterSymbol.RefKind == RefKind.None && RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } if (this.LockedOrDisposedVariables.Contains(parameterSymbol)) { // Consider: It would be more conventional to pass "symbol" rather than "symbol.Name". // The issue is that the error SymbolDisplayFormat doesn't display parameter // names - only their types - which works great in signatures, but not at all // at the top level. diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, parameter.Syntax.Location, parameterSymbol.Name); } return true; } private static bool CheckParameterRefEscape(SyntaxNode node, BoundParameter parameter, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) { ParameterSymbol parameterSymbol = parameter.ParameterSymbol; // byval parameters can escape to method's top level. Others can escape further. // NOTE: "method" here means nearest containing method, lambda or local function. if (escapeTo == Binder.ExternalScope && parameterSymbol.RefKind == RefKind.None) { if (checkingReceiver) { Error(diagnostics, ErrorCode.ERR_RefReturnParameter2, parameter.Syntax, parameterSymbol.Name); } else { Error(diagnostics, ErrorCode.ERR_RefReturnParameter, node, parameterSymbol.Name); } return false; } // can ref-escape to any scope otherwise return true; } private bool CheckFieldValueKind(SyntaxNode node, BoundFieldAccess fieldAccess, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { var fieldSymbol = fieldAccess.FieldSymbol; var fieldIsStatic = fieldSymbol.IsStatic; if (RequiresAssignableVariable(valueKind)) { // A field is writeable unless // (1) it is readonly and we are not in a constructor or field initializer // (2) the receiver of the field is of value type and is not a variable or object creation expression. // For example, if you have a class C with readonly field f of type S, and // S has a mutable field x, then c.f.x is not a variable because c.f is not // writable. if (fieldSymbol.IsReadOnly) { var canModifyReadonly = false; Symbol containing = this.ContainingMemberOrLambda; if ((object)containing != null && fieldIsStatic == containing.IsStatic && (fieldIsStatic || fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference) && (Compilation.FeatureStrictEnabled ? TypeSymbol.Equals(fieldSymbol.ContainingType, containing.ContainingType, TypeCompareKind.ConsiderEverything2) // We duplicate a bug in the native compiler for compatibility in non-strict mode : TypeSymbol.Equals(fieldSymbol.ContainingType.OriginalDefinition, containing.ContainingType.OriginalDefinition, TypeCompareKind.ConsiderEverything2))) { if (containing.Kind == SymbolKind.Method) { MethodSymbol containingMethod = (MethodSymbol)containing; MethodKind desiredMethodKind = fieldIsStatic ? MethodKind.StaticConstructor : MethodKind.Constructor; canModifyReadonly = (containingMethod.MethodKind == desiredMethodKind) || isAssignedFromInitOnlySetterOnThis(fieldAccess.ReceiverOpt); } else if (containing.Kind == SymbolKind.Field) { canModifyReadonly = true; } } if (!canModifyReadonly) { ReportReadOnlyFieldError(fieldSymbol, node, valueKind, checkingReceiver, diagnostics); return false; } } if (fieldSymbol.IsFixedSizeBuffer) { Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } } if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } // r/w fields that are static or belong to reference types are writeable and returnable if (fieldIsStatic || fieldSymbol.ContainingType.IsReferenceType) { return true; } // for other fields defer to the receiver. return CheckIsValidReceiverForVariable(node, fieldAccess.ReceiverOpt, valueKind, diagnostics); bool isAssignedFromInitOnlySetterOnThis(BoundExpression receiver) { // bad: other.readonlyField = ... // bad: base.readonlyField = ... if (!(receiver is BoundThisReference)) { return false; } if (!(ContainingMemberOrLambda is MethodSymbol method)) { return false; } return method.IsInitOnly; } } private bool CheckSimpleAssignmentValueKind(SyntaxNode node, BoundAssignmentOperator assignment, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { // Only ref-assigns produce LValues if (assignment.IsRef) { return CheckValueKind(node, assignment.Left, valueKind, checkingReceiver: false, diagnostics); } Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; } private static bool CheckFieldRefEscape(SyntaxNode node, BoundFieldAccess fieldAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { var fieldSymbol = fieldAccess.FieldSymbol; // fields that are static or belong to reference types can ref escape anywhere if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType) { return true; } // for other fields defer to the receiver. return CheckRefEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics); } private static bool CheckFieldLikeEventRefEscape(SyntaxNode node, BoundEventAccess eventAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { var eventSymbol = eventAccess.EventSymbol; // field-like events that are static or belong to reference types can ref escape anywhere if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType) { return true; } // for other events defer to the receiver. return CheckRefEscape(node, eventAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics); } private bool CheckEventValueKind(BoundEventAccess boundEvent, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { // Compound assignment (actually "event assignment") is allowed "everywhere", subject to the restrictions of // accessibility, use site errors, and receiver variable-ness (for structs). // Other operations are allowed only for field-like events and only where the backing field is accessible // (i.e. in the declaring type) - subject to use site errors and receiver variable-ness. BoundExpression receiver = boundEvent.ReceiverOpt; SyntaxNode eventSyntax = GetEventName(boundEvent); //does not include receiver EventSymbol eventSymbol = boundEvent.EventSymbol; if (valueKind == BindValueKind.CompoundAssignment) { // NOTE: accessibility has already been checked by lookup. // NOTE: availability of well-known members is checked in BindEventAssignment because // we don't have the context to determine whether addition or subtraction is being performed. if (ReportUseSite(eventSymbol, diagnostics, eventSyntax)) { // NOTE: BindEventAssignment checks use site errors on the specific accessor // (since we don't know which is being used). return false; } Debug.Assert(!RequiresVariableReceiver(receiver, eventSymbol)); return true; } else { if (!boundEvent.IsUsableAsField) { // Dev10 reports this in addition to ERR_BadAccess, but we won't even reach this point if the event isn't accessible (caught by lookup). Error(diagnostics, GetBadEventUsageDiagnosticInfo(eventSymbol), eventSyntax); return false; } else if (ReportUseSite(eventSymbol, diagnostics, eventSyntax)) { if (!CheckIsValidReceiverForVariable(eventSyntax, receiver, BindValueKind.Assignable, diagnostics)) { return false; } } else if (RequiresVariable(valueKind)) { if (eventSymbol.IsWindowsRuntimeEvent && valueKind != BindValueKind.Assignable) { // NOTE: Dev11 reports ERR_RefProperty, as if this were a property access (since that's how it will be lowered). // Roslyn reports a new, more specific, error code. ErrorCode errorCode = valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_WinRtEventPassedByRef : GetStandardLvalueError(valueKind); Error(diagnostics, errorCode, eventSyntax, eventSymbol); return false; } else if (RequiresVariableReceiver(receiver, eventSymbol.AssociatedField) && // NOTE: using field, not event !CheckIsValidReceiverForVariable(eventSyntax, receiver, valueKind, diagnostics)) { return false; } } return true; } } private bool CheckIsValidReceiverForVariable(SyntaxNode node, BoundExpression receiver, BindValueKind kind, BindingDiagnosticBag diagnostics) { Debug.Assert(receiver != null); return Flags.Includes(BinderFlags.ObjectInitializerMember) && receiver.Kind == BoundKind.ObjectOrCollectionValuePlaceholder || CheckValueKind(node, receiver, kind, true, diagnostics); } /// <summary> /// SPEC: When a property or indexer declared in a struct-type is the target of an /// SPEC: assignment, the instance expression associated with the property or indexer /// SPEC: access must be classified as a variable. If the instance expression is /// SPEC: classified as a value, a compile-time error occurs. Because of 7.6.4, /// SPEC: the same rule also applies to fields. /// </summary> /// <remarks> /// NOTE: The spec fails to impose the restriction that the event receiver must be classified /// as a variable (unlike for properties - 7.17.1). This seems like a bug, but we have /// production code that won't build with the restriction in place (see DevDiv #15674). /// </remarks> private static bool RequiresVariableReceiver(BoundExpression receiver, Symbol symbol) { return symbol.RequiresInstanceReceiver() && symbol.Kind != SymbolKind.Event && receiver?.Type?.IsValueType == true; } private bool CheckCallValueKind(BoundCall call, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) => CheckMethodReturnValueKind(call.Method, call.Syntax, node, valueKind, checkingReceiver, diagnostics); protected bool CheckMethodReturnValueKind( MethodSymbol methodSymbol, SyntaxNode callSyntaxOpt, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { // A call can only be a variable if it returns by reference. If this is the case, // whether or not it is a valid variable depends on whether or not the call is the // RHS of a return or an assign by reference: // - If call is used in a context demanding ref-returnable reference all of its ref // inputs must be ref-returnable if (RequiresVariable(valueKind) && methodSymbol.RefKind == RefKind.None) { if (checkingReceiver) { // Error is associated with expression, not node which may be distinct. Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, callSyntaxOpt, methodSymbol); } else { Error(diagnostics, GetStandardLvalueError(valueKind), node); } return false; } if (RequiresAssignableVariable(valueKind) && methodSymbol.RefKind == RefKind.RefReadOnly) { ReportReadOnlyError(methodSymbol, node, valueKind, checkingReceiver, diagnostics); return false; } if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } return true; } private bool CheckPropertyValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { // SPEC: If the left operand is a property or indexer access, the property or indexer must // SPEC: have a set accessor. If this is not the case, a compile-time error occurs. // Addendum: Assignment is also allowed for get-only autoprops in their constructor BoundExpression receiver; SyntaxNode propertySyntax; var propertySymbol = GetPropertySymbol(expr, out receiver, out propertySyntax); Debug.Assert((object)propertySymbol != null); Debug.Assert(propertySyntax != null); if ((RequiresReferenceToLocation(valueKind) || checkingReceiver) && propertySymbol.RefKind == RefKind.None) { if (checkingReceiver) { // Error is associated with expression, not node which may be distinct. // This error is reported for all values types. That is a breaking // change from Dev10 which reports this error for struct types only, // not for type parameters constrained to "struct". Debug.Assert(propertySymbol.TypeWithAnnotations.HasType); Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, expr.Syntax, propertySymbol); } else { Error(diagnostics, valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_RefProperty : GetStandardLvalueError(valueKind), node, propertySymbol); } return false; } if (RequiresAssignableVariable(valueKind) && propertySymbol.RefKind == RefKind.RefReadOnly) { ReportReadOnlyError(propertySymbol, node, valueKind, checkingReceiver, diagnostics); return false; } var requiresSet = RequiresAssignableVariable(valueKind) && propertySymbol.RefKind == RefKind.None; if (requiresSet) { var setMethod = propertySymbol.GetOwnOrInheritedSetMethod(); if (setMethod is null) { var containing = this.ContainingMemberOrLambda; if (!AccessingAutoPropertyFromConstructor(receiver, propertySymbol, containing) && !isAllowedDespiteReadonly(receiver)) { Error(diagnostics, ErrorCode.ERR_AssgReadonlyProp, node, propertySymbol); return false; } } else { if (setMethod.IsInitOnly) { if (!isAllowedInitOnlySet(receiver)) { Error(diagnostics, ErrorCode.ERR_AssignmentInitOnly, node, propertySymbol); return false; } if (setMethod.DeclaringCompilation != this.Compilation) { // an error would have already been reported on declaring an init-only setter CheckFeatureAvailability(node, MessageID.IDS_FeatureInitOnlySetters, diagnostics); } } var accessThroughType = this.GetAccessThroughType(receiver); bool failedThroughTypeCheck; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsAccessible(setMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { if (failedThroughTypeCheck) { Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, node, propertySymbol, accessThroughType, this.ContainingType); } else { Error(diagnostics, ErrorCode.ERR_InaccessibleSetter, node, propertySymbol); } return false; } ReportDiagnosticsIfObsolete(diagnostics, setMethod, node, receiver?.Kind == BoundKind.BaseReference); var setValueKind = setMethod.IsEffectivelyReadOnly ? BindValueKind.RValue : BindValueKind.Assignable; if (RequiresVariableReceiver(receiver, setMethod) && !CheckIsValidReceiverForVariable(node, receiver, setValueKind, diagnostics)) { return false; } if (IsBadBaseAccess(node, receiver, setMethod, diagnostics, propertySymbol) || reportUseSite(setMethod)) { return false; } CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, setMethod, diagnostics); } } var requiresGet = !RequiresAssignmentOnly(valueKind) || propertySymbol.RefKind != RefKind.None; if (requiresGet) { var getMethod = propertySymbol.GetOwnOrInheritedGetMethod(); if ((object)getMethod == null) { Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, node, propertySymbol); return false; } else { var accessThroughType = this.GetAccessThroughType(receiver); bool failedThroughTypeCheck; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsAccessible(getMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { if (failedThroughTypeCheck) { Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, node, propertySymbol, accessThroughType, this.ContainingType); } else { Error(diagnostics, ErrorCode.ERR_InaccessibleGetter, node, propertySymbol); } return false; } CheckImplicitThisCopyInReadOnlyMember(receiver, getMethod, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, getMethod, node, receiver?.Kind == BoundKind.BaseReference); if (IsBadBaseAccess(node, receiver, getMethod, diagnostics, propertySymbol) || reportUseSite(getMethod)) { return false; } CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, getMethod, diagnostics); } } if (RequiresRefAssignableVariable(valueKind)) { Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node); return false; } return true; bool reportUseSite(MethodSymbol accessor) { UseSiteInfo<AssemblySymbol> useSiteInfo = accessor.GetUseSiteInfo(); if (!object.Equals(useSiteInfo.DiagnosticInfo, propertySymbol.GetUseSiteInfo().DiagnosticInfo)) { return diagnostics.Add(useSiteInfo, propertySyntax); } else { diagnostics.AddDependencies(useSiteInfo); } return false; } static bool isAllowedDespiteReadonly(BoundExpression receiver) { // ok: anonymousType with { Property = ... } if (receiver is BoundObjectOrCollectionValuePlaceholder && receiver.Type.IsAnonymousType) { return true; } return false; } bool isAllowedInitOnlySet(BoundExpression receiver) { // ok: new C() { InitOnlyProperty = ... } // bad: { ... = { InitOnlyProperty = ... } } if (receiver is BoundObjectOrCollectionValuePlaceholder placeholder) { return placeholder.IsNewInstance; } // bad: other.InitOnlyProperty = ... if (!(receiver is BoundThisReference || receiver is BoundBaseReference)) { return false; } var containingMember = ContainingMemberOrLambda; if (!(containingMember is MethodSymbol method)) { return false; } if (method.MethodKind == MethodKind.Constructor || method.IsInitOnly) { // ok: setting on `this` or `base` from an instance constructor or init-only setter return true; } return false; } } private bool IsBadBaseAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol member, BindingDiagnosticBag diagnostics, Symbol propertyOrEventSymbolOpt = null) { Debug.Assert(member.Kind != SymbolKind.Property); Debug.Assert(member.Kind != SymbolKind.Event); if (receiverOpt?.Kind == BoundKind.BaseReference && member.IsAbstract) { Error(diagnostics, ErrorCode.ERR_AbstractBaseCall, node, propertyOrEventSymbolOpt ?? member); return true; } return false; } internal static uint GetInterpolatedStringHandlerConversionEscapeScope( InterpolatedStringHandlerData data, uint scopeOfTheContainingExpression) => GetValEscape(data.Construction, scopeOfTheContainingExpression); /// <summary> /// Computes the scope to which the given invocation can escape /// NOTE: the escape scope for ref and val escapes is the same for invocations except for trivial cases (ordinary type returned by val) /// where escape is known otherwise. Therefore we do not have two ref/val variants of this. /// /// NOTE: we need scopeOfTheContainingExpression as some expressions such as optional <c>in</c> parameters or <c>ref dynamic</c> behave as /// local variables declared at the scope of the invocation. /// </summary> internal static uint GetInvocationEscapeScope( Symbol symbol, BoundExpression receiverOpt, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<BoundExpression> argsOpt, ImmutableArray<RefKind> argRefKindsOpt, ImmutableArray<int> argsToParamsOpt, uint scopeOfTheContainingExpression, bool isRefEscape ) { // SPEC: (also applies to the CheckInvocationEscape counterpart) // // An lvalue resulting from a ref-returning method invocation e1.M(e2, ...) is ref-safe - to - escape the smallest of the following scopes: //• The entire enclosing method //• the ref-safe-to-escape of all ref/out/in argument expressions(excluding the receiver) //• the safe-to - escape of all argument expressions(including the receiver) // // An rvalue resulting from a method invocation e1.M(e2, ...) is safe - to - escape from the smallest of the following scopes: //• The entire enclosing method //• the safe-to-escape of all argument expressions(including the receiver) // if (!symbol.RequiresInstanceReceiver()) { // ignore receiver when symbol is static receiverOpt = null; } //by default it is safe to escape uint escapeScope = Binder.ExternalScope; ArrayBuilder<bool> inParametersMatchedWithArgs = null; if (!argsOpt.IsDefault) { moreArguments: for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++) { var argument = argsOpt[argIndex]; if (argument.Kind == BoundKind.ArgListOperator) { Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last"); var argList = (BoundArgListOperator)argument; // unwrap varargs and process as more arguments argsOpt = argList.Arguments; // ref kinds of varargs are not interesting here. // __refvalue is not ref-returnable, so ref varargs can't come back from a call argRefKindsOpt = default; parameters = ImmutableArray<ParameterSymbol>.Empty; argsToParamsOpt = default; goto moreArguments; } RefKind effectiveRefKind = GetEffectiveRefKindAndMarkMatchedInParameter(argIndex, argRefKindsOpt, parameters, argsToParamsOpt, ref inParametersMatchedWithArgs); // ref escape scope is the narrowest of // - ref escape of all byref arguments // - val escape of all byval arguments (ref-like values can be unwrapped into refs, so treat val escape of values as possible ref escape of the result) // // val escape scope is the narrowest of // - val escape of all byval arguments (refs cannot be wrapped into values, so their ref escape is irrelevant, only use val escapes) var argEscape = effectiveRefKind != RefKind.None && isRefEscape ? GetRefEscape(argument, scopeOfTheContainingExpression) : GetValEscape(argument, scopeOfTheContainingExpression); escapeScope = Math.Max(escapeScope, argEscape); if (escapeScope >= scopeOfTheContainingExpression) { // no longer needed inParametersMatchedWithArgs?.Free(); // can't get any worse return escapeScope; } } } // handle omitted optional "in" parameters if there are any ParameterSymbol unmatchedInParameter = TryGetunmatchedInParameterAndFreeMatchedArgs(parameters, ref inParametersMatchedWithArgs); // unmatched "in" parameter is the same as a literal, its ref escape is scopeOfTheContainingExpression (can't get any worse) // its val escape is ExternalScope (does not affect overall result) if (unmatchedInParameter != null && isRefEscape) { return scopeOfTheContainingExpression; } // check receiver if ref-like if (receiverOpt?.Type?.IsRefLikeType == true) { escapeScope = Math.Max(escapeScope, GetValEscape(receiverOpt, scopeOfTheContainingExpression)); } return escapeScope; } /// <summary> /// Validates whether given invocation can allow its results to escape from <paramref name="escapeFrom"/> level to <paramref name="escapeTo"/> level. /// The result indicates whether the escape is possible. /// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure. /// /// NOTE: we need scopeOfTheContainingExpression as some expressions such as optional <c>in</c> parameters or <c>ref dynamic</c> behave as /// local variables declared at the scope of the invocation. /// </summary> private static bool CheckInvocationEscape( SyntaxNode syntax, Symbol symbol, BoundExpression receiverOpt, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<BoundExpression> argsOpt, ImmutableArray<RefKind> argRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool checkingReceiver, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics, bool isRefEscape ) { // SPEC: // In a method invocation, the following constraints apply: //• If there is a ref or out argument to a ref struct type (including the receiver), with safe-to-escape E1, then // o no ref or out argument(excluding the receiver and arguments of ref-like types) may have a narrower ref-safe-to-escape than E1; and // o no argument(including the receiver) may have a narrower safe-to-escape than E1. if (!symbol.RequiresInstanceReceiver()) { // ignore receiver when symbol is static receiverOpt = null; } ArrayBuilder<bool> inParametersMatchedWithArgs = null; if (!argsOpt.IsDefault) { moreArguments: for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++) { var argument = argsOpt[argIndex]; if (argument.Kind == BoundKind.ArgListOperator) { Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last"); var argList = (BoundArgListOperator)argument; // unwrap varargs and process as more arguments argsOpt = argList.Arguments; // ref kinds of varargs are not interesting here. // __refvalue is not ref-returnable, so ref varargs can't come back from a call argRefKindsOpt = default; parameters = ImmutableArray<ParameterSymbol>.Empty; argsToParamsOpt = default; goto moreArguments; } RefKind effectiveRefKind = GetEffectiveRefKindAndMarkMatchedInParameter(argIndex, argRefKindsOpt, parameters, argsToParamsOpt, ref inParametersMatchedWithArgs); // ref escape scope is the narrowest of // - ref escape of all byref arguments // - val escape of all byval arguments (ref-like values can be unwrapped into refs, so treat val escape of values as possible ref escape of the result) // // val escape scope is the narrowest of // - val escape of all byval arguments (refs cannot be wrapped into values, so their ref escape is irrelevant, only use val escapes) var valid = effectiveRefKind != RefKind.None && isRefEscape ? CheckRefEscape(argument.Syntax, argument, escapeFrom, escapeTo, false, diagnostics) : CheckValEscape(argument.Syntax, argument, escapeFrom, escapeTo, false, diagnostics); if (!valid) { // no longer needed inParametersMatchedWithArgs?.Free(); ErrorCode errorCode = GetStandardCallEscapeError(checkingReceiver); string parameterName; if (parameters.Length > 0) { var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex]; parameterName = parameters[paramIndex].Name; if (string.IsNullOrEmpty(parameterName)) { parameterName = paramIndex.ToString(); } } else { parameterName = "__arglist"; } Error(diagnostics, errorCode, syntax, symbol, parameterName); return false; } } } // handle omitted optional "in" parameters if there are any ParameterSymbol unmatchedInParameter = TryGetunmatchedInParameterAndFreeMatchedArgs(parameters, ref inParametersMatchedWithArgs); // unmatched "in" parameter is the same as a literal, its ref escape is scopeOfTheContainingExpression (can't get any worse) // its val escape is ExternalScope (does not affect overall result) if (unmatchedInParameter != null && isRefEscape) { var parameterName = unmatchedInParameter.Name; if (string.IsNullOrEmpty(parameterName)) { parameterName = unmatchedInParameter.Ordinal.ToString(); } Error(diagnostics, GetStandardCallEscapeError(checkingReceiver), syntax, symbol, parameterName); return false; } // check receiver if ref-like if (receiverOpt?.Type?.IsRefLikeType == true) { return CheckValEscape(receiverOpt.Syntax, receiverOpt, escapeFrom, escapeTo, false, diagnostics); } return true; } /// <summary> /// Validates whether the invocation is valid per no-mixing rules. /// Returns <see langword="false"/> when it is not valid and produces diagnostics (possibly more than one recursively) that helps to figure the reason. /// </summary> private static bool CheckInvocationArgMixing( SyntaxNode syntax, Symbol symbol, BoundExpression receiverOpt, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<BoundExpression> argsOpt, ImmutableArray<int> argsToParamsOpt, uint scopeOfTheContainingExpression, BindingDiagnosticBag diagnostics) { // SPEC: // In a method invocation, the following constraints apply: // - If there is a ref or out argument of a ref struct type (including the receiver), with safe-to-escape E1, then // - no argument (including the receiver) may have a narrower safe-to-escape than E1. if (!symbol.RequiresInstanceReceiver()) { // ignore receiver when symbol is static receiverOpt = null; } // widest possible escape via writeable ref-like receiver or ref/out argument. uint escapeTo = scopeOfTheContainingExpression; // collect all writeable ref-like arguments, including receiver var receiverType = receiverOpt?.Type; if (receiverType?.IsRefLikeType == true && !isReceiverRefReadOnly(symbol)) { escapeTo = GetValEscape(receiverOpt, scopeOfTheContainingExpression); } if (!argsOpt.IsDefault) { BoundArgListOperator argList = null; for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++) { var argument = argsOpt[argIndex]; if (argument.Kind == BoundKind.ArgListOperator) { Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last"); argList = (BoundArgListOperator)argument; break; } var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex]; if (parameters[paramIndex].RefKind.IsWritableReference() && argument.Type?.IsRefLikeType == true) { escapeTo = Math.Min(escapeTo, GetValEscape(argument, scopeOfTheContainingExpression)); } } if (argList != null) { var argListArgs = argList.Arguments; var argListRefKindsOpt = argList.ArgumentRefKindsOpt; for (var argIndex = 0; argIndex < argListArgs.Length; argIndex++) { var argument = argListArgs[argIndex]; var refKind = argListRefKindsOpt.IsDefault ? RefKind.None : argListRefKindsOpt[argIndex]; if (refKind.IsWritableReference() && argument.Type?.IsRefLikeType == true) { escapeTo = Math.Min(escapeTo, GetValEscape(argument, scopeOfTheContainingExpression)); } } } } if (escapeTo == scopeOfTheContainingExpression) { // cannot fail. common case. return true; } if (!argsOpt.IsDefault) { moreArguments: for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++) { // check val escape of all arguments var argument = argsOpt[argIndex]; if (argument.Kind == BoundKind.ArgListOperator) { Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last"); var argList = (BoundArgListOperator)argument; // unwrap varargs and process as more arguments argsOpt = argList.Arguments; parameters = ImmutableArray<ParameterSymbol>.Empty; argsToParamsOpt = default; goto moreArguments; } var valid = CheckValEscape(argument.Syntax, argument, scopeOfTheContainingExpression, escapeTo, false, diagnostics); if (!valid) { string parameterName; if (parameters.Length > 0) { var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex]; parameterName = parameters[paramIndex].Name; } else { parameterName = "__arglist"; } Error(diagnostics, ErrorCode.ERR_CallArgMixing, syntax, symbol, parameterName); return false; } } } //NB: we do not care about unmatched "in" parameters here. // They have "outer" val escape, so cannot be worse than escapeTo. // check val escape of receiver if ref-like if (receiverOpt?.Type?.IsRefLikeType == true) { return CheckValEscape(receiverOpt.Syntax, receiverOpt, scopeOfTheContainingExpression, escapeTo, false, diagnostics); } return true; static bool isReceiverRefReadOnly(Symbol methodOrPropertySymbol) => methodOrPropertySymbol switch { MethodSymbol m => m.IsEffectivelyReadOnly, // TODO: val escape checks should be skipped for property accesses when // we can determine the only accessors being called are readonly. // For now we are pessimistic and check escape if any accessor is non-readonly. // Tracking in https://github.com/dotnet/roslyn/issues/35606 PropertySymbol p => p.GetMethod?.IsEffectivelyReadOnly != false && p.SetMethod?.IsEffectivelyReadOnly != false, _ => throw ExceptionUtilities.UnexpectedValue(methodOrPropertySymbol) }; } /// <summary> /// Gets "effective" ref kind of an argument. /// If the ref kind is 'in', marks that that corresponding parameter was matched with a value /// We need that to detect when there were optional 'in' parameters for which values were not supplied. /// /// NOTE: Generally we know if a formal argument is passed as ref/out/in by looking at the call site. /// However, 'in' may also be passed as an ordinary val argument so we need to take a look at corresponding parameter, if such exists. /// There are cases like params/vararg, when a corresponding parameter may not exist, then val cannot become 'in'. /// </summary> private static RefKind GetEffectiveRefKindAndMarkMatchedInParameter( int argIndex, ImmutableArray<RefKind> argRefKindsOpt, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt, ref ArrayBuilder<bool> inParametersMatchedWithArgs) { var effectiveRefKind = argRefKindsOpt.IsDefault ? RefKind.None : argRefKindsOpt[argIndex]; if ((effectiveRefKind == RefKind.None || effectiveRefKind == RefKind.In) && argIndex < parameters.Length) { var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex]; if (parameters[paramIndex].RefKind == RefKind.In) { effectiveRefKind = RefKind.In; inParametersMatchedWithArgs = inParametersMatchedWithArgs ?? ArrayBuilder<bool>.GetInstance(parameters.Length, fillWithValue: false); inParametersMatchedWithArgs[paramIndex] = true; } } return effectiveRefKind; } /// <summary> /// Gets a "in" parameter for which there is no argument supplied, if such exists. /// That indicates an optional "in" parameter. We treat it as an RValue passed by reference via a temporary. /// The effective scope of such variable is the immediately containing scope. /// </summary> private static ParameterSymbol TryGetunmatchedInParameterAndFreeMatchedArgs(ImmutableArray<ParameterSymbol> parameters, ref ArrayBuilder<bool> inParametersMatchedWithArgs) { try { if (!parameters.IsDefault) { for (int i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; if (parameter.IsParams) { break; } if (parameter.RefKind == RefKind.In && inParametersMatchedWithArgs?[i] != true && parameter.Type.IsRefLikeType == false) { return parameter; } } } return null; } finally { inParametersMatchedWithArgs?.Free(); // make sure noone uses it after. inParametersMatchedWithArgs = null; } } private static ErrorCode GetStandardCallEscapeError(bool checkingReceiver) { return checkingReceiver ? ErrorCode.ERR_EscapeCall2 : ErrorCode.ERR_EscapeCall; } private static void ReportReadonlyLocalError(SyntaxNode node, LocalSymbol local, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert((object)local != null); Debug.Assert(kind != BindValueKind.RValue); MessageID cause; if (local.IsForEach) { cause = MessageID.IDS_FOREACHLOCAL; } else if (local.IsUsing) { cause = MessageID.IDS_USINGLOCAL; } else if (local.IsFixed) { cause = MessageID.IDS_FIXEDLOCAL; } else { Error(diagnostics, GetStandardLvalueError(kind), node); return; } ErrorCode[] ReadOnlyLocalErrors = { ErrorCode.ERR_RefReadonlyLocalCause, ErrorCode.ERR_AssgReadonlyLocalCause, ErrorCode.ERR_RefReadonlyLocal2Cause, ErrorCode.ERR_AssgReadonlyLocal2Cause }; int index = (checkingReceiver ? 2 : 0) + (RequiresRefOrOut(kind) ? 0 : 1); Error(diagnostics, ReadOnlyLocalErrors[index], node, local, cause.Localize()); } private static ErrorCode GetThisLvalueError(BindValueKind kind, bool isValueType) { switch (kind) { case BindValueKind.CompoundAssignment: case BindValueKind.Assignable: return ErrorCode.ERR_AssgReadonlyLocal; case BindValueKind.RefOrOut: return ErrorCode.ERR_RefReadonlyLocal; case BindValueKind.AddressOf: return ErrorCode.ERR_InvalidAddrOp; case BindValueKind.IncrementDecrement: return isValueType ? ErrorCode.ERR_AssgReadonlyLocal : ErrorCode.ERR_IncrementLvalueExpected; case BindValueKind.RefReturn: case BindValueKind.ReadonlyRef: return ErrorCode.ERR_RefReturnThis; case BindValueKind.RefAssignable: return ErrorCode.ERR_RefLocalOrParamExpected; } if (RequiresReferenceToLocation(kind)) { return ErrorCode.ERR_RefLvalueExpected; } throw ExceptionUtilities.UnexpectedValue(kind); } private static ErrorCode GetRangeLvalueError(BindValueKind kind) { switch (kind) { case BindValueKind.Assignable: case BindValueKind.CompoundAssignment: case BindValueKind.IncrementDecrement: return ErrorCode.ERR_QueryRangeVariableReadOnly; case BindValueKind.AddressOf: return ErrorCode.ERR_InvalidAddrOp; case BindValueKind.RefReturn: case BindValueKind.ReadonlyRef: return ErrorCode.ERR_RefReturnRangeVariable; case BindValueKind.RefAssignable: return ErrorCode.ERR_RefLocalOrParamExpected; } if (RequiresReferenceToLocation(kind)) { return ErrorCode.ERR_QueryOutRefRangeVariable; } throw ExceptionUtilities.UnexpectedValue(kind); } private static ErrorCode GetMethodGroupOrFunctionPointerLvalueError(BindValueKind valueKind) { if (RequiresReferenceToLocation(valueKind)) { return ErrorCode.ERR_RefReadonlyLocalCause; } // Cannot assign to 'W' because it is a 'method group' return ErrorCode.ERR_AssgReadonlyLocalCause; } private static ErrorCode GetStandardLvalueError(BindValueKind kind) { switch (kind) { case BindValueKind.CompoundAssignment: case BindValueKind.Assignable: return ErrorCode.ERR_AssgLvalueExpected; case BindValueKind.AddressOf: return ErrorCode.ERR_InvalidAddrOp; case BindValueKind.IncrementDecrement: return ErrorCode.ERR_IncrementLvalueExpected; case BindValueKind.FixedReceiver: return ErrorCode.ERR_FixedNeedsLvalue; case BindValueKind.RefReturn: case BindValueKind.ReadonlyRef: return ErrorCode.ERR_RefReturnLvalueExpected; case BindValueKind.RefAssignable: return ErrorCode.ERR_RefLocalOrParamExpected; } if (RequiresReferenceToLocation(kind)) { return ErrorCode.ERR_RefLvalueExpected; } throw ExceptionUtilities.UnexpectedValue(kind); } private static ErrorCode GetStandardRValueRefEscapeError(uint escapeTo) { if (escapeTo == Binder.ExternalScope) { return ErrorCode.ERR_RefReturnLvalueExpected; } return ErrorCode.ERR_EscapeOther; } private static void ReportReadOnlyFieldError(FieldSymbol field, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert((object)field != null); Debug.Assert(RequiresAssignableVariable(kind)); Debug.Assert(field.Type != (object)null); // It's clearer to say that the address can't be taken than to say that the field can't be modified // (even though the latter message gives more explanation of why). if (kind == BindValueKind.AddressOf) { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, node); return; } ErrorCode[] ReadOnlyErrors = { ErrorCode.ERR_RefReturnReadonly, ErrorCode.ERR_RefReadonly, ErrorCode.ERR_AssgReadonly, ErrorCode.ERR_RefReturnReadonlyStatic, ErrorCode.ERR_RefReadonlyStatic, ErrorCode.ERR_AssgReadonlyStatic, ErrorCode.ERR_RefReturnReadonly2, ErrorCode.ERR_RefReadonly2, ErrorCode.ERR_AssgReadonly2, ErrorCode.ERR_RefReturnReadonlyStatic2, ErrorCode.ERR_RefReadonlyStatic2, ErrorCode.ERR_AssgReadonlyStatic2 }; int index = (checkingReceiver ? 6 : 0) + (field.IsStatic ? 3 : 0) + (kind == BindValueKind.RefReturn ? 0 : (RequiresRefOrOut(kind) ? 1 : 2)); if (checkingReceiver) { Error(diagnostics, ReadOnlyErrors[index], node, field); } else { Error(diagnostics, ReadOnlyErrors[index], node); } } private static void ReportReadOnlyError(Symbol symbol, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert((object)symbol != null); Debug.Assert(RequiresAssignableVariable(kind)); // It's clearer to say that the address can't be taken than to say that the parameter can't be modified // (even though the latter message gives more explanation of why). if (kind == BindValueKind.AddressOf) { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, node); return; } var symbolKind = symbol.Kind.Localize(); ErrorCode[] ReadOnlyErrors = { ErrorCode.ERR_RefReturnReadonlyNotField, ErrorCode.ERR_RefReadonlyNotField, ErrorCode.ERR_AssignReadonlyNotField, ErrorCode.ERR_RefReturnReadonlyNotField2, ErrorCode.ERR_RefReadonlyNotField2, ErrorCode.ERR_AssignReadonlyNotField2, }; int index = (checkingReceiver ? 3 : 0) + (kind == BindValueKind.RefReturn ? 0 : (RequiresRefOrOut(kind) ? 1 : 2)); Error(diagnostics, ReadOnlyErrors[index], node, symbolKind, symbol); } /// <summary> /// Checks whether given expression can escape from the current scope to the <paramref name="escapeTo"/> /// In a case if it cannot a bad expression is returned and diagnostics is produced. /// </summary> internal BoundExpression ValidateEscape(BoundExpression expr, uint escapeTo, bool isByRef, BindingDiagnosticBag diagnostics) { if (isByRef) { if (CheckRefEscape(expr.Syntax, expr, this.LocalScopeDepth, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return expr; } } else { if (CheckValEscape(expr.Syntax, expr, this.LocalScopeDepth, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return expr; } } return ToBadExpression(expr); } /// <summary> /// Computes the widest scope depth to which the given expression can escape by reference. /// /// NOTE: in a case if expression cannot be passed by an alias (RValue and similar), the ref-escape is scopeOfTheContainingExpression /// There are few cases where RValues are permitted to be passed by reference which implies that a temporary local proxy is passed instead. /// We reflect such behavior by constraining the escape value to the narrowest scope possible. /// </summary> internal static uint GetRefEscape(BoundExpression expr, uint scopeOfTheContainingExpression) { // cannot infer anything from errors if (expr.HasAnyErrors) { return Binder.ExternalScope; } // cannot infer anything from Void (broken code) if (expr.Type?.GetSpecialTypeSafe() == SpecialType.System_Void) { return Binder.ExternalScope; } // constants/literals cannot ref-escape current scope if (expr.ConstantValue != null) { return scopeOfTheContainingExpression; } // cover case that cannot refer to local state // otherwise default to current scope (RValues, etc) switch (expr.Kind) { case BoundKind.ArrayAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: // array elements and pointer dereferencing are readwrite variables return Binder.ExternalScope; case BoundKind.RefValueOperator: // The undocumented __refvalue(tr, T) expression results in an lvalue of type T. // for compat reasons it is not ref-returnable (since TypedReference is not val-returnable) // it can, however, ref-escape to any other level (since TypedReference can val-escape to any other level) return Binder.TopLevelScope; case BoundKind.DiscardExpression: // same as write-only byval local break; case BoundKind.DynamicMemberAccess: case BoundKind.DynamicIndexerAccess: // dynamic expressions can be read and written to // can even be passed by reference (which is implemented via a temp) // it is not valid to escape them by reference though, so treat them as RValues here break; case BoundKind.Parameter: var parameter = ((BoundParameter)expr).ParameterSymbol; // byval parameters can escape to method's top level. Others can escape further. // NOTE: "method" here means nearest containing method, lambda or local function. return parameter.RefKind == RefKind.None ? Binder.TopLevelScope : Binder.ExternalScope; case BoundKind.Local: return ((BoundLocal)expr).LocalSymbol.RefEscapeScope; case BoundKind.ThisReference: var thisref = (BoundThisReference)expr; // "this" is an RValue, unless in a struct. if (!thisref.Type.IsValueType) { break; } //"this" is not returnable by reference in a struct. // can ref escape to any other level return Binder.TopLevelScope; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expr; if (conditional.IsRef) { // ref conditional defers to its operands return Math.Max(GetRefEscape(conditional.Consequence, scopeOfTheContainingExpression), GetRefEscape(conditional.Alternative, scopeOfTheContainingExpression)); } // otherwise it is an RValue break; case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; // fields that are static or belong to reference types can ref escape anywhere if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType) { return Binder.ExternalScope; } // for other fields defer to the receiver. return GetRefEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression); case BoundKind.EventAccess: var eventAccess = (BoundEventAccess)expr; if (!eventAccess.IsUsableAsField) { // not field-like events are RValues break; } var eventSymbol = eventAccess.EventSymbol; // field-like events that are static or belong to reference types can ref escape anywhere if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType) { return Binder.ExternalScope; } // for other events defer to the receiver. return GetRefEscape(eventAccess.ReceiverOpt, scopeOfTheContainingExpression); case BoundKind.Call: var call = (BoundCall)expr; var methodSymbol = call.Method; if (methodSymbol.RefKind == RefKind.None) { break; } return GetInvocationEscapeScope( call.Method, call.ReceiverOpt, methodSymbol.Parameters, call.Arguments, call.ArgumentRefKindsOpt, call.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: true); case BoundKind.FunctionPointerInvocation: var ptrInvocation = (BoundFunctionPointerInvocation)expr; methodSymbol = ptrInvocation.FunctionPointer.Signature; if (methodSymbol.RefKind == RefKind.None) { break; } return GetInvocationEscapeScope( methodSymbol, receiverOpt: null, methodSymbol.Parameters, ptrInvocation.Arguments, ptrInvocation.ArgumentRefKindsOpt, argsToParamsOpt: default, scopeOfTheContainingExpression, isRefEscape: true); case BoundKind.IndexerAccess: var indexerAccess = (BoundIndexerAccess)expr; var indexerSymbol = indexerAccess.Indexer; return GetInvocationEscapeScope( indexerSymbol, indexerAccess.ReceiverOpt, indexerSymbol.Parameters, indexerAccess.Arguments, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: true); case BoundKind.PropertyAccess: var propertyAccess = (BoundPropertyAccess)expr; // not passing any arguments/parameters return GetInvocationEscapeScope( propertyAccess.PropertySymbol, propertyAccess.ReceiverOpt, default, default, default, default, scopeOfTheContainingExpression, isRefEscape: true); case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expr; if (!assignment.IsRef) { // non-ref assignments are RValues break; } return GetRefEscape(assignment.Left, scopeOfTheContainingExpression); } // At this point we should have covered all the possible cases for anything that is not a strict RValue. return scopeOfTheContainingExpression; } /// <summary> /// A counterpart to the GetRefEscape, which validates if given escape demand can be met by the expression. /// The result indicates whether the escape is possible. /// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure. /// </summary> internal static bool CheckRefEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter()); if (escapeTo >= escapeFrom) { // escaping to same or narrower scope is ok. return true; } if (expr.HasAnyErrors) { // already an error return true; } // void references cannot escape (error should be reported somewhere) if (expr.Type?.GetSpecialTypeSafe() == SpecialType.System_Void) { return true; } // references to constants/literals cannot escape higher. if (expr.ConstantValue != null) { Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), node); return false; } switch (expr.Kind) { case BoundKind.ArrayAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: // array elements and pointer dereferencing are readwrite variables return true; case BoundKind.RefValueOperator: // The undocumented __refvalue(tr, T) expression results in an lvalue of type T. // for compat reasons it is not ref-returnable (since TypedReference is not val-returnable) if (escapeTo == Binder.ExternalScope) { break; } // it can, however, ref-escape to any other level (since TypedReference can val-escape to any other level) return true; case BoundKind.DiscardExpression: // same as write-only byval local break; case BoundKind.DynamicMemberAccess: case BoundKind.DynamicIndexerAccess: // dynamic expressions can be read and written to // can even be passed by reference (which is implemented via a temp) // it is not valid to escape them by reference though. break; case BoundKind.Parameter: var parameter = (BoundParameter)expr; return CheckParameterRefEscape(node, parameter, escapeTo, checkingReceiver, diagnostics); case BoundKind.Local: var local = (BoundLocal)expr; return CheckLocalRefEscape(node, local, escapeTo, checkingReceiver, diagnostics); case BoundKind.ThisReference: var thisref = (BoundThisReference)expr; // "this" is an RValue, unless in a struct. if (!thisref.Type.IsValueType) { break; } //"this" is not returnable by reference in a struct. if (escapeTo == Binder.ExternalScope) { Error(diagnostics, ErrorCode.ERR_RefReturnStructThis, node, ThisParameterSymbol.SymbolName); return false; } // can ref escape to any other level return true; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expr; if (conditional.IsRef) { return CheckRefEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckRefEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); } // report standard lvalue error break; case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; return CheckFieldRefEscape(node, fieldAccess, escapeFrom, escapeTo, diagnostics); case BoundKind.EventAccess: var eventAccess = (BoundEventAccess)expr; if (!eventAccess.IsUsableAsField) { // not field-like events are RValues break; } return CheckFieldLikeEventRefEscape(node, eventAccess, escapeFrom, escapeTo, diagnostics); case BoundKind.Call: var call = (BoundCall)expr; var methodSymbol = call.Method; if (methodSymbol.RefKind == RefKind.None) { break; } return CheckInvocationEscape( call.Syntax, methodSymbol, call.ReceiverOpt, methodSymbol.Parameters, call.Arguments, call.ArgumentRefKindsOpt, call.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.IndexerAccess: var indexerAccess = (BoundIndexerAccess)expr; var indexerSymbol = indexerAccess.Indexer; if (indexerSymbol.RefKind == RefKind.None) { break; } return CheckInvocationEscape( indexerAccess.Syntax, indexerSymbol, indexerAccess.ReceiverOpt, indexerSymbol.Parameters, indexerAccess.Arguments, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; RefKind refKind; ImmutableArray<ParameterSymbol> parameters; switch (patternIndexer.PatternSymbol) { case PropertySymbol p: refKind = p.RefKind; parameters = p.Parameters; break; case MethodSymbol m: refKind = m.RefKind; parameters = m.Parameters; break; default: throw ExceptionUtilities.Unreachable; } if (refKind == RefKind.None) { break; } return CheckInvocationEscape( patternIndexer.Syntax, patternIndexer.PatternSymbol, patternIndexer.Receiver, parameters, ImmutableArray.Create<BoundExpression>(patternIndexer.Argument), default, default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.FunctionPointerInvocation: var functionPointerInvocation = (BoundFunctionPointerInvocation)expr; FunctionPointerMethodSymbol signature = functionPointerInvocation.FunctionPointer.Signature; if (signature.RefKind == RefKind.None) { break; } return CheckInvocationEscape( functionPointerInvocation.Syntax, signature, functionPointerInvocation.InvokedExpression, signature.Parameters, functionPointerInvocation.Arguments, functionPointerInvocation.ArgumentRefKindsOpt, argsToParamsOpt: default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.PropertyAccess: var propertyAccess = (BoundPropertyAccess)expr; var propertySymbol = propertyAccess.PropertySymbol; if (propertySymbol.RefKind == RefKind.None) { break; } // not passing any arguments/parameters return CheckInvocationEscape( propertyAccess.Syntax, propertySymbol, propertyAccess.ReceiverOpt, default, default, default, default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expr; // Only ref-assignments can be LValues if (!assignment.IsRef) { break; } return CheckRefEscape( node, assignment.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); } // At this point we should have covered all the possible cases for anything that is not a strict RValue. Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), node); return false; } internal static uint GetBroadestValEscape(BoundTupleExpression expr, uint scopeOfTheContainingExpression) { uint broadest = scopeOfTheContainingExpression; foreach (var element in expr.Arguments) { uint valEscape; if (element is BoundTupleExpression te) { valEscape = GetBroadestValEscape(te, scopeOfTheContainingExpression); } else { valEscape = GetValEscape(element, scopeOfTheContainingExpression); } broadest = Math.Min(broadest, valEscape); } return broadest; } /// <summary> /// Computes the widest scope depth to which the given expression can escape by value. /// /// NOTE: unless the type of expression is ref-like, the result is Binder.ExternalScope since ordinary values can always be returned from methods. /// </summary> internal static uint GetValEscape(BoundExpression expr, uint scopeOfTheContainingExpression) { // cannot infer anything from errors if (expr.HasAnyErrors) { return Binder.ExternalScope; } // constants/literals cannot refer to local state if (expr.ConstantValue != null) { return Binder.ExternalScope; } // to have local-referring values an expression must have a ref-like type if (expr.Type?.IsRefLikeType != true) { return Binder.ExternalScope; } // cover case that can refer to local state // otherwise default to ExternalScope (ordinary values) switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Parameter: case BoundKind.ThisReference: // always returnable return Binder.ExternalScope; case BoundKind.FromEndIndexExpression: // We are going to call a constructor that takes an integer and a bool. Cannot leak any references through them. // always returnable return Binder.ExternalScope; case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: var tupleLiteral = (BoundTupleExpression)expr; return GetTupleValEscape(tupleLiteral.Arguments, scopeOfTheContainingExpression); case BoundKind.MakeRefOperator: case BoundKind.RefValueOperator: // for compat reasons // NB: it also means can`t assign stackalloc spans to a __refvalue // we are ok with that. return Binder.ExternalScope; case BoundKind.DiscardExpression: return ((BoundDiscardExpression)expr).ValEscape; case BoundKind.DeconstructValuePlaceholder: return ((BoundDeconstructValuePlaceholder)expr).ValEscape; case BoundKind.Local: return ((BoundLocal)expr).LocalSymbol.ValEscapeScope; case BoundKind.StackAllocArrayCreation: case BoundKind.ConvertedStackAllocExpression: return Binder.TopLevelScope; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expr; var consEscape = GetValEscape(conditional.Consequence, scopeOfTheContainingExpression); if (conditional.IsRef) { // ref conditional defers to one operand. // the other one is the same or we will be reporting errors anyways. return consEscape; } // val conditional gets narrowest of its operands return Math.Max(consEscape, GetValEscape(conditional.Alternative, scopeOfTheContainingExpression)); case BoundKind.NullCoalescingOperator: var coalescingOp = (BoundNullCoalescingOperator)expr; return Math.Max(GetValEscape(coalescingOp.LeftOperand, scopeOfTheContainingExpression), GetValEscape(coalescingOp.RightOperand, scopeOfTheContainingExpression)); case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType) { // Already an error state. return Binder.ExternalScope; } // for ref-like fields defer to the receiver. return GetValEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression); case BoundKind.Call: var call = (BoundCall)expr; return GetInvocationEscapeScope( call.Method, call.ReceiverOpt, call.Method.Parameters, call.Arguments, call.ArgumentRefKindsOpt, call.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.FunctionPointerInvocation: var ptrInvocation = (BoundFunctionPointerInvocation)expr; var ptrSymbol = ptrInvocation.FunctionPointer.Signature; return GetInvocationEscapeScope( ptrSymbol, receiverOpt: null, ptrSymbol.Parameters, ptrInvocation.Arguments, ptrInvocation.ArgumentRefKindsOpt, argsToParamsOpt: default, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.IndexerAccess: var indexerAccess = (BoundIndexerAccess)expr; var indexerSymbol = indexerAccess.Indexer; return GetInvocationEscapeScope( indexerSymbol, indexerAccess.ReceiverOpt, indexerSymbol.Parameters, indexerAccess.Arguments, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; var parameters = patternIndexer.PatternSymbol switch { PropertySymbol p => p.Parameters, MethodSymbol m => m.Parameters, _ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol) }; return GetInvocationEscapeScope( patternIndexer.PatternSymbol, patternIndexer.Receiver, parameters, default, default, default, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.PropertyAccess: var propertyAccess = (BoundPropertyAccess)expr; // not passing any arguments/parameters return GetInvocationEscapeScope( propertyAccess.PropertySymbol, propertyAccess.ReceiverOpt, default, default, default, default, scopeOfTheContainingExpression, isRefEscape: false); case BoundKind.ObjectCreationExpression: var objectCreation = (BoundObjectCreationExpression)expr; var constructorSymbol = objectCreation.Constructor; var escape = GetInvocationEscapeScope( constructorSymbol, null, constructorSymbol.Parameters, objectCreation.Arguments, objectCreation.ArgumentRefKindsOpt, objectCreation.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); var initializerOpt = objectCreation.InitializerExpressionOpt; if (initializerOpt != null) { escape = Math.Max(escape, GetValEscape(initializerOpt, scopeOfTheContainingExpression)); } return escape; case BoundKind.WithExpression: var withExpression = (BoundWithExpression)expr; return Math.Max(GetValEscape(withExpression.Receiver, scopeOfTheContainingExpression), GetValEscape(withExpression.InitializerExpression, scopeOfTheContainingExpression)); case BoundKind.UnaryOperator: return GetValEscape(((BoundUnaryOperator)expr).Operand, scopeOfTheContainingExpression); case BoundKind.Conversion: var conversion = (BoundConversion)expr; Debug.Assert(conversion.ConversionKind != ConversionKind.StackAllocToSpanType, "StackAllocToSpanType unexpected"); if (conversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { var data = conversion.Operand switch { BoundInterpolatedString { InterpolationData: { } d } => d, BoundBinaryOperator { InterpolatedStringHandlerData: { } d } => d, _ => throw ExceptionUtilities.UnexpectedValue(conversion.Operand.Kind) }; return GetInterpolatedStringHandlerConversionEscapeScope(data, scopeOfTheContainingExpression); } return GetValEscape(conversion.Operand, scopeOfTheContainingExpression); case BoundKind.AssignmentOperator: return GetValEscape(((BoundAssignmentOperator)expr).Right, scopeOfTheContainingExpression); case BoundKind.IncrementOperator: return GetValEscape(((BoundIncrementOperator)expr).Operand, scopeOfTheContainingExpression); case BoundKind.CompoundAssignmentOperator: var compound = (BoundCompoundAssignmentOperator)expr; return Math.Max(GetValEscape(compound.Left, scopeOfTheContainingExpression), GetValEscape(compound.Right, scopeOfTheContainingExpression)); case BoundKind.BinaryOperator: var binary = (BoundBinaryOperator)expr; return Math.Max(GetValEscape(binary.Left, scopeOfTheContainingExpression), GetValEscape(binary.Right, scopeOfTheContainingExpression)); case BoundKind.RangeExpression: var range = (BoundRangeExpression)expr; return Math.Max((range.LeftOperandOpt is { } left ? GetValEscape(left, scopeOfTheContainingExpression) : Binder.ExternalScope), (range.RightOperandOpt is { } right ? GetValEscape(right, scopeOfTheContainingExpression) : Binder.ExternalScope)); case BoundKind.UserDefinedConditionalLogicalOperator: var uo = (BoundUserDefinedConditionalLogicalOperator)expr; return Math.Max(GetValEscape(uo.Left, scopeOfTheContainingExpression), GetValEscape(uo.Right, scopeOfTheContainingExpression)); case BoundKind.QueryClause: return GetValEscape(((BoundQueryClause)expr).Value, scopeOfTheContainingExpression); case BoundKind.RangeVariable: return GetValEscape(((BoundRangeVariable)expr).Value, scopeOfTheContainingExpression); case BoundKind.ObjectInitializerExpression: var initExpr = (BoundObjectInitializerExpression)expr; return GetValEscapeOfObjectInitializer(initExpr, scopeOfTheContainingExpression); case BoundKind.CollectionInitializerExpression: var colExpr = (BoundCollectionInitializerExpression)expr; return GetValEscape(colExpr.Initializers, scopeOfTheContainingExpression); case BoundKind.CollectionElementInitializer: var colElement = (BoundCollectionElementInitializer)expr; return GetValEscape(colElement.Arguments, scopeOfTheContainingExpression); case BoundKind.ObjectInitializerMember: // this node generally makes no sense outside of the context of containing initializer // however binder uses it as a placeholder when binding assignments inside an object initializer // just say it does not escape anywhere, so that we do not get false errors. return scopeOfTheContainingExpression; case BoundKind.ImplicitReceiver: case BoundKind.ObjectOrCollectionValuePlaceholder: // binder uses this as a placeholder when binding members inside an object initializer // just say it does not escape anywhere, so that we do not get false errors. return scopeOfTheContainingExpression; case BoundKind.InterpolatedStringHandlerPlaceholder: // The handler placeholder cannot escape out of the current expression, as it's a compiler-synthesized // location. return scopeOfTheContainingExpression; case BoundKind.InterpolatedStringArgumentPlaceholder: // We saved off the safe-to-escape of the argument when we did binding return ((BoundInterpolatedStringArgumentPlaceholder)expr).ValSafeToEscape; case BoundKind.DisposableValuePlaceholder: // Disposable value placeholder is only ever used to lookup a pattern dispose method // then immediately discarded. The actual expression will be generated during lowering return scopeOfTheContainingExpression; case BoundKind.AwaitableValuePlaceholder: return ((BoundAwaitableValuePlaceholder)expr).ValEscape; case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: // Unsafe code will always be allowed to escape. return Binder.ExternalScope; case BoundKind.AsOperator: case BoundKind.AwaitExpression: case BoundKind.ConditionalAccess: case BoundKind.ArrayAccess: // only possible in error cases (if possible at all) return scopeOfTheContainingExpression; case BoundKind.ConvertedSwitchExpression: case BoundKind.UnconvertedSwitchExpression: var switchExpr = (BoundSwitchExpression)expr; return GetValEscape(switchExpr.SwitchArms.SelectAsArray(a => a.Value), scopeOfTheContainingExpression); default: // in error situations some unexpected nodes could make here // returning "scopeOfTheContainingExpression" seems safer than throwing. // we will still assert to make sure that all nodes are accounted for. Debug.Assert(false, $"{expr.Kind} expression of {expr.Type} type"); return scopeOfTheContainingExpression; } } private static uint GetTupleValEscape(ImmutableArray<BoundExpression> elements, uint scopeOfTheContainingExpression) { uint narrowestScope = scopeOfTheContainingExpression; foreach (var element in elements) { narrowestScope = Math.Max(narrowestScope, GetValEscape(element, scopeOfTheContainingExpression)); } return narrowestScope; } private static uint GetValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint scopeOfTheContainingExpression) { var result = Binder.ExternalScope; foreach (var expression in initExpr.Initializers) { if (expression.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expression; result = Math.Max(result, GetValEscape(assignment.Right, scopeOfTheContainingExpression)); var left = (BoundObjectInitializerMember)assignment.Left; result = Math.Max(result, GetValEscape(left.Arguments, scopeOfTheContainingExpression)); } else { result = Math.Max(result, GetValEscape(expression, scopeOfTheContainingExpression)); } } return result; } private static uint GetValEscape(ImmutableArray<BoundExpression> expressions, uint scopeOfTheContainingExpression) { var result = Binder.ExternalScope; foreach (var expression in expressions) { result = Math.Max(result, GetValEscape(expression, scopeOfTheContainingExpression)); } return result; } /// <summary> /// A counterpart to the GetValEscape, which validates if given escape demand can be met by the expression. /// The result indicates whether the escape is possible. /// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure. /// </summary> internal static bool CheckValEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter()); if (escapeTo >= escapeFrom) { // escaping to same or narrower scope is ok. return true; } // cannot infer anything from errors if (expr.HasAnyErrors) { return true; } // constants/literals cannot refer to local state if (expr.ConstantValue != null) { return true; } // to have local-referring values an expression must have a ref-like type if (expr.Type?.IsRefLikeType != true) { return true; } switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Parameter: case BoundKind.ThisReference: // always returnable return true; case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: var tupleLiteral = (BoundTupleExpression)expr; return CheckTupleValEscape(tupleLiteral.Arguments, escapeFrom, escapeTo, diagnostics); case BoundKind.MakeRefOperator: case BoundKind.RefValueOperator: // for compat reasons return true; case BoundKind.DiscardExpression: // same as uninitialized local return true; case BoundKind.DeconstructValuePlaceholder: if (((BoundDeconstructValuePlaceholder)expr).ValEscape > escapeTo) { Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax); return false; } return true; case BoundKind.AwaitableValuePlaceholder: if (((BoundAwaitableValuePlaceholder)expr).ValEscape > escapeTo) { Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax); return false; } return true; case BoundKind.InterpolatedStringArgumentPlaceholder: if (((BoundInterpolatedStringArgumentPlaceholder)expr).ValSafeToEscape > escapeTo) { Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax); return false; } return true; case BoundKind.Local: var localSymbol = ((BoundLocal)expr).LocalSymbol; if (localSymbol.ValEscapeScope > escapeTo) { Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol); return false; } return true; case BoundKind.StackAllocArrayCreation: case BoundKind.ConvertedStackAllocExpression: if (escapeTo < Binder.TopLevelScope) { Error(diagnostics, ErrorCode.ERR_EscapeStackAlloc, node, expr.Type); return false; } return true; case BoundKind.UnconvertedConditionalOperator: { var conditional = (BoundUnconvertedConditionalOperator)expr; return CheckValEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckValEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); } case BoundKind.ConditionalOperator: { var conditional = (BoundConditionalOperator)expr; var consValid = CheckValEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); if (!consValid || conditional.IsRef) { // ref conditional defers to one operand. // the other one is the same or we will be reporting errors anyways. return consValid; } return CheckValEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); } case BoundKind.NullCoalescingOperator: var coalescingOp = (BoundNullCoalescingOperator)expr; return CheckValEscape(coalescingOp.LeftOperand.Syntax, coalescingOp.LeftOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics) && CheckValEscape(coalescingOp.RightOperand.Syntax, coalescingOp.RightOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics); case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType) { // Already an error state. return true; } // for ref-like fields defer to the receiver. return CheckValEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, true, diagnostics); case BoundKind.Call: var call = (BoundCall)expr; var methodSymbol = call.Method; return CheckInvocationEscape( call.Syntax, methodSymbol, call.ReceiverOpt, methodSymbol.Parameters, call.Arguments, call.ArgumentRefKindsOpt, call.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.FunctionPointerInvocation: var ptrInvocation = (BoundFunctionPointerInvocation)expr; var ptrSymbol = ptrInvocation.FunctionPointer.Signature; return CheckInvocationEscape( ptrInvocation.Syntax, ptrSymbol, receiverOpt: null, ptrSymbol.Parameters, ptrInvocation.Arguments, ptrInvocation.ArgumentRefKindsOpt, argsToParamsOpt: default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.IndexerAccess: var indexerAccess = (BoundIndexerAccess)expr; var indexerSymbol = indexerAccess.Indexer; return CheckInvocationEscape( indexerAccess.Syntax, indexerSymbol, indexerAccess.ReceiverOpt, indexerSymbol.Parameters, indexerAccess.Arguments, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; var patternSymbol = patternIndexer.PatternSymbol; var parameters = patternSymbol switch { PropertySymbol p => p.Parameters, MethodSymbol m => m.Parameters, _ => throw ExceptionUtilities.Unreachable, }; return CheckInvocationEscape( patternIndexer.Syntax, patternSymbol, patternIndexer.Receiver, parameters, ImmutableArray.Create(patternIndexer.Argument), default, default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.PropertyAccess: var propertyAccess = (BoundPropertyAccess)expr; // not passing any arguments/parameters return CheckInvocationEscape( propertyAccess.Syntax, propertyAccess.PropertySymbol, propertyAccess.ReceiverOpt, default, default, default, default, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); case BoundKind.ObjectCreationExpression: { var objectCreation = (BoundObjectCreationExpression)expr; var constructorSymbol = objectCreation.Constructor; var escape = CheckInvocationEscape( objectCreation.Syntax, constructorSymbol, null, constructorSymbol.Parameters, objectCreation.Arguments, objectCreation.ArgumentRefKindsOpt, objectCreation.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); var initializerExpr = objectCreation.InitializerExpressionOpt; if (initializerExpr != null) { escape = escape && CheckValEscape( initializerExpr.Syntax, initializerExpr, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); } return escape; } case BoundKind.WithExpression: { var withExpr = (BoundWithExpression)expr; var escape = CheckValEscape(node, withExpr.Receiver, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); var initializerExpr = withExpr.InitializerExpression; escape = escape && CheckValEscape(initializerExpr.Syntax, initializerExpr, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); return escape; } case BoundKind.UnaryOperator: var unary = (BoundUnaryOperator)expr; return CheckValEscape(node, unary.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.FromEndIndexExpression: // We are going to call a constructor that takes an integer and a bool. Cannot leak any references through them. return true; case BoundKind.Conversion: var conversion = (BoundConversion)expr; Debug.Assert(conversion.ConversionKind != ConversionKind.StackAllocToSpanType, "StackAllocToSpanType unexpected"); if (conversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { return CheckInterpolatedStringHandlerConversionEscape(conversion.Operand, escapeFrom, escapeTo, diagnostics); } return CheckValEscape(node, conversion.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expr; return CheckValEscape(node, assignment.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.IncrementOperator: var increment = (BoundIncrementOperator)expr; return CheckValEscape(node, increment.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.CompoundAssignmentOperator: var compound = (BoundCompoundAssignmentOperator)expr; return CheckValEscape(compound.Left.Syntax, compound.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckValEscape(compound.Right.Syntax, compound.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.BinaryOperator: var binary = (BoundBinaryOperator)expr; return CheckValEscape(binary.Left.Syntax, binary.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckValEscape(binary.Right.Syntax, binary.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.RangeExpression: var range = (BoundRangeExpression)expr; if (range.LeftOperandOpt is { } left && !CheckValEscape(left.Syntax, left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } return !(range.RightOperandOpt is { } right && !CheckValEscape(right.Syntax, right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)); case BoundKind.UserDefinedConditionalLogicalOperator: var uo = (BoundUserDefinedConditionalLogicalOperator)expr; return CheckValEscape(uo.Left.Syntax, uo.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) && CheckValEscape(uo.Right.Syntax, uo.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.QueryClause: var clauseValue = ((BoundQueryClause)expr).Value; return CheckValEscape(clauseValue.Syntax, clauseValue, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.RangeVariable: var variableValue = ((BoundRangeVariable)expr).Value; return CheckValEscape(variableValue.Syntax, variableValue, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.ObjectInitializerExpression: var initExpr = (BoundObjectInitializerExpression)expr; return CheckValEscapeOfObjectInitializer(initExpr, escapeFrom, escapeTo, diagnostics); // this would be correct implementation for CollectionInitializerExpression // however it is unclear if it is reachable since the initialized type must implement IEnumerable case BoundKind.CollectionInitializerExpression: var colExpr = (BoundCollectionInitializerExpression)expr; return CheckValEscape(colExpr.Initializers, escapeFrom, escapeTo, diagnostics); // this would be correct implementation for CollectionElementInitializer // however it is unclear if it is reachable since the initialized type must implement IEnumerable case BoundKind.CollectionElementInitializer: var colElement = (BoundCollectionElementInitializer)expr; return CheckValEscape(colElement.Arguments, escapeFrom, escapeTo, diagnostics); case BoundKind.PointerElementAccess: var accessedExpression = ((BoundPointerElementAccess)expr).Expression; return CheckValEscape(accessedExpression.Syntax, accessedExpression, escapeFrom, escapeTo, checkingReceiver, diagnostics); case BoundKind.PointerIndirectionOperator: var operandExpression = ((BoundPointerIndirectionOperator)expr).Operand; return CheckValEscape(operandExpression.Syntax, operandExpression, escapeFrom, escapeTo, checkingReceiver, diagnostics); case BoundKind.AsOperator: case BoundKind.AwaitExpression: case BoundKind.ConditionalAccess: case BoundKind.ArrayAccess: // only possible in error cases (if possible at all) return false; case BoundKind.UnconvertedSwitchExpression: case BoundKind.ConvertedSwitchExpression: foreach (var arm in ((BoundSwitchExpression)expr).SwitchArms) { var result = arm.Value; if (!CheckValEscape(result.Syntax, result, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) return false; } return true; default: // in error situations some unexpected nodes could make here // returning "false" seems safer than throwing. // we will still assert to make sure that all nodes are accounted for. Debug.Assert(false, $"{expr.Kind} expression of {expr.Type} type"); diagnostics.Add(ErrorCode.ERR_InternalError, node.Location); return false; #region "cannot produce ref-like values" // case BoundKind.ThrowExpression: // case BoundKind.ArgListOperator: // case BoundKind.ArgList: // case BoundKind.RefTypeOperator: // case BoundKind.AddressOfOperator: // case BoundKind.TypeOfOperator: // case BoundKind.IsOperator: // case BoundKind.SizeOfOperator: // case BoundKind.DynamicMemberAccess: // case BoundKind.DynamicInvocation: // case BoundKind.NewT: // case BoundKind.DelegateCreationExpression: // case BoundKind.ArrayCreation: // case BoundKind.AnonymousObjectCreationExpression: // case BoundKind.NameOfOperator: // case BoundKind.InterpolatedString: // case BoundKind.StringInsert: // case BoundKind.DynamicIndexerAccess: // case BoundKind.Lambda: // case BoundKind.DynamicObjectCreationExpression: // case BoundKind.NoPiaObjectCreationExpression: // case BoundKind.BaseReference: // case BoundKind.Literal: // case BoundKind.IsPatternExpression: // case BoundKind.DeconstructionAssignmentOperator: // case BoundKind.EventAccess: #endregion #region "not expression that can produce a value" // case BoundKind.FieldEqualsValue: // case BoundKind.PropertyEqualsValue: // case BoundKind.ParameterEqualsValue: // case BoundKind.NamespaceExpression: // case BoundKind.TypeExpression: // case BoundKind.BadStatement: // case BoundKind.MethodDefIndex: // case BoundKind.SourceDocumentIndex: // case BoundKind.ArgList: // case BoundKind.ArgListOperator: // case BoundKind.Block: // case BoundKind.Scope: // case BoundKind.NoOpStatement: // case BoundKind.ReturnStatement: // case BoundKind.YieldReturnStatement: // case BoundKind.YieldBreakStatement: // case BoundKind.ThrowStatement: // case BoundKind.ExpressionStatement: // case BoundKind.SwitchStatement: // case BoundKind.SwitchSection: // case BoundKind.SwitchLabel: // case BoundKind.BreakStatement: // case BoundKind.LocalFunctionStatement: // case BoundKind.ContinueStatement: // case BoundKind.PatternSwitchStatement: // case BoundKind.PatternSwitchSection: // case BoundKind.PatternSwitchLabel: // case BoundKind.IfStatement: // case BoundKind.DoStatement: // case BoundKind.WhileStatement: // case BoundKind.ForStatement: // case BoundKind.ForEachStatement: // case BoundKind.ForEachDeconstructStep: // case BoundKind.UsingStatement: // case BoundKind.FixedStatement: // case BoundKind.LockStatement: // case BoundKind.TryStatement: // case BoundKind.CatchBlock: // case BoundKind.LabelStatement: // case BoundKind.GotoStatement: // case BoundKind.LabeledStatement: // case BoundKind.Label: // case BoundKind.StatementList: // case BoundKind.ConditionalGoto: // case BoundKind.LocalDeclaration: // case BoundKind.MultipleLocalDeclarations: // case BoundKind.ArrayInitialization: // case BoundKind.AnonymousPropertyDeclaration: // case BoundKind.MethodGroup: // case BoundKind.PropertyGroup: // case BoundKind.EventAssignmentOperator: // case BoundKind.Attribute: // case BoundKind.FixedLocalCollectionInitializer: // case BoundKind.DynamicObjectInitializerMember: // case BoundKind.DynamicCollectionElementInitializer: // case BoundKind.ImplicitReceiver: // case BoundKind.FieldInitializer: // case BoundKind.GlobalStatementInitializer: // case BoundKind.TypeOrInstanceInitializers: // case BoundKind.DeclarationPattern: // case BoundKind.ConstantPattern: // case BoundKind.WildcardPattern: #endregion #region "not found as an operand in no-error unlowered bound tree" // case BoundKind.MaximumMethodDefIndex: // case BoundKind.InstrumentationPayloadRoot: // case BoundKind.ModuleVersionId: // case BoundKind.ModuleVersionIdString: // case BoundKind.Dup: // case BoundKind.TypeOrValueExpression: // case BoundKind.BadExpression: // case BoundKind.ArrayLength: // case BoundKind.MethodInfo: // case BoundKind.FieldInfo: // case BoundKind.SequencePoint: // case BoundKind.SequencePointExpression: // case BoundKind.SequencePointWithSpan: // case BoundKind.StateMachineScope: // case BoundKind.ConditionalReceiver: // case BoundKind.ComplexConditionalReceiver: // case BoundKind.PreviousSubmissionReference: // case BoundKind.HostObjectMemberReference: // case BoundKind.UnboundLambda: // case BoundKind.LoweredConditionalAccess: // case BoundKind.Sequence: // case BoundKind.HoistedFieldAccess: // case BoundKind.OutVariablePendingInference: // case BoundKind.DeconstructionVariablePendingInference: // case BoundKind.OutDeconstructVarPendingInference: // case BoundKind.PseudoVariable: #endregion } } private static bool CheckTupleValEscape(ImmutableArray<BoundExpression> elements, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { foreach (var element in elements) { if (!CheckValEscape(element.Syntax, element, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } } return true; } private static bool CheckValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { foreach (var expression in initExpr.Initializers) { if (expression.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expression; if (!CheckValEscape(expression.Syntax, assignment.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } var left = (BoundObjectInitializerMember)assignment.Left; if (!CheckValEscape(left.Arguments, escapeFrom, escapeTo, diagnostics: diagnostics)) { return false; } } else { if (!CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } } } return true; } private static bool CheckValEscape(ImmutableArray<BoundExpression> expressions, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { foreach (var expression in expressions) { if (!CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)) { return false; } } return true; } private static bool CheckInterpolatedStringHandlerConversionEscape(BoundExpression expression, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) { var data = expression switch { BoundInterpolatedString { InterpolationData: { } d } => d, BoundBinaryOperator { InterpolatedStringHandlerData: { } d } => d, _ => throw ExceptionUtilities.UnexpectedValue(expression.Kind) }; // We need to check to see if any values could potentially escape outside the max depth via the handler type. // Consider the case where a ref-struct handler saves off the result of one call to AppendFormatted, // and then on a subsequent call it either assigns that saved value to another ref struct with a larger // escape, or does the opposite. In either case, we need to check. CheckValEscape(expression.Syntax, data.Construction, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); while (true) { switch (expression) { case BoundBinaryOperator binary: if (!checkParts((BoundInterpolatedString)binary.Right)) { return false; } expression = binary.Left; continue; case BoundInterpolatedString interpolatedString: if (!checkParts(interpolatedString)) { return false; } return true; default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } bool checkParts(BoundInterpolatedString interpolatedString) { foreach (var part in interpolatedString.Parts) { if (part is not BoundCall { Method.Name: BoundInterpolatedString.AppendFormattedMethod } call) { // Dynamic calls cannot have ref struct parameters, and AppendLiteral calls will always have literal // string arguments and do not require us to be concerned with escape continue; } // The interpolation component is always the first argument to the method, and it was not passed by name // so there can be no reordering. var argument = call.Arguments[0]; var success = CheckValEscape(argument.Syntax, argument, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); if (!success) { return false; } } return true; } } internal enum AddressKind { // reference may be written to Writeable, // reference itself will not be written to, but may be used for call, callvirt. // for all purposes it is the same as Writeable, except when fetching an address of an array element // where it results in a ".readonly" prefix to deal with array covariance. Constrained, // reference itself will not be written to, nor it will be used to modify fields. ReadOnly, // same as ReadOnly, but we are not supposed to get a reference to a clone // regardless of compat settings. ReadOnlyStrict, } internal static bool IsAnyReadOnly(AddressKind addressKind) => addressKind >= AddressKind.ReadOnly; /// <summary> /// Checks if expression directly or indirectly represents a value with its own home. In /// such cases it is possible to get a reference without loading into a temporary. /// </summary> internal static bool HasHome( BoundExpression expression, AddressKind addressKind, MethodSymbol method, bool peVerifyCompatEnabled, HashSet<LocalSymbol> stackLocalsOpt) { Debug.Assert(method is object); switch (expression.Kind) { case BoundKind.ArrayAccess: if (addressKind == AddressKind.ReadOnly && !expression.Type.IsValueType && peVerifyCompatEnabled) { // due to array covariance getting a reference may throw ArrayTypeMismatch when element is not a struct, // passing "readonly." prefix would prevent that, but it is unverifiable, so will make a copy in compat case return false; } return true; case BoundKind.PointerIndirectionOperator: case BoundKind.RefValueOperator: return true; case BoundKind.ThisReference: var type = expression.Type; if (type.IsReferenceType) { Debug.Assert(IsAnyReadOnly(addressKind), "`this` is readonly in classes"); return true; } if (!IsAnyReadOnly(addressKind) && method.IsEffectivelyReadOnly) { return false; } return true; case BoundKind.ThrowExpression: // vacuously this is true, we can take address of throw without temps return true; case BoundKind.Parameter: return IsAnyReadOnly(addressKind) || ((BoundParameter)expression).ParameterSymbol.RefKind != RefKind.In; case BoundKind.Local: // locals have home unless they are byval stack locals or ref-readonly // locals in a mutating call var local = ((BoundLocal)expression).LocalSymbol; return !((CodeGenerator.IsStackLocal(local, stackLocalsOpt) && local.RefKind == RefKind.None) || (!IsAnyReadOnly(addressKind) && local.RefKind == RefKind.RefReadOnly)); case BoundKind.Call: var methodRefKind = ((BoundCall)expression).Method.RefKind; return methodRefKind == RefKind.Ref || (IsAnyReadOnly(addressKind) && methodRefKind == RefKind.RefReadOnly); case BoundKind.Dup: //NB: Dup represents locals that do not need IL slot var dupRefKind = ((BoundDup)expression).RefKind; return dupRefKind == RefKind.Ref || (IsAnyReadOnly(addressKind) && dupRefKind == RefKind.RefReadOnly); case BoundKind.FieldAccess: return HasHome((BoundFieldAccess)expression, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt); case BoundKind.Sequence: return HasHome(((BoundSequence)expression).Value, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt); case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)expression; if (!assignment.IsRef) { return false; } var lhsRefKind = assignment.Left.GetRefKind(); return lhsRefKind == RefKind.Ref || (IsAnyReadOnly(addressKind) && lhsRefKind == RefKind.RefReadOnly); case BoundKind.ComplexConditionalReceiver: Debug.Assert(HasHome( ((BoundComplexConditionalReceiver)expression).ValueTypeReceiver, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt)); Debug.Assert(HasHome( ((BoundComplexConditionalReceiver)expression).ReferenceTypeReceiver, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt)); goto case BoundKind.ConditionalReceiver; case BoundKind.ConditionalReceiver: //ConditionalReceiver is a noop from Emit point of view. - it represents something that has already been pushed. //We should never need a temp for it. return true; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)expression; // only ref conditional may be referenced as a variable if (!conditional.IsRef) { return false; } // branch that has no home will need a temporary // if both have no home, just say whole expression has no home // so we could just use one temp for the whole thing return HasHome(conditional.Consequence, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt) && HasHome(conditional.Alternative, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt); default: return false; } } /// <summary> /// Special HasHome for fields. /// Fields have readable homes when they are not constants. /// Fields have writeable homes unless they are readonly and used outside of the constructor. /// </summary> private static bool HasHome( BoundFieldAccess fieldAccess, AddressKind addressKind, MethodSymbol method, bool peVerifyCompatEnabled, HashSet<LocalSymbol> stackLocalsOpt) { Debug.Assert(method is object); FieldSymbol field = fieldAccess.FieldSymbol; // const fields are literal values with no homes. (ex: decimal.Zero) if (field.IsConst) { return false; } // in readonly situations where ref to a copy is not allowed, consider fields as addressable if (addressKind == AddressKind.ReadOnlyStrict) { return true; } // ReadOnly references can always be taken unless we are in peverify compat mode if (addressKind == AddressKind.ReadOnly && !peVerifyCompatEnabled) { return true; } // Some field accesses must be values; values do not have homes. if (fieldAccess.IsByValue) { return false; } if (!field.IsReadOnly) { // in a case if we have a writeable struct field with a receiver that only has a readable home we would need to pass it via a temp. // it would be advantageous to make a temp for the field, not for the outer struct, since the field is smaller and we can get to is by fetching references. // NOTE: this would not be profitable if we have to satisfy verifier, since for verifiability // we would not be able to dig for the inner field using references and the outer struct will have to be copied to a temp anyways. if (!peVerifyCompatEnabled) { Debug.Assert(!IsAnyReadOnly(addressKind)); var receiver = fieldAccess.ReceiverOpt; if (receiver?.Type.IsValueType == true) { // Check receiver: // has writeable home -> return true - the whole chain has writeable home (also a more common case) // has readable home -> return false - we need to copy the field // otherwise -> return true - the copy will be made at higher level so the leaf field can have writeable home return HasHome(receiver, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt) || !HasHome(receiver, AddressKind.ReadOnly, method, peVerifyCompatEnabled, stackLocalsOpt); } } return true; } // while readonly fields have home it is not valid to refer to it when not constructing. if (!TypeSymbol.Equals(field.ContainingType, method.ContainingType, TypeCompareKind.AllIgnoreOptions)) { return false; } if (field.IsStatic) { return method.MethodKind == MethodKind.StaticConstructor; } else { return (method.MethodKind == MethodKind.Constructor || method.IsInitOnly) && fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference; } } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) { var startText = node.StringStartToken.Text; if (startText.StartsWith("@$\"") && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings)) { Error(diagnostics, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, node.StringStartToken.GetLocation(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings.RequiredVersion())); } var builder = ArrayBuilder<BoundExpression>.GetInstance(); var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node); ConstantValue? resultConstant = null; bool isResultConstant = true; if (node.Contents.Count == 0) { resultConstant = ConstantValue.Create(string.Empty); } else { var isNonVerbatimInterpolatedString = node.StringStartToken.Kind() != SyntaxKind.InterpolatedVerbatimStringStartToken; var newLinesInInterpolationsAllowed = this.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNewLinesInInterpolations); var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); foreach (var content in node.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; // If we're prior to C# 11 then we don't allow newlines in the interpolations of // non-verbatim interpolated strings. Check for that here and report an error // if the interpolation spans multiple lines (and thus must have a newline). // // Note: don't bother doing this if the interpolation is otherwise malformed or // we've already reported some other error within it. No need to spam the user // with multiple errors (esp as a malformed interpolation may commonly span multiple // lines due to error recovery). if (isNonVerbatimInterpolatedString && !interpolation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) && !newLinesInInterpolationsAllowed && !interpolation.OpenBraceToken.IsMissing && !interpolation.CloseBraceToken.IsMissing) { var text = node.SyntaxTree.GetText(); if (text.Lines.GetLineFromPosition(interpolation.OpenBraceToken.SpanStart).LineNumber != text.Lines.GetLineFromPosition(interpolation.CloseBraceToken.SpanStart).LineNumber) { diagnostics.Add( ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, interpolation.CloseBraceToken.GetLocation(), this.Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNewLinesInInterpolations.RequiredVersion())); } } var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue); // We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering, // when we perform overload resolution, to report a problem. So we do that check by calling // GenerateConversionForAssignment with objectType. However we want to preserve the original expression's // natural type so that overload resolution may select a specialized implementation of string.Format, // so we discard the result of that call and only preserve its diagnostics. BoundExpression? alignment = null; BoundLiteral? format = null; if (interpolation.AlignmentClause != null) { alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics); var alignmentConstant = alignment.ConstantValue; if (alignmentConstant != null && !alignmentConstant.IsBad) { const int magnitudeLimit = 32767; // check that the magnitude of the alignment is "in range". int alignmentValue = alignmentConstant.Int32Value; // We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value. alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue; if (alignmentValue < -magnitudeLimit) { diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit); } } else if (!alignment.HasErrors) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location); } } if (interpolation.FormatClause != null) { var text = interpolation.FormatClause.FormatStringToken.ValueText; char lastChar; bool hasErrors = false; if (text.Length == 0) { diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar)) { diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors); } builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false)); if (!isResultConstant || value.ConstantValue == null || !(interpolation is { FormatClause: null, AlignmentClause: null }) || !(value.ConstantValue is { IsString: true, IsBad: false })) { isResultConstant = false; continue; } resultConstant = (resultConstant is null) ? value.ConstantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue); continue; } case SyntaxKind.InterpolatedStringText: { var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText; builder.Add(new BoundLiteral(content, ConstantValue.Create(text, SpecialType.System_String), stringType)); if (isResultConstant) { var constantVal = ConstantValue.Create(ConstantValueUtils.UnescapeInterpolatedStringLiteral(text), SpecialType.System_String); resultConstant = (resultConstant is null) ? constantVal : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantVal); } continue; } default: throw ExceptionUtilities.UnexpectedValue(content.Kind()); } } if (!isResultConstant) { resultConstant = null; } } Debug.Assert(isResultConstant == (resultConstant != null)); return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType); } private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { // We have 4 possible lowering strategies, dependent on the contents of the string, in this order: // 1. The string is a constant value. We can just use the final value. // 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a // params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and // make no intermediate allocations. // 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression. // The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any // awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation // hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for // the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected. // We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we // cannot put a try/finally inside a filter block. // 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single // call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this // call will need to allocate a param array. // 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await // expression. This is turned into a call to string.Format. // // We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being // able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering. if (unconvertedInterpolatedString.ConstantValue is not null) { // Case 1 Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String })); return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } // Case 2. Attempt to see if all parts are strings. if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts)) { return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } if (tryBindAsHandlerType(out var result)) { // Case 3 return result; } // The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible // object. return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) => new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result) { result = null; if (InExpressionTree || !InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType is MissingMetadataTypeSymbol) { return false; } result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false); return true; } } private static bool InterpolatedStringPartsAreValidInDefaultHandler(BoundUnconvertedInterpolatedString unconvertedInterpolatedString) => !unconvertedInterpolatedString.Parts.ContainsAwaitExpression() && unconvertedInterpolatedString.Parts.All(p => p is not BoundStringInsert { Value.Type.TypeKind: TypeKind.Dynamic }); private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray<BoundExpression> parts) => parts.All(p => p is BoundLiteral or BoundStringInsert { Value.Type.SpecialType: SpecialType.System_String, Alignment: null, Format: null }); private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator) { // Much like BindUnconvertedInterpolatedStringToString above, we only want to use DefaultInterpolatedStringHandler if it's worth it. We therefore // check for cases 1 and 2: if they are present, we let normal string binary operator binding machinery handle it. Otherwise, we take care of it ourselves. Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); convertedBinaryOperator = null; if (InExpressionTree) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType.IsErrorType()) { // Can't ever bind to the handler no matter what, so just let the default handling take care of it. Cases 4 and 5 are covered by this. return false; } // The constant value is folded as part of creating the unconverted operator. If there is a constant value, then the top-level binary operator // will have one. if (binaryOperator.ConstantValue is not null) { // This is case 1. Let the standard machinery handle it return false; } var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); if (!binaryOperator.VisitBinaryOperatorInterpolatedString( partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { if (!InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; })) { partsArrayBuilder.Free(); return false; } Debug.Assert(partsArrayBuilder.Count >= 2); if (partsArrayBuilder.Count <= 4 && partsArrayBuilder.All(static parts => AllInterpolatedStringPartsAreStrings(parts))) { // This is case 2. Let the standard machinery handle it partsArrayBuilder.Free(); return false; } // Case 3. Bind as handler. var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: false, additionalConstructorArguments: default, additionalConstructorRefKinds: default); // Now that the parts have been bound, reconstruct the binary operators. convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return true; } private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(BoundBinaryOperator originalOperator, ImmutableArray<ImmutableArray<BoundExpression>> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics) { var @string = GetSpecialType(SpecialType.System_String, diagnostics, rootSyntax); Func<BoundUnconvertedInterpolatedString, int, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> interpolationFactory = createInterpolation; Func<BoundBinaryOperator, BoundExpression, BoundExpression, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> binaryOperatorFactory = createBinaryOperator; var rewritten = (BoundBinaryOperator)originalOperator.RewriteInterpolatedStringAddition((appendCalls, @string), interpolationFactory, binaryOperatorFactory); return rewritten.Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data)); static BoundInterpolatedString createInterpolation(BoundUnconvertedInterpolatedString expression, int i, (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, TypeSymbol _) arg) { Debug.Assert(arg.AppendCalls.Length > i); return new BoundInterpolatedString( expression.Syntax, interpolationData: null, arg.AppendCalls[i], expression.ConstantValue, expression.Type, expression.HasErrors); } static BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, BoundExpression right, (ImmutableArray<ImmutableArray<BoundExpression>> _, TypeSymbol @string) arg) => new BoundBinaryOperator( original.Syntax, BinaryOperatorKind.StringConcatenation, left, right, original.ConstantValue, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, originalUserDefinedOperatorsOpt: default, arg.@string, original.HasErrors); } private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType( BoundExpression unconvertedExpression, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) => unconvertedExpression switch { BoundUnconvertedInterpolatedString interpolatedString => BindUnconvertedInterpolatedStringToHandlerType( interpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds), BoundBinaryOperator binary => BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binary, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds), _ => throw ExceptionUtilities.UnexpectedValue(unconvertedExpression.Kind) }; private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType( BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) { var (appendCalls, interpolationData) = BindUnconvertedInterpolatedPartsToHandlerType( unconvertedInterpolatedString.Syntax, ImmutableArray.Create(unconvertedInterpolatedString.Parts), interpolatedStringHandlerType, diagnostics, isHandlerConversion, additionalConstructorArguments, additionalConstructorRefKinds); Debug.Assert(appendCalls.Length == 1); return new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, interpolationData, appendCalls[0], unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); } private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType( BoundBinaryOperator binaryOperator, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); binaryOperator.VisitBinaryOperatorInterpolatedString(partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; }); var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds); var result = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return result; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType( SyntaxNode syntax, ImmutableArray<ImmutableArray<BoundExpression>> partsArray, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(additionalConstructorArguments.IsDefault ? additionalConstructorRefKinds.IsDefault : additionalConstructorArguments.Length == additionalConstructorRefKinds.Length); additionalConstructorArguments = additionalConstructorArguments.NullToEmpty(); additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty(); ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax); // We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if // there are errors we get better diagnostics than "could not convert to object." var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true }; var (appendCallsArray, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(partsArray, implicitBuilderReceiver, diagnostics); // Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types // (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there // is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components // are convertible to object if the current langversion is lower than the interpolation feature and we're converting this // interpolation into an actual string. bool needToCheckConversionToObject = false; if (isHandlerConversion) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics) { needToCheckConversionToObject = true; } Debug.Assert(appendCallsArray.Select(a => a.Length).SequenceEqual(partsArray.Select(a => a.Length))); Debug.Assert(appendCallsArray.All(appendCalls => appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation))); if (needToCheckConversionToObject) { TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, syntax); BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); foreach (var parts in partsArray) { foreach (var currentPart in parts) { if (currentPart is BoundStringInsert insert) { var value = insert.Value; bool reported = false; if (value.Type is not null) { value = BindToNaturalType(value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); reported = true; } } if (!reported) { _ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } } conversionDiagnostics.Clear(); } } } conversionDiagnostics.Free(); } var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, syntax); int constructorArgumentLength = 3 + additionalConstructorArguments.Length; var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength); refKindsBuilder.Add(RefKind.None); refKindsBuilder.Add(RefKind.None); refKindsBuilder.AddRange(additionalConstructorRefKinds); // Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean, // because we want to track that we're using the type no matter what. var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, syntax); var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType); var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder); refKindsBuilder.Add(RefKind.Out); populateArguments(syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); BoundExpression constructorCall; var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, outConstructorDiagnostics); if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which // could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate. argumentsBuilder.Clear(); // Try again without an out parameter. populateArguments(syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); refKindsBuilder.RemoveLast(); var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics); BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, nonOutConstructorDiagnostics); if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // We successfully bound the out version, so set all the final data based on that binding constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); } else { // We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find // a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed // for a different reason, that different reason is the one the user will want to know about. If both or neither failed // because of this error, we'll report everything. // https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload // resolution and attempting to determine which method considered was the best to report errors for. var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; switch ((nonOutConstructorHasArityError, outConstructorHasArityError)) { case (true, false): constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; diagnostics.AddRangeAndFree(outConstructorDiagnostics); nonOutConstructorDiagnostics.Free(); break; case (false, true): constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); break; default: // For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker, // but we'll report all diagnostics constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); diagnostics.AddRangeAndFree(outConstructorDiagnostics); break; } } } else { diagnostics.AddRangeAndFree(outConstructorDiagnostics); constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; } argumentsBuilder.Free(); refKindsBuilder.Free(); Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression); if (constructorCall is BoundDynamicObjectCreationExpression) { // An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name); } var interpolationData = new InterpolatedStringHandlerData( interpolatedStringHandlerType, constructorCall, usesBoolReturn, LocalScopeDepth, additionalConstructorArguments.NullToEmpty(), positionInfo, implicitBuilderReceiver); return (appendCallsArray, interpolationData); static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder) { // literalLength argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true }); // formattedCount argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true }); // Any other arguments from the call site argumentsBuilder.AddRange(additionalConstructorArguments); } } private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundExpression>? partsBuilder = null; var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) { var part = unconvertedInterpolatedString.Parts[i]; if (part is BoundStringInsert insert) { BoundExpression newValue; if (insert.Value.Type is null) { newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } else { newValue = BindToNaturalType(insert.Value, diagnostics); _ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } if (insert.Value != newValue) { if (partsBuilder is null) { partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length); partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i); } partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false)); } else { partsBuilder?.Add(part); } } else { Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } }); partsBuilder?.Add(part); } } return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls( ImmutableArray<ImmutableArray<BoundExpression>> partsArray, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) { if (partsArray.IsEmpty && partsArray.All(p => p.IsEmpty)) { return (ImmutableArray<ImmutableArray<BoundExpression>>.Empty, false, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.Empty, 0, 0); } bool? builderPatternExpectsBool = null; var firstPartsLength = partsArray[0].Length; var builderAppendCallsArray = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(partsArray.Length); var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(firstPartsLength); var positionInfoArray = ArrayBuilder<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.GetInstance(partsArray.Length); var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(firstPartsLength); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3); var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3); int baseStringLength = 0; int numFormatHoles = 0; foreach (var parts in partsArray) { foreach (var part in parts) { Debug.Assert(part is BoundLiteral or BoundStringInsert); string methodName; bool isLiteral; bool hasAlignment; bool hasFormat; if (part is BoundStringInsert insert) { methodName = "AppendFormatted"; argumentsBuilder.Add(insert.Value); parameterNamesAndLocationsBuilder.Add(null); isLiteral = false; hasAlignment = false; hasFormat = false; if (insert.Alignment is not null) { hasAlignment = true; argumentsBuilder.Add(insert.Alignment); parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location)); } if (insert.Format is not null) { hasFormat = true; argumentsBuilder.Add(insert.Format); parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location)); } numFormatHoles++; } else { var boundLiteral = (BoundLiteral)part; Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString); var literalText = ConstantValueUtils.UnescapeInterpolatedStringLiteral(boundLiteral.ConstantValue.StringValue); methodName = "AppendLiteral"; argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type)); isLiteral = true; hasAlignment = false; hasFormat = false; baseStringLength += literalText.Length; } var arguments = argumentsBuilder.ToImmutableAndClear(); ImmutableArray<(string, Location)?> parameterNamesAndLocations; if (parameterNamesAndLocationsBuilder.Count > 1) { parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear(); } else { Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null); parameterNamesAndLocations = default; parameterNamesAndLocationsBuilder.Clear(); } var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false); builderAppendCalls.Add(call); positionInfo.Add((isLiteral, hasAlignment, hasFormat)); Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true }); // We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that // void is returned. if (call is BoundCall { Method: { ReturnType: var returnType } method }) { bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean; if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void) { // Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method); } else if (builderPatternExpectsBool == null) { builderPatternExpectsBool = methodReturnsBool; } else if (builderPatternExpectsBool != methodReturnsBool) { // Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'. var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void); diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected); } } } builderAppendCallsArray.Add(builderAppendCalls.ToImmutableAndClear()); positionInfoArray.Add(positionInfo.ToImmutableAndClear()); } argumentsBuilder.Free(); parameterNamesAndLocationsBuilder.Free(); builderAppendCalls.Free(); positionInfo.Free(); return (builderAppendCallsArray.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfoArray.ToImmutableAndFree(), baseStringLength, numFormatHoles); } private BoundExpression BindInterpolatedStringHandlerInMemberCall( BoundExpression unconvertedString, ArrayBuilder<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, TypeSymbol? receiverType, uint receiverEscapeScope, BindingDiagnosticBag diagnostics) { Debug.Assert(unconvertedString is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }); var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler); var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); Debug.Assert(interpolatedStringParameter is { Type: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } } #pragma warning disable format or { IsParams: true, Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } }, InterpolatedStringHandlerArgumentIndexes.IsEmpty: true }); #pragma warning restore format Debug.Assert(!interpolatedStringParameter.IsParams || memberAnalysisResult.Kind == MemberResolutionKind.ApplicableInExpandedForm); if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError) { // The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type); return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: false, interpolatedStringParameter.Type, diagnostics, hasErrors: true); } var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes; if (handlerParameterIndexes.IsEmpty) { // No arguments, fall back to the standard conversion steps. return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, interpolatedStringParameter.IsParams ? ((ArrayTypeSymbol)interpolatedStringParameter.Type).ElementType : interpolatedStringParameter.Type, diagnostics); } Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength, parameters.Length)); // We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter ImmutableArray<int> handlerArgumentIndexes; if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) { // No parameters are missing and no remapped indexes, we can just use the original indexes handlerArgumentIndexes = handlerParameterIndexes; } else { // Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter. var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++) { int handlerParameter = handlerParameterIndexes[handlerParameterIndex]; Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter) { handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter; continue; } for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++) { // The index in the original parameter list we're looking to match up. int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex); // Is the original parameter index of the current argument the parameter index that was specified in the attribute? if (argumentParameterIndex == handlerParameter) { // We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice. handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex; } } } handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree(); } var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length); var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length); bool hasErrors = false; // Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct // a set of placeholders for overload resolution. for (int i = 0; i < handlerArgumentIndexes.Length; i++) { int argumentIndex = handlerArgumentIndexes[i]; Debug.Assert(argumentIndex != interpolatedStringArgNum); RefKind refKind; TypeSymbol placeholderType; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiverType is not null); refKind = RefKind.None; placeholderType = receiverType; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: { // Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed. // If it is optional, then they could otherwise not specify the parameter and that's an error var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter))) { // Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; default: { var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (argumentIndex > interpolatedStringArgNum) { // Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[argumentIndex].Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; } SyntaxNode placeholderSyntax; uint valSafeToEscapeScope; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = receiverEscapeScope; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = Binder.ExternalScope; break; case >= 0: placeholderSyntax = arguments[argumentIndex].Syntax; valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth); break; default: throw ExceptionUtilities.UnexpectedValue(argumentIndex); } argumentPlaceholdersBuilder.Add( new BoundInterpolatedStringArgumentPlaceholder( placeholderSyntax, argumentIndex, valSafeToEscapeScope, placeholderType, hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter)); // We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors // about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will // be a place where refkinds are allowed to differ argumentRefKindsBuilder.Add(refKind); } var interpolatedString = BindUnconvertedInterpolatedExpressionToHandlerType( unconvertedString, (NamedTypeSymbol)interpolatedStringParameter.Type, diagnostics, additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(), additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree()); return new BoundConversion( interpolatedString.Syntax, interpolatedString, interpolatedStringConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, interpolatedStringParameter.Type, hasErrors || interpolatedString.HasErrors); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) { var startText = node.StringStartToken.Text; if (startText.StartsWith("@$\"") && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings)) { Error(diagnostics, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, node.StringStartToken.GetLocation(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings.RequiredVersion())); } var builder = ArrayBuilder<BoundExpression>.GetInstance(); var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node); ConstantValue? resultConstant = null; bool isResultConstant = true; if (node.Contents.Count == 0) { resultConstant = ConstantValue.Create(string.Empty); } else { var isNonVerbatimInterpolatedString = node.StringStartToken.Kind() != SyntaxKind.InterpolatedVerbatimStringStartToken; var newLinesInInterpolationsAllowed = this.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNewLinesInInterpolations); var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); foreach (var content in node.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; // If we're prior to C# 11 then we don't allow newlines in the interpolations of // non-verbatim interpolated strings. Check for that here and report an error // if the interpolation spans multiple lines (and thus must have a newline). // // Note: don't bother doing this if the interpolation is otherwise malformed or // we've already reported some other error within it. No need to spam the user // with multiple errors (esp as a malformed interpolation may commonly span multiple // lines due to error recovery). if (isNonVerbatimInterpolatedString && !interpolation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) && !newLinesInInterpolationsAllowed && !interpolation.OpenBraceToken.IsMissing && !interpolation.CloseBraceToken.IsMissing) { var text = node.SyntaxTree.GetText(); if (text.Lines.GetLineFromPosition(interpolation.OpenBraceToken.SpanStart).LineNumber != text.Lines.GetLineFromPosition(interpolation.CloseBraceToken.SpanStart).LineNumber) { diagnostics.Add( ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, interpolation.CloseBraceToken.GetLocation(), this.Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNewLinesInInterpolations.RequiredVersion())); } } var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue); // We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering, // when we perform overload resolution, to report a problem. So we do that check by calling // GenerateConversionForAssignment with objectType. However we want to preserve the original expression's // natural type so that overload resolution may select a specialized implementation of string.Format, // so we discard the result of that call and only preserve its diagnostics. BoundExpression? alignment = null; BoundLiteral? format = null; if (interpolation.AlignmentClause != null) { alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics); var alignmentConstant = alignment.ConstantValue; if (alignmentConstant != null && !alignmentConstant.IsBad) { const int magnitudeLimit = 32767; // check that the magnitude of the alignment is "in range". int alignmentValue = alignmentConstant.Int32Value; // We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value. alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue; if (alignmentValue < -magnitudeLimit) { diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit); } } else if (!alignment.HasErrors) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location); } } if (interpolation.FormatClause != null) { var text = interpolation.FormatClause.FormatStringToken.ValueText; char lastChar; bool hasErrors = false; if (text.Length == 0) { diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar)) { diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors); } builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false)); if (!isResultConstant || value.ConstantValue == null || !(interpolation is { FormatClause: null, AlignmentClause: null }) || !(value.ConstantValue is { IsString: true, IsBad: false })) { isResultConstant = false; continue; } resultConstant = (resultConstant is null) ? value.ConstantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue); continue; } case SyntaxKind.InterpolatedStringText: { var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText; builder.Add(new BoundLiteral(content, ConstantValue.Create(text, SpecialType.System_String), stringType)); if (isResultConstant) { var constantVal = ConstantValue.Create(ConstantValueUtils.UnescapeInterpolatedStringLiteral(text), SpecialType.System_String); resultConstant = (resultConstant is null) ? constantVal : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantVal); } continue; } default: throw ExceptionUtilities.UnexpectedValue(content.Kind()); } } if (!isResultConstant) { resultConstant = null; } } Debug.Assert(isResultConstant == (resultConstant != null)); return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType); } private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { // We have 4 possible lowering strategies, dependent on the contents of the string, in this order: // 1. The string is a constant value. We can just use the final value. // 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a // params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and // make no intermediate allocations. // 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression. // The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any // awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation // hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for // the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected. // We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we // cannot put a try/finally inside a filter block. // 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single // call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this // call will need to allocate a param array. // 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await // expression. This is turned into a call to string.Format. // // We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being // able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering. if (unconvertedInterpolatedString.ConstantValue is not null) { // Case 1 Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String })); return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } // Case 2. Attempt to see if all parts are strings. if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts)) { return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } if (tryBindAsHandlerType(out var result)) { // Case 3 return result; } // The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible // object. return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) => new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result) { result = null; if (InExpressionTree || !InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType is MissingMetadataTypeSymbol) { return false; } result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false); return true; } } private static bool InterpolatedStringPartsAreValidInDefaultHandler(BoundUnconvertedInterpolatedString unconvertedInterpolatedString) => !unconvertedInterpolatedString.Parts.ContainsAwaitExpression() && unconvertedInterpolatedString.Parts.All(p => p is not BoundStringInsert { Value.Type.TypeKind: TypeKind.Dynamic }); private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray<BoundExpression> parts) => parts.All(p => p is BoundLiteral or BoundStringInsert { Value.Type.SpecialType: SpecialType.System_String, Alignment: null, Format: null }); private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator) { // Much like BindUnconvertedInterpolatedStringToString above, we only want to use DefaultInterpolatedStringHandler if it's worth it. We therefore // check for cases 1 and 2: if they are present, we let normal string binary operator binding machinery handle it. Otherwise, we take care of it ourselves. Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); convertedBinaryOperator = null; if (InExpressionTree) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType.IsErrorType()) { // Can't ever bind to the handler no matter what, so just let the default handling take care of it. Cases 4 and 5 are covered by this. return false; } // The constant value is folded as part of creating the unconverted operator. If there is a constant value, then the top-level binary operator // will have one. if (binaryOperator.ConstantValue is not null) { // This is case 1. Let the standard machinery handle it return false; } var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); if (!binaryOperator.VisitBinaryOperatorInterpolatedString( partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { if (!InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; })) { partsArrayBuilder.Free(); return false; } Debug.Assert(partsArrayBuilder.Count >= 2); if (partsArrayBuilder.Count <= 4 && partsArrayBuilder.All(static parts => AllInterpolatedStringPartsAreStrings(parts))) { // This is case 2. Let the standard machinery handle it partsArrayBuilder.Free(); return false; } // Case 3. Bind as handler. var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: false, additionalConstructorArguments: default, additionalConstructorRefKinds: default); // Now that the parts have been bound, reconstruct the binary operators. convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return true; } private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(BoundBinaryOperator originalOperator, ImmutableArray<ImmutableArray<BoundExpression>> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics) { var @string = GetSpecialType(SpecialType.System_String, diagnostics, rootSyntax); Func<BoundUnconvertedInterpolatedString, int, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> interpolationFactory = createInterpolation; Func<BoundBinaryOperator, BoundExpression, BoundExpression, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> binaryOperatorFactory = createBinaryOperator; var rewritten = (BoundBinaryOperator)originalOperator.RewriteInterpolatedStringAddition((appendCalls, @string), interpolationFactory, binaryOperatorFactory); return rewritten.Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data)); static BoundInterpolatedString createInterpolation(BoundUnconvertedInterpolatedString expression, int i, (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, TypeSymbol _) arg) { Debug.Assert(arg.AppendCalls.Length > i); return new BoundInterpolatedString( expression.Syntax, interpolationData: null, arg.AppendCalls[i], expression.ConstantValue, expression.Type, expression.HasErrors); } static BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, BoundExpression right, (ImmutableArray<ImmutableArray<BoundExpression>> _, TypeSymbol @string) arg) => new BoundBinaryOperator( original.Syntax, BinaryOperatorKind.StringConcatenation, left, right, original.ConstantValue, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, originalUserDefinedOperatorsOpt: default, arg.@string, original.HasErrors); } private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType( BoundExpression unconvertedExpression, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) => unconvertedExpression switch { BoundUnconvertedInterpolatedString interpolatedString => BindUnconvertedInterpolatedStringToHandlerType( interpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds), BoundBinaryOperator binary => BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binary, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds), _ => throw ExceptionUtilities.UnexpectedValue(unconvertedExpression.Kind) }; private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType( BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) { var (appendCalls, interpolationData) = BindUnconvertedInterpolatedPartsToHandlerType( unconvertedInterpolatedString.Syntax, ImmutableArray.Create(unconvertedInterpolatedString.Parts), interpolatedStringHandlerType, diagnostics, isHandlerConversion, additionalConstructorArguments, additionalConstructorRefKinds); Debug.Assert(appendCalls.Length == 1); return new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, interpolationData, appendCalls[0], unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); } private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType( BoundBinaryOperator binaryOperator, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); binaryOperator.VisitBinaryOperatorInterpolatedString(partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; }); var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds); var result = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return result; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType( SyntaxNode syntax, ImmutableArray<ImmutableArray<BoundExpression>> partsArray, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(additionalConstructorArguments.IsDefault ? additionalConstructorRefKinds.IsDefault : additionalConstructorArguments.Length == additionalConstructorRefKinds.Length); additionalConstructorArguments = additionalConstructorArguments.NullToEmpty(); additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty(); ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax); // We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if // there are errors we get better diagnostics than "could not convert to object." var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true }; var (appendCallsArray, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(partsArray, implicitBuilderReceiver, diagnostics); // Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types // (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there // is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components // are convertible to object if the current langversion is lower than the interpolation feature and we're converting this // interpolation into an actual string. bool needToCheckConversionToObject = false; if (isHandlerConversion) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics) { needToCheckConversionToObject = true; } Debug.Assert(appendCallsArray.Select(a => a.Length).SequenceEqual(partsArray.Select(a => a.Length))); Debug.Assert(appendCallsArray.All(appendCalls => appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation))); if (needToCheckConversionToObject) { TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, syntax); BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); foreach (var parts in partsArray) { foreach (var currentPart in parts) { if (currentPart is BoundStringInsert insert) { var value = insert.Value; bool reported = false; if (value.Type is not null) { value = BindToNaturalType(value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); reported = true; } } if (!reported) { _ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } } conversionDiagnostics.Clear(); } } } conversionDiagnostics.Free(); } var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, syntax); int constructorArgumentLength = 3 + additionalConstructorArguments.Length; var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength); refKindsBuilder.Add(RefKind.None); refKindsBuilder.Add(RefKind.None); refKindsBuilder.AddRange(additionalConstructorRefKinds); // Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean, // because we want to track that we're using the type no matter what. var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, syntax); var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType) { WasCompilerGenerated = true }; var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder); refKindsBuilder.Add(RefKind.Out); populateArguments(syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); BoundExpression constructorCall; var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, outConstructorDiagnostics); if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which // could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate. argumentsBuilder.Clear(); // Try again without an out parameter. populateArguments(syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); refKindsBuilder.RemoveLast(); var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics); BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, nonOutConstructorDiagnostics); if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // We successfully bound the out version, so set all the final data based on that binding constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); } else { // We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find // a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed // for a different reason, that different reason is the one the user will want to know about. If both or neither failed // because of this error, we'll report everything. // https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload // resolution and attempting to determine which method considered was the best to report errors for. var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; switch ((nonOutConstructorHasArityError, outConstructorHasArityError)) { case (true, false): constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; diagnostics.AddRangeAndFree(outConstructorDiagnostics); nonOutConstructorDiagnostics.Free(); break; case (false, true): constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); break; default: // For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker, // but we'll report all diagnostics constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); diagnostics.AddRangeAndFree(outConstructorDiagnostics); break; } } } else { diagnostics.AddRangeAndFree(outConstructorDiagnostics); constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; } argumentsBuilder.Free(); refKindsBuilder.Free(); Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression); if (constructorCall is BoundDynamicObjectCreationExpression) { // An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name); } var interpolationData = new InterpolatedStringHandlerData( interpolatedStringHandlerType, constructorCall, usesBoolReturn, LocalScopeDepth, additionalConstructorArguments.NullToEmpty(), positionInfo, implicitBuilderReceiver); return (appendCallsArray, interpolationData); static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder) { // literalLength argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true }); // formattedCount argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true }); // Any other arguments from the call site argumentsBuilder.AddRange(additionalConstructorArguments); } } private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundExpression>? partsBuilder = null; var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) { var part = unconvertedInterpolatedString.Parts[i]; if (part is BoundStringInsert insert) { BoundExpression newValue; if (insert.Value.Type is null) { newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } else { newValue = BindToNaturalType(insert.Value, diagnostics); _ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } if (insert.Value != newValue) { if (partsBuilder is null) { partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length); partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i); } partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false)); } else { partsBuilder?.Add(part); } } else { Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } }); partsBuilder?.Add(part); } } return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls( ImmutableArray<ImmutableArray<BoundExpression>> partsArray, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) { if (partsArray.IsEmpty && partsArray.All(p => p.IsEmpty)) { return (ImmutableArray<ImmutableArray<BoundExpression>>.Empty, false, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.Empty, 0, 0); } bool? builderPatternExpectsBool = null; var firstPartsLength = partsArray[0].Length; var builderAppendCallsArray = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(partsArray.Length); var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(firstPartsLength); var positionInfoArray = ArrayBuilder<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.GetInstance(partsArray.Length); var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(firstPartsLength); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3); var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3); int baseStringLength = 0; int numFormatHoles = 0; foreach (var parts in partsArray) { foreach (var part in parts) { Debug.Assert(part is BoundLiteral or BoundStringInsert); string methodName; bool isLiteral; bool hasAlignment; bool hasFormat; if (part is BoundStringInsert insert) { methodName = BoundInterpolatedString.AppendFormattedMethod; argumentsBuilder.Add(insert.Value); parameterNamesAndLocationsBuilder.Add(null); isLiteral = false; hasAlignment = false; hasFormat = false; if (insert.Alignment is not null) { hasAlignment = true; argumentsBuilder.Add(insert.Alignment); parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location)); } if (insert.Format is not null) { hasFormat = true; argumentsBuilder.Add(insert.Format); parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location)); } numFormatHoles++; } else { var boundLiteral = (BoundLiteral)part; Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString); var literalText = ConstantValueUtils.UnescapeInterpolatedStringLiteral(boundLiteral.ConstantValue.StringValue); methodName = BoundInterpolatedString.AppendLiteralMethod; argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type)); isLiteral = true; hasAlignment = false; hasFormat = false; baseStringLength += literalText.Length; } var arguments = argumentsBuilder.ToImmutableAndClear(); ImmutableArray<(string, Location)?> parameterNamesAndLocations; if (parameterNamesAndLocationsBuilder.Count > 1) { parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear(); } else { Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null); parameterNamesAndLocations = default; parameterNamesAndLocationsBuilder.Clear(); } var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false); builderAppendCalls.Add(call); positionInfo.Add((isLiteral, hasAlignment, hasFormat)); Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true }); // We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that // void is returned. if (call is BoundCall { Method: { ReturnType: var returnType } method }) { bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean; if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void) { // Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method); } else if (builderPatternExpectsBool == null) { builderPatternExpectsBool = methodReturnsBool; } else if (builderPatternExpectsBool != methodReturnsBool) { // Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'. var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void); diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected); } } } builderAppendCallsArray.Add(builderAppendCalls.ToImmutableAndClear()); positionInfoArray.Add(positionInfo.ToImmutableAndClear()); } argumentsBuilder.Free(); parameterNamesAndLocationsBuilder.Free(); builderAppendCalls.Free(); positionInfo.Free(); return (builderAppendCallsArray.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfoArray.ToImmutableAndFree(), baseStringLength, numFormatHoles); } private BoundExpression BindInterpolatedStringHandlerInMemberCall( BoundExpression unconvertedString, ArrayBuilder<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, TypeSymbol? receiverType, uint receiverEscapeScope, BindingDiagnosticBag diagnostics) { Debug.Assert(unconvertedString is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }); var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler); var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); Debug.Assert(interpolatedStringParameter is { Type: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } } #pragma warning disable format or { IsParams: true, Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } }, InterpolatedStringHandlerArgumentIndexes.IsEmpty: true }); #pragma warning restore format Debug.Assert(!interpolatedStringParameter.IsParams || memberAnalysisResult.Kind == MemberResolutionKind.ApplicableInExpandedForm); if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError) { // The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type); return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: false, interpolatedStringParameter.Type, diagnostics, hasErrors: true); } var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes; if (handlerParameterIndexes.IsEmpty) { // No arguments, fall back to the standard conversion steps. return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, interpolatedStringParameter.IsParams ? ((ArrayTypeSymbol)interpolatedStringParameter.Type).ElementType : interpolatedStringParameter.Type, diagnostics); } Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength, parameters.Length)); // We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter ImmutableArray<int> handlerArgumentIndexes; if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) { // No parameters are missing and no remapped indexes, we can just use the original indexes handlerArgumentIndexes = handlerParameterIndexes; } else { // Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter. var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++) { int handlerParameter = handlerParameterIndexes[handlerParameterIndex]; Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter) { handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter; continue; } for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++) { // The index in the original parameter list we're looking to match up. int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex); // Is the original parameter index of the current argument the parameter index that was specified in the attribute? if (argumentParameterIndex == handlerParameter) { // We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice. handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex; } } } handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree(); } var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length); var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length); bool hasErrors = false; // Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct // a set of placeholders for overload resolution. for (int i = 0; i < handlerArgumentIndexes.Length; i++) { int argumentIndex = handlerArgumentIndexes[i]; Debug.Assert(argumentIndex != interpolatedStringArgNum); RefKind refKind; TypeSymbol placeholderType; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiverType is not null); refKind = RefKind.None; placeholderType = receiverType; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: { // Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed. // If it is optional, then they could otherwise not specify the parameter and that's an error var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter))) { // Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; default: { var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (argumentIndex > interpolatedStringArgNum) { // Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[argumentIndex].Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; } SyntaxNode placeholderSyntax; uint valSafeToEscapeScope; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = receiverEscapeScope; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = Binder.ExternalScope; break; case >= 0: placeholderSyntax = arguments[argumentIndex].Syntax; valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth); break; default: throw ExceptionUtilities.UnexpectedValue(argumentIndex); } argumentPlaceholdersBuilder.Add( new BoundInterpolatedStringArgumentPlaceholder( placeholderSyntax, argumentIndex, valSafeToEscapeScope, placeholderType, hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter) { WasCompilerGenerated = true }); // We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors // about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will // be a place where refkinds are allowed to differ argumentRefKindsBuilder.Add(refKind); } var interpolatedString = BindUnconvertedInterpolatedExpressionToHandlerType( unconvertedString, (NamedTypeSymbol)interpolatedStringParameter.Type, diagnostics, additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(), additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree()); return new BoundConversion( interpolatedString.Syntax, interpolatedString, interpolatedStringConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, interpolatedStringParameter.Type, hasErrors || interpolatedString.HasErrors); } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { internal sealed partial class CSharpOperationFactory { private readonly SemanticModel _semanticModel; public CSharpOperationFactory(SemanticModel semanticModel) { _semanticModel = semanticModel; } [return: NotNullIfNotNull("boundNode")] public IOperation? Create(BoundNode? boundNode) { if (boundNode == null) { return null; } switch (boundNode.Kind) { case BoundKind.DeconstructValuePlaceholder: return CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); case BoundKind.DeconstructionAssignmentOperator: return CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); case BoundKind.Call: return CreateBoundCallOperation((BoundCall)boundNode); case BoundKind.Local: return CreateBoundLocalOperation((BoundLocal)boundNode); case BoundKind.FieldAccess: return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); case BoundKind.PropertyAccess: return CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); case BoundKind.IndexerAccess: return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); case BoundKind.EventAccess: return CreateBoundEventAccessOperation((BoundEventAccess)boundNode); case BoundKind.EventAssignmentOperator: return CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); case BoundKind.Parameter: return CreateBoundParameterOperation((BoundParameter)boundNode); case BoundKind.Literal: return CreateBoundLiteralOperation((BoundLiteral)boundNode); case BoundKind.DynamicInvocation: return CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); case BoundKind.DynamicIndexerAccess: return CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); case BoundKind.ObjectCreationExpression: return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); case BoundKind.WithExpression: return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); case BoundKind.DynamicObjectCreationExpression: return CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); case BoundKind.ObjectInitializerExpression: return CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); case BoundKind.CollectionInitializerExpression: return CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); case BoundKind.ObjectInitializerMember: return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); case BoundKind.CollectionElementInitializer: return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); case BoundKind.DynamicObjectInitializerMember: return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); case BoundKind.DynamicMemberAccess: return CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); case BoundKind.DynamicCollectionElementInitializer: return CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); case BoundKind.UnboundLambda: return CreateUnboundLambdaOperation((UnboundLambda)boundNode); case BoundKind.Lambda: return CreateBoundLambdaOperation((BoundLambda)boundNode); case BoundKind.Conversion: return CreateBoundConversionOperation((BoundConversion)boundNode); case BoundKind.AsOperator: return CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); case BoundKind.IsOperator: return CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); case BoundKind.SizeOfOperator: return CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); case BoundKind.TypeOfOperator: return CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); case BoundKind.ArrayCreation: return CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); case BoundKind.ArrayInitialization: return CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); case BoundKind.DefaultLiteral: return CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); case BoundKind.DefaultExpression: return CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); case BoundKind.BaseReference: return CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); case BoundKind.ThisReference: return CreateBoundThisReferenceOperation((BoundThisReference)boundNode); case BoundKind.AssignmentOperator: return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); case BoundKind.CompoundAssignmentOperator: return CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); case BoundKind.IncrementOperator: return CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); case BoundKind.BadExpression: return CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); case BoundKind.NewT: return CreateBoundNewTOperation((BoundNewT)boundNode); case BoundKind.NoPiaObjectCreationExpression: return CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); case BoundKind.UnaryOperator: return CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); case BoundKind.BinaryOperator: case BoundKind.UserDefinedConditionalLogicalOperator: return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); case BoundKind.TupleBinaryOperator: return CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); case BoundKind.ConditionalOperator: return CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); case BoundKind.NullCoalescingOperator: return CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); case BoundKind.AwaitExpression: return CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); case BoundKind.ArrayAccess: return CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); case BoundKind.NameOfOperator: return CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); case BoundKind.ThrowExpression: return CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); case BoundKind.AddressOfOperator: return CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); case BoundKind.ImplicitReceiver: return CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); case BoundKind.ConditionalAccess: return CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); case BoundKind.ConditionalReceiver: return CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); case BoundKind.FieldEqualsValue: return CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); case BoundKind.PropertyEqualsValue: return CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); case BoundKind.ParameterEqualsValue: return CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); case BoundKind.Block: return CreateBoundBlockOperation((BoundBlock)boundNode); case BoundKind.ContinueStatement: return CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); case BoundKind.BreakStatement: return CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); case BoundKind.YieldBreakStatement: return CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); case BoundKind.GotoStatement: return CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); case BoundKind.NoOpStatement: return CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); case BoundKind.IfStatement: return CreateBoundIfStatementOperation((BoundIfStatement)boundNode); case BoundKind.WhileStatement: return CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); case BoundKind.DoStatement: return CreateBoundDoStatementOperation((BoundDoStatement)boundNode); case BoundKind.ForStatement: return CreateBoundForStatementOperation((BoundForStatement)boundNode); case BoundKind.ForEachStatement: return CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); case BoundKind.TryStatement: return CreateBoundTryStatementOperation((BoundTryStatement)boundNode); case BoundKind.CatchBlock: return CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); case BoundKind.FixedStatement: return CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); case BoundKind.UsingStatement: return CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); case BoundKind.ThrowStatement: return CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); case BoundKind.ReturnStatement: return CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); case BoundKind.YieldReturnStatement: return CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); case BoundKind.LockStatement: return CreateBoundLockStatementOperation((BoundLockStatement)boundNode); case BoundKind.BadStatement: return CreateBoundBadStatementOperation((BoundBadStatement)boundNode); case BoundKind.LocalDeclaration: return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); case BoundKind.LabelStatement: return CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); case BoundKind.LabeledStatement: return CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); case BoundKind.ExpressionStatement: return CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return CreateBoundTupleOperation((BoundTupleExpression)boundNode); case BoundKind.UnconvertedInterpolatedString: throw ExceptionUtilities.Unreachable; case BoundKind.InterpolatedString: return CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); case BoundKind.StringInsert: return CreateBoundInterpolationOperation((BoundStringInsert)boundNode); case BoundKind.LocalFunctionStatement: return CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); case BoundKind.AnonymousObjectCreationExpression: return CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); case BoundKind.AnonymousPropertyDeclaration: throw ExceptionUtilities.Unreachable; case BoundKind.ConstantPattern: return CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); case BoundKind.DeclarationPattern: return CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); case BoundKind.RecursivePattern: return CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); case BoundKind.ITuplePattern: return CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); case BoundKind.DiscardPattern: return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); case BoundKind.BinaryPattern: return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); case BoundKind.NegatedPattern: return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); case BoundKind.RelationalPattern: return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); case BoundKind.TypePattern: return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); case BoundKind.SwitchStatement: return CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); case BoundKind.SwitchLabel: return CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); case BoundKind.IsPatternExpression: return CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); case BoundKind.QueryClause: return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); case BoundKind.DelegateCreationExpression: return CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); case BoundKind.RangeVariable: return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); case BoundKind.ConstructorMethodBody: return CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); case BoundKind.NonConstructorMethodBody: return CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); case BoundKind.DiscardExpression: return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); case BoundKind.NullCoalescingAssignmentOperator: return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); case BoundKind.FromEndIndexExpression: return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); case BoundKind.RangeExpression: return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); case BoundKind.SwitchSection: return CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); case BoundKind.UnconvertedConditionalOperator: throw ExceptionUtilities.Unreachable; case BoundKind.UnconvertedSwitchExpression: throw ExceptionUtilities.Unreachable; case BoundKind.ConvertedSwitchExpression: return CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); case BoundKind.SwitchExpressionArm: return CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); case BoundKind.ObjectOrCollectionValuePlaceholder: return CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); case BoundKind.FunctionPointerInvocation: return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); case BoundKind.UnconvertedAddressOfOperator: return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); case BoundKind.Attribute: case BoundKind.ArgList: case BoundKind.ArgListOperator: case BoundKind.ConvertedStackAllocExpression: case BoundKind.FixedLocalCollectionInitializer: case BoundKind.GlobalStatementInitializer: case BoundKind.HostObjectMemberReference: case BoundKind.MakeRefOperator: case BoundKind.MethodGroup: case BoundKind.NamespaceExpression: case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PreviousSubmissionReference: case BoundKind.RefTypeOperator: case BoundKind.RefValueOperator: case BoundKind.Sequence: case BoundKind.StackAllocArrayCreation: case BoundKind.TypeExpression: case BoundKind.TypeOrValueExpression: case BoundKind.IndexOrRangePatternIndexerAccess: ConstantValue? constantValue = (boundNode as BoundExpression)?.ConstantValue; bool isImplicit = boundNode.WasCompilerGenerated; if (!isImplicit) { switch (boundNode.Kind) { case BoundKind.FixedLocalCollectionInitializer: isImplicit = true; break; } } ImmutableArray<IOperation> children = GetIOperationChildren(boundNode); return new NoneOperation(children, _semanticModel, boundNode.Syntax, type: null, constantValue, isImplicit: isImplicit); default: // If you're hitting this because the IOperation test hook has failed, see // <roslyn-root>/docs/Compilers/IOperation Test Hook.md for instructions on how to fix. throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } public ImmutableArray<TOperation> CreateFromArray<TBoundNode, TOperation>(ImmutableArray<TBoundNode> boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation { if (boundNodes.IsDefault) { return ImmutableArray<TOperation>.Empty; } var builder = ArrayBuilder<TOperation>.GetInstance(boundNodes.Length); foreach (var node in boundNodes) { builder.AddIfNotNull((TOperation)Create(node)); } return builder.ToImmutableAndFree(); } private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) { return new MethodBodyOperation( (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) { return new ConstructorBodyOperation( boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal ImmutableArray<IOperation> GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) { var children = boundNodeWithChildren.Children; if (children.IsDefaultOrEmpty) { return ImmutableArray<IOperation>.Empty; } var builder = ArrayBuilder<IOperation>.GetInstance(children.Length); foreach (BoundNode? childNode in children) { if (childNode == null) { continue; } IOperation operation = Create(childNode); builder.Add(operation); } return builder.ToImmutableAndFree(); } internal ImmutableArray<IVariableDeclaratorOperation> CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (declarationSyntax as VariableDeclarationSyntax)?.Variables[0] ?? declarationSyntax)); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var multipleDeclaration = (BoundMultipleLocalDeclarationsBase)declaration; var builder = ArrayBuilder<IVariableDeclaratorOperation>.GetInstance(multipleDeclaration.LocalDeclarations.Length); foreach (var decl in multipleDeclaration.LocalDeclarations) { builder.Add((IVariableDeclaratorOperation)CreateVariableDeclaratorInternal(decl, decl.Syntax)); } return builder.ToImmutableAndFree(); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) { SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; ITypeSymbol? type = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructValuePlaceholder.WasCompilerGenerated; return new PlaceholderOperation(PlaceholderKind.Unspecified, _semanticModel, syntax, type, isImplicit); } private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) { IOperation target = Create(boundDeconstructionAssignmentOperator.Left); // Skip the synthetic deconstruction conversion wrapping the right operand. This is a compiler-generated conversion that we don't want to reflect // in the public API because it's an implementation detail. IOperation value = Create(boundDeconstructionAssignmentOperator.Right.Operand); SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; ITypeSymbol? type = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructionAssignmentOperator.WasCompilerGenerated; return new DeconstructionAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCallOperation(BoundCall boundCall) { MethodSymbol targetMethod = boundCall.Method; SyntaxNode syntax = boundCall.Syntax; ITypeSymbol? type = boundCall.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCall.ConstantValue; bool isImplicit = boundCall.WasCompilerGenerated; if (!boundCall.OriginalMethodsOpt.IsDefault || IsMethodInvalid(boundCall.ResultKind, targetMethod)) { ImmutableArray<IOperation> children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCall).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(targetMethod, boundCall.ReceiverOpt); IOperation? receiver = CreateReceiverOperation(boundCall.ReceiverOpt, targetMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCall); return new InvocationOperation(targetMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) { ITypeSymbol? type = boundFunctionPointerInvocation.GetPublicTypeSymbol(); SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; bool isImplicit = boundFunctionPointerInvocation.WasCompilerGenerated; ImmutableArray<IOperation> children; if (boundFunctionPointerInvocation.ResultKind != LookupResultKind.Viable) { children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } children = GetIOperationChildren(boundFunctionPointerInvocation); return new NoneOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) { return new AddressOfOperation( Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); } internal ImmutableArray<IOperation> CreateIgnoredDimensions(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { BoundTypeExpression? declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); return CreateFromArray<BoundExpression, IOperation>(declaredTypeOpt.BoundDimensionsOpt); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var declarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; ImmutableArray<BoundExpression> dimensions; if (declarations.Length > 0) { BoundTypeExpression? declaredTypeOpt = declarations[0].DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); dimensions = declaredTypeOpt.BoundDimensionsOpt; } else { dimensions = ImmutableArray<BoundExpression>.Empty; } return CreateFromArray<BoundExpression, IOperation>(dimensions); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) { ILocalSymbol local = boundLocal.LocalSymbol.GetPublicSymbol(); bool isDeclaration = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; SyntaxNode syntax = boundLocal.Syntax; ITypeSymbol? type = boundLocal.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLocal.ConstantValue; bool isImplicit = boundLocal.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation localReference = CreateBoundLocalOperation(boundLocal, createDeclaration: false); return new DeclarationExpressionOperation(localReference, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } return new LocalReferenceOperation(local, isDeclaration, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) { IFieldSymbol field = boundFieldAccess.FieldSymbol.GetPublicSymbol(); bool isDeclaration = boundFieldAccess.IsDeclaration; SyntaxNode syntax = boundFieldAccess.Syntax; ITypeSymbol? type = boundFieldAccess.GetPublicTypeSymbol(); ConstantValue? constantValue = boundFieldAccess.ConstantValue; bool isImplicit = boundFieldAccess.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation fieldAccess = CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false); return new DeclarationExpressionOperation(fieldAccess, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } IOperation? instance = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); return new FieldReferenceOperation(field, isDeclaration, instance, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) { switch (boundNode) { case BoundPropertyAccess boundPropertyAccess: return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); case BoundObjectInitializerMember boundObjectInitializerMember: return boundObjectInitializerMember.MemberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); case BoundIndexerAccess boundIndexerAccess: return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); default: throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) { IOperation? instance = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); var arguments = ImmutableArray<IArgumentOperation>.Empty; IPropertySymbol property = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); SyntaxNode syntax = boundPropertyAccess.Syntax; ITypeSymbol? type = boundPropertyAccess.GetPublicTypeSymbol(); bool isImplicit = boundPropertyAccess.WasCompilerGenerated; return new PropertyReferenceOperation(property, arguments, instance, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) { PropertySymbol property = boundIndexerAccess.Indexer; SyntaxNode syntax = boundIndexerAccess.Syntax; ITypeSymbol? type = boundIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundIndexerAccess.WasCompilerGenerated; if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundIndexerAccess, isObjectOrCollectionInitializer: false); IOperation? instance = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, instance, _semanticModel, syntax, type, isImplicit); } private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) { IEventSymbol @event = boundEventAccess.EventSymbol.GetPublicSymbol(); IOperation? instance = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); SyntaxNode syntax = boundEventAccess.Syntax; ITypeSymbol? type = boundEventAccess.GetPublicTypeSymbol(); bool isImplicit = boundEventAccess.WasCompilerGenerated; return new EventReferenceOperation(@event, instance, _semanticModel, syntax, type, isImplicit); } private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) { IOperation eventReference = CreateBoundEventAccessOperation(boundEventAssignmentOperator); IOperation handlerValue = Create(boundEventAssignmentOperator.Argument); SyntaxNode syntax = boundEventAssignmentOperator.Syntax; bool adds = boundEventAssignmentOperator.IsAddition; ITypeSymbol? type = boundEventAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundEventAssignmentOperator.WasCompilerGenerated; return new EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, syntax, type, isImplicit); } private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) { IParameterSymbol parameter = boundParameter.ParameterSymbol.GetPublicSymbol(); SyntaxNode syntax = boundParameter.Syntax; ITypeSymbol? type = boundParameter.GetPublicTypeSymbol(); bool isImplicit = boundParameter.WasCompilerGenerated; return new ParameterReferenceOperation(parameter, _semanticModel, syntax, type, isImplicit); } internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) { SyntaxNode syntax = boundLiteral.Syntax; ITypeSymbol? type = boundLiteral.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLiteral.ConstantValue; bool isImplicit = boundLiteral.WasCompilerGenerated || @implicit; return new LiteralOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) { SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; ITypeSymbol? type = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); Debug.Assert(type is not null); bool isImplicit = boundAnonymousObjectCreationExpression.WasCompilerGenerated; ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) { MethodSymbol constructor = boundObjectCreationExpression.Constructor; SyntaxNode syntax = boundObjectCreationExpression.Syntax; ITypeSymbol? type = boundObjectCreationExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundObjectCreationExpression.ConstantValue; bool isImplicit = boundObjectCreationExpression.WasCompilerGenerated; if (boundObjectCreationExpression.ResultKind == LookupResultKind.OverloadResolutionFailure || constructor == null || constructor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } else if (boundObjectCreationExpression.Type.IsAnonymousType) { // Workaround for https://github.com/dotnet/roslyn/issues/28157 Debug.Assert(isImplicit); Debug.Assert(type is not null); ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers( boundObjectCreationExpression.Arguments, declarations: ImmutableArray<BoundAnonymousPropertyDeclaration>.Empty, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundObjectCreationExpression); IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundObjectCreationExpression.InitializerExpressionOpt); return new ObjectCreationOperation(constructor.GetPublicSymbol(), initializer, arguments, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) { IOperation operand = Create(boundWithExpression.Receiver); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); MethodSymbol? constructor = boundWithExpression.CloneMethod; SyntaxNode syntax = boundWithExpression.Syntax; ITypeSymbol? type = boundWithExpression.GetPublicTypeSymbol(); bool isImplicit = boundWithExpression.WasCompilerGenerated; return new WithOperation(operand, constructor.GetPublicSymbol(), initializer, _semanticModel, syntax, type, isImplicit); } private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicObjectCreationExpression.Arguments); ImmutableArray<string> argumentNames = boundDynamicObjectCreationExpression.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicObjectCreationExpression.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; ITypeSymbol? type = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectCreationExpression.WasCompilerGenerated; return new DynamicObjectCreationOperation(initializer, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) { switch (receiver) { case BoundObjectOrCollectionValuePlaceholder implicitReceiver: return CreateBoundDynamicMemberAccessOperation(implicitReceiver, typeArgumentsOpt: ImmutableArray<TypeSymbol>.Empty, memberName: "Add", implicitReceiver.Syntax, type: null, isImplicit: true); case BoundMethodGroup methodGroup: return CreateBoundDynamicMemberAccessOperation(methodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(methodGroup.TypeArgumentsOpt), methodGroup.Name, methodGroup.Syntax, methodGroup.GetPublicTypeSymbol(), methodGroup.WasCompilerGenerated); default: return Create(receiver); } } private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicInvocation.Arguments); ImmutableArray<string> argumentNames = boundDynamicInvocation.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicInvocation.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicInvocation.Syntax; ITypeSymbol? type = boundDynamicInvocation.GetPublicTypeSymbol(); bool isImplicit = boundDynamicInvocation.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicIndexerAccess: return Create(boundDynamicIndexerAccess.Receiver); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } internal ImmutableArray<IOperation> CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicAccess: return CreateFromArray<BoundExpression, IOperation>(boundDynamicAccess.Arguments); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateFromArray<BoundExpression, IOperation>(boundObjectInitializerMember.Arguments); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) { IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); ImmutableArray<string> argumentNames = boundDynamicIndexerAccess.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicIndexerAccess.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; ITypeSymbol? type = boundDynamicIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundDynamicIndexerAccess.WasCompilerGenerated; return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); SyntaxNode syntax = boundObjectInitializerExpression.Syntax; ITypeSymbol? type = boundObjectInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; ITypeSymbol? type = boundCollectionInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundCollectionInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) { Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; SyntaxNode syntax = boundObjectInitializerMember.Syntax; ITypeSymbol? type = boundObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerMember.WasCompilerGenerated; if ((object?)memberSymbol == null) { Debug.Assert(boundObjectInitializerMember.Type.IsDynamic()); IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); ImmutableArray<string> argumentNames = boundObjectInitializerMember.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundObjectInitializerMember.ArgumentRefKindsOpt.NullToEmpty(); return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } switch (memberSymbol.Kind) { case SymbolKind.Field: var field = (FieldSymbol)memberSymbol; bool isDeclaration = false; return new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration, createReceiver(), _semanticModel, syntax, type, constantValue: null, isImplicit); case SymbolKind.Event: var eventSymbol = (EventSymbol)memberSymbol; return new EventReferenceOperation(eventSymbol.GetPublicSymbol(), createReceiver(), _semanticModel, syntax, type, isImplicit); case SymbolKind.Property: var property = (PropertySymbol)memberSymbol; ImmutableArray<IArgumentOperation> arguments; if (!boundObjectInitializerMember.Arguments.IsEmpty) { // In nested member initializers, the property is not actually set. Instead, it is retrieved for a series of Add method calls or nested property setter calls, // so we need to use the getter for this property MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); if (accessor == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } arguments = DeriveArguments(boundObjectInitializerMember, isObjectOrCollectionInitializer); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, createReceiver(), _semanticModel, syntax, type, isImplicit); default: throw ExceptionUtilities.Unreachable; } IOperation? createReceiver() => memberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); } private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) { IOperation instanceReceiver = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); string memberName = boundDynamicObjectInitializerMember.MemberName; ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; ITypeSymbol containingType = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; ITypeSymbol? type = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectInitializerMember.WasCompilerGenerated; return new DynamicMemberReferenceOperation(instanceReceiver, memberName, typeArguments, containingType, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) { MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; IOperation? receiver = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCollectionElementInitializer); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCollectionElementInitializer.ConstantValue; bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; if (IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); return new InvocationOperation(addMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) { return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation( BoundExpression? receiver, ImmutableArray<TypeSymbol> typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) { ITypeSymbol? containingType = null; if (receiver?.Kind == BoundKind.TypeExpression) { containingType = receiver.GetPublicTypeSymbol(); receiver = null; } ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; if (!typeArgumentsOpt.IsDefault) { typeArguments = typeArgumentsOpt.GetPublicSymbols(); } IOperation? instance = Create(receiver); return new DynamicMemberReferenceOperation(instance, memberName, typeArguments, containingType, _semanticModel, syntaxNode, type, isImplicit); } private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundCollectionElementInitializer.Arguments); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames: ImmutableArray<string>.Empty, argumentRefKinds: ImmutableArray<RefKind>.Empty, _semanticModel, syntax, type, isImplicit); } private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) { // We want to ensure that we never see the UnboundLambda node, and that we don't end up having two different IOperation // nodes for the lambda expression. So, we ask the semantic model for the IOperation node for the unbound lambda syntax. // We are counting on the fact that will do the error recovery and actually create the BoundLambda node appropriate for // this syntax node. BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); return Create(boundLambda); } private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) { IMethodSymbol symbol = boundLambda.Symbol.GetPublicSymbol(); IBlockOperation body = (IBlockOperation)Create(boundLambda.Body); SyntaxNode syntax = boundLambda.Syntax; bool isImplicit = boundLambda.WasCompilerGenerated; return new AnonymousFunctionOperation(symbol, body, _semanticModel, syntax, isImplicit); } private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) { IBlockOperation? body = (IBlockOperation?)Create(boundLocalFunctionStatement.Body); IBlockOperation? ignoredBody = boundLocalFunctionStatement is { BlockBody: { }, ExpressionBody: { } exprBody } ? (IBlockOperation?)Create(exprBody) : null; IMethodSymbol symbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); SyntaxNode syntax = boundLocalFunctionStatement.Syntax; bool isImplicit = boundLocalFunctionStatement.WasCompilerGenerated; return new LocalFunctionOperation(symbol, body, ignoredBody, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) { Debug.Assert(!forceOperandImplicitLiteral || boundConversion.Operand is BoundLiteral); bool isImplicit = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; BoundExpression boundOperand = boundConversion.Operand; if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { // https://github.com/dotnet/roslyn/issues/54505 Support interpolation handlers in conversions Debug.Assert(!forceOperandImplicitLiteral); Debug.Assert(boundOperand is BoundInterpolatedString { InterpolationData: not null } or BoundBinaryOperator { InterpolatedStringHandlerData: not null }); var interpolatedString = Create(boundOperand); return new NoneOperation(ImmutableArray.Create(interpolatedString), _semanticModel, boundConversion.Syntax, boundConversion.GetPublicTypeSymbol(), boundConversion.ConstantValue, isImplicit); } if (boundConversion.ConversionKind == CSharp.ConversionKind.MethodGroup) { SyntaxNode syntax = boundConversion.Syntax; ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); Debug.Assert(!forceOperandImplicitLiteral); if (boundConversion.Type is FunctionPointerTypeSymbol) { Debug.Assert(boundConversion.SymbolOpt is object); return new AddressOfOperation( CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, type, boundConversion.WasCompilerGenerated); } // We don't check HasErrors on the conversion here because if we actually have a MethodGroup conversion, // overload resolution succeeded. The resulting method could be invalid for other reasons, but we don't // hide the resolved method. IOperation target = CreateDelegateTargetOperation(boundConversion); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { SyntaxNode syntax = boundConversion.Syntax; if (syntax.IsMissing) { // If the underlying syntax IsMissing, then that means we're in case where the compiler generated a piece of syntax to fill in for // an error, such as this case: // // int i = ; // // Semantic model has a special case here that we match: if the underlying syntax is missing, don't create a conversion expression, // and instead directly return the operand, which will be a BoundBadExpression. When we generate a node for the BoundBadExpression, // the resulting IOperation will also have a null Type. Debug.Assert(boundOperand.Kind == BoundKind.BadExpression || ((boundOperand as BoundLambda)?.Body.Statements.SingleOrDefault() as BoundReturnStatement)?. ExpressionOpt?.Kind == BoundKind.BadExpression); Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } BoundConversion correctedConversionNode = boundConversion; Conversion conversion = boundConversion.Conversion; if (boundOperand.Syntax == boundConversion.Syntax) { if (boundOperand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(boundOperand.Type, boundConversion.Type, TypeCompareKind.ConsiderEverything2)) { // Erase this conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } else { // Make this conversion implicit isImplicit = true; } } if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && boundOperand.Kind == BoundKind.Conversion) { var nestedConversion = (BoundConversion)boundOperand; BoundExpression nestedOperand = nestedConversion.Operand; if (nestedConversion.Syntax == nestedOperand.Syntax && nestedConversion.ExplicitCastInCode && nestedOperand.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything2)) { // Let's erase the nested conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion. // We need to use conversion information from the nested conversion because that is where the real conversion // information is stored. conversion = nestedConversion.Conversion; correctedConversionNode = nestedConversion; } } ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConversion.ConstantValue; // If this is a lambda or method group conversion to a delegate type, we return a delegate creation instead of a conversion if ((boundOperand.Kind == BoundKind.Lambda || boundOperand.Kind == BoundKind.UnboundLambda || boundOperand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) { IOperation target = CreateDelegateTargetOperation(correctedConversionNode); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { bool isTryCast = false; // Checked conversions only matter if the conversion is a Numeric conversion. Don't have true unless the conversion is actually numeric. bool isChecked = conversion.IsNumeric && boundConversion.Checked; IOperation operand = forceOperandImplicitLiteral ? CreateBoundLiteralOperation((BoundLiteral)correctedConversionNode.Operand, @implicit: true) : Create(correctedConversionNode.Operand); return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue, isImplicit); } } } private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) { IOperation operand = Create(boundAsOperator.Operand); SyntaxNode syntax = boundAsOperator.Syntax; Conversion conversion = BoundNode.GetConversion(boundAsOperator.OperandConversion, boundAsOperator.OperandPlaceholder); bool isTryCast = true; bool isChecked = false; ITypeSymbol? type = boundAsOperator.GetPublicTypeSymbol(); bool isImplicit = boundAsOperator.WasCompilerGenerated; return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) { IOperation target = CreateDelegateTargetOperation(boundDelegateCreationExpression); SyntaxNode syntax = boundDelegateCreationExpression.Syntax; ITypeSymbol? type = boundDelegateCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDelegateCreationExpression.WasCompilerGenerated; return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) { bool isVirtual = (methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls; IOperation? instance = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); SyntaxNode bindingSyntax = boundMethodGroup.Syntax; ITypeSymbol? bindingType = null; bool isImplicit = boundMethodGroup.WasCompilerGenerated; return new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), isVirtual, instance, _semanticModel, bindingSyntax, bindingType, boundMethodGroup.WasCompilerGenerated); } private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) { IOperation value = Create(boundIsOperator.Operand); ITypeSymbol? typeOperand = boundIsOperator.TargetType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundIsOperator.Syntax; ITypeSymbol? type = boundIsOperator.GetPublicTypeSymbol(); bool isNegated = false; bool isImplicit = boundIsOperator.WasCompilerGenerated; return new IsTypeOperation(value, typeOperand, isNegated, _semanticModel, syntax, type, isImplicit); } private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) { ITypeSymbol? typeOperand = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundSizeOfOperator.Syntax; ITypeSymbol? type = boundSizeOfOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundSizeOfOperator.ConstantValue; bool isImplicit = boundSizeOfOperator.WasCompilerGenerated; return new SizeOfOperation(typeOperand, _semanticModel, syntax, type, constantValue, isImplicit); } private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) { ITypeSymbol? typeOperand = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundTypeOfOperator.Syntax; ITypeSymbol? type = boundTypeOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundTypeOfOperator.WasCompilerGenerated; return new TypeOfOperation(typeOperand, _semanticModel, syntax, type, isImplicit); } private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) { ImmutableArray<IOperation> dimensionSizes = CreateFromArray<BoundExpression, IOperation>(boundArrayCreation.Bounds); IArrayInitializerOperation? arrayInitializer = (IArrayInitializerOperation?)Create(boundArrayCreation.InitializerOpt); SyntaxNode syntax = boundArrayCreation.Syntax; ITypeSymbol? type = boundArrayCreation.GetPublicTypeSymbol(); bool isImplicit = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); return new ArrayCreationOperation(dimensionSizes, arrayInitializer, _semanticModel, syntax, type, isImplicit); } private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) { ImmutableArray<IOperation> elementValues = CreateFromArray<BoundExpression, IOperation>(boundArrayInitialization.Initializers); SyntaxNode syntax = boundArrayInitialization.Syntax; bool isImplicit = boundArrayInitialization.WasCompilerGenerated; return new ArrayInitializerOperation(elementValues, _semanticModel, syntax, isImplicit); } private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) { SyntaxNode syntax = boundDefaultLiteral.Syntax; ConstantValue? constantValue = boundDefaultLiteral.ConstantValue; bool isImplicit = boundDefaultLiteral.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type: null, constantValue, isImplicit); } private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) { SyntaxNode syntax = boundDefaultExpression.Syntax; ITypeSymbol? type = boundDefaultExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundDefaultExpression.ConstantValue; bool isImplicit = boundDefaultExpression.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundBaseReference.Syntax; ITypeSymbol? type = boundBaseReference.GetPublicTypeSymbol(); bool isImplicit = boundBaseReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundThisReference.Syntax; ITypeSymbol? type = boundThisReference.GetPublicTypeSymbol(); bool isImplicit = boundThisReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { return IsMemberInitializer(boundAssignmentOperator) ? (IOperation)CreateBoundMemberInitializerOperation(boundAssignmentOperator) : CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); } private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) => boundAssignmentOperator.Right?.Kind == BoundKind.ObjectInitializerExpression || boundAssignmentOperator.Right?.Kind == BoundKind.CollectionInitializerExpression; private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(!IsMemberInitializer(boundAssignmentOperator)); IOperation target = Create(boundAssignmentOperator.Left); IOperation value = Create(boundAssignmentOperator.Right); bool isRef = boundAssignmentOperator.IsRef; SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundAssignmentOperator.ConstantValue; bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicit); } private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(IsMemberInitializer(boundAssignmentOperator)); IOperation initializedMember = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new MemberInitializerOperation(initializedMember, initializer, _semanticModel, syntax, type, isImplicit); } private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) { IOperation target = Create(boundCompoundAssignmentOperator.Left); IOperation value = Create(boundCompoundAssignmentOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); Conversion inConversion = BoundNode.GetConversion(boundCompoundAssignmentOperator.LeftConversion, boundCompoundAssignmentOperator.LeftPlaceholder); Conversion outConversion = BoundNode.GetConversion(boundCompoundAssignmentOperator.FinalConversion, boundCompoundAssignmentOperator.FinalPlaceholder); bool isLifted = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); bool isChecked = boundCompoundAssignmentOperator.Operator.Kind.IsChecked(); IMethodSymbol operatorMethod = boundCompoundAssignmentOperator.Operator.Method.GetPublicSymbol(); SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; ITypeSymbol? type = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundCompoundAssignmentOperator.WasCompilerGenerated; return new CompoundAssignmentOperation(inConversion, outConversion, operatorKind, isLifted, isChecked, operatorMethod, target, value, _semanticModel, syntax, type, isImplicit); } private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) { OperationKind operationKind = Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? OperationKind.Decrement : OperationKind.Increment; bool isPostfix = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); bool isLifted = boundIncrementOperator.OperatorKind.IsLifted(); bool isChecked = boundIncrementOperator.OperatorKind.IsChecked(); IOperation target = Create(boundIncrementOperator.Operand); IMethodSymbol? operatorMethod = boundIncrementOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundIncrementOperator.Syntax; ITypeSymbol? type = boundIncrementOperator.GetPublicTypeSymbol(); bool isImplicit = boundIncrementOperator.WasCompilerGenerated; return new IncrementOrDecrementOperation(isPostfix, isLifted, isChecked, target, operatorMethod, operationKind, _semanticModel, syntax, type, isImplicit); } private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) { SyntaxNode syntax = boundBadExpression.Syntax; // We match semantic model here: if the expression IsMissing, we have a null type, rather than the ErrorType of the bound node. ITypeSymbol? type = syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol(); // if child has syntax node point to same syntax node as bad expression, then this invalid expression is implicit bool isImplicit = boundBadExpression.WasCompilerGenerated || boundBadExpression.ChildBoundNodes.Any(e => e?.Syntax == boundBadExpression.Syntax); var children = CreateFromArray<BoundExpression, IOperation>(boundBadExpression.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundNewT.InitializerExpressionOpt); SyntaxNode syntax = boundNewT.Syntax; ITypeSymbol? type = boundNewT.GetPublicTypeSymbol(); bool isImplicit = boundNewT.WasCompilerGenerated; return new TypeParameterObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(creation.InitializerExpressionOpt); SyntaxNode syntax = creation.Syntax; ITypeSymbol? type = creation.GetPublicTypeSymbol(); bool isImplicit = creation.WasCompilerGenerated; return new NoPiaObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) { UnaryOperatorKind unaryOperatorKind = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); IOperation operand = Create(boundUnaryOperator.Operand); IMethodSymbol? operatorMethod = boundUnaryOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundUnaryOperator.Syntax; ITypeSymbol? type = boundUnaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundUnaryOperator.ConstantValue; bool isLifted = boundUnaryOperator.OperatorKind.IsLifted(); bool isChecked = boundUnaryOperator.OperatorKind.IsChecked(); bool isImplicit = boundUnaryOperator.WasCompilerGenerated; return new UnaryOperation(unaryOperatorKind, operand, isLifted, isChecked, operatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) { if (boundBinaryOperatorBase is BoundBinaryOperator { InterpolatedStringHandlerData: not null } binary) { return CreateBoundInterpolatedStringBinaryOperator(binary); } // Binary operators can be nested _many_ levels deep, and cause a stack overflow if we manually recurse. // To solve this, we use a manual stack for the left side. var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = boundBinaryOperatorBase; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null and not BoundBinaryOperator { InterpolatedStringHandlerData: not null }); Debug.Assert(stack.Count > 0); IOperation? left = null; while (stack.TryPop(out currentBinary)) { left ??= Create(currentBinary.Left); IOperation right = Create(currentBinary.Right); left = currentBinary switch { BoundBinaryOperator binaryOp => CreateBoundBinaryOperatorOperation(binaryOp, left, right), BoundUserDefinedConditionalLogicalOperator logicalOp => createBoundUserDefinedConditionalLogicalOperator(logicalOp, left, right), { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; } Debug.Assert(left is not null && stack.Count == 0); stack.Free(); return left; IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol operatorMethod = boundBinaryOperator.LogicalOperator.GetPublicSymbol(); IMethodSymbol unaryOperatorMethod = boundBinaryOperator.OperatorKind.Operator() == CSharp.BinaryOperatorKind.And ? boundBinaryOperator.FalseOperator.GetPublicSymbol() : boundBinaryOperator.TrueOperator.GetPublicSymbol(); SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } } private IBinaryOperation CreateBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol? operatorMethod = boundBinaryOperator.Method.GetPublicSymbol(); IMethodSymbol? unaryOperatorMethod = null; // For dynamic logical operator MethodOpt is actually the unary true/false operator if (boundBinaryOperator.Type.IsDynamic() && (operatorKind == BinaryOperatorKind.ConditionalAnd || operatorKind == BinaryOperatorKind.ConditionalOr) && operatorMethod?.Parameters.Length == 1) { unaryOperatorMethod = operatorMethod; operatorMethod = null; } SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundInterpolatedStringBinaryOperator(BoundBinaryOperator boundBinaryOperator) { Debug.Assert(boundBinaryOperator.InterpolatedStringHandlerData is not null); Func<BoundInterpolatedString, int, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createInterpolatedString = createInterpolatedStringOperand; Func<BoundBinaryOperator, IOperation, IOperation, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createBinaryOperator = createBoundBinaryOperatorOperation; return boundBinaryOperator.RewriteInterpolatedStringAddition((this, boundBinaryOperator.InterpolatedStringHandlerData.GetValueOrDefault()), createInterpolatedString, createBinaryOperator); static IInterpolatedStringOperation createInterpolatedStringOperand( BoundInterpolatedString boundInterpolatedString, int i, (CSharpOperationFactory @this, InterpolatedStringHandlerData Data) arg) => [email protected](boundInterpolatedString, arg.Data.PositionInfo[i]); static IBinaryOperation createBoundBinaryOperatorOperation( BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right, (CSharpOperationFactory @this, InterpolatedStringHandlerData _) arg) => [email protected](boundBinaryOperator, left, right); } private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) { IOperation left = Create(boundTupleBinaryOperator.Left); IOperation right = Create(boundTupleBinaryOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); SyntaxNode syntax = boundTupleBinaryOperator.Syntax; ITypeSymbol? type = boundTupleBinaryOperator.GetPublicTypeSymbol(); bool isImplicit = boundTupleBinaryOperator.WasCompilerGenerated; return new TupleBinaryOperation(operatorKind, left, right, _semanticModel, syntax, type, isImplicit); } private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) { IOperation condition = Create(boundConditionalOperator.Condition); IOperation whenTrue = Create(boundConditionalOperator.Consequence); IOperation whenFalse = Create(boundConditionalOperator.Alternative); bool isRef = boundConditionalOperator.IsRef; SyntaxNode syntax = boundConditionalOperator.Syntax; ITypeSymbol? type = boundConditionalOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConditionalOperator.ConstantValue; bool isImplicit = boundConditionalOperator.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) { IOperation value = Create(boundNullCoalescingOperator.LeftOperand); IOperation whenNull = Create(boundNullCoalescingOperator.RightOperand); SyntaxNode syntax = boundNullCoalescingOperator.Syntax; ITypeSymbol? type = boundNullCoalescingOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundNullCoalescingOperator.ConstantValue; bool isImplicit = boundNullCoalescingOperator.WasCompilerGenerated; Conversion valueConversion = BoundNode.GetConversion(boundNullCoalescingOperator.LeftConversion, boundNullCoalescingOperator.LeftPlaceholder); if (valueConversion.Exists && !valueConversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } return new CoalesceOperation(value, whenNull, valueConversion, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) { IOperation target = Create(boundNode.LeftOperand); IOperation value = Create(boundNode.RightOperand); SyntaxNode syntax = boundNode.Syntax; ITypeSymbol? type = boundNode.GetPublicTypeSymbol(); bool isImplicit = boundNode.WasCompilerGenerated; return new CoalesceAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) { IOperation awaitedValue = Create(boundAwaitExpression.Expression); SyntaxNode syntax = boundAwaitExpression.Syntax; ITypeSymbol? type = boundAwaitExpression.GetPublicTypeSymbol(); bool isImplicit = boundAwaitExpression.WasCompilerGenerated; return new AwaitOperation(awaitedValue, _semanticModel, syntax, type, isImplicit); } private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) { IOperation arrayReference = Create(boundArrayAccess.Expression); ImmutableArray<IOperation> indices = CreateFromArray<BoundExpression, IOperation>(boundArrayAccess.Indices); SyntaxNode syntax = boundArrayAccess.Syntax; ITypeSymbol? type = boundArrayAccess.GetPublicTypeSymbol(); bool isImplicit = boundArrayAccess.WasCompilerGenerated; return new ArrayElementReferenceOperation(arrayReference, indices, _semanticModel, syntax, type, isImplicit); } private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) { IOperation argument = Create(boundNameOfOperator.Argument); SyntaxNode syntax = boundNameOfOperator.Syntax; ITypeSymbol? type = boundNameOfOperator.GetPublicTypeSymbol(); ConstantValue constantValue = boundNameOfOperator.ConstantValue; bool isImplicit = boundNameOfOperator.WasCompilerGenerated; return new NameOfOperation(argument, _semanticModel, syntax, type, constantValue, isImplicit); } private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) { IOperation expression = Create(boundThrowExpression.Expression); SyntaxNode syntax = boundThrowExpression.Syntax; ITypeSymbol? type = boundThrowExpression.GetPublicTypeSymbol(); bool isImplicit = boundThrowExpression.WasCompilerGenerated; return new ThrowOperation(expression, _semanticModel, syntax, type, isImplicit); } private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) { IOperation reference = Create(boundAddressOfOperator.Operand); SyntaxNode syntax = boundAddressOfOperator.Syntax; ITypeSymbol? type = boundAddressOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundAddressOfOperator.WasCompilerGenerated; return new AddressOfOperation(reference, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = boundImplicitReceiver.Syntax; ITypeSymbol? type = boundImplicitReceiver.GetPublicTypeSymbol(); bool isImplicit = boundImplicitReceiver.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) { IOperation operation = Create(boundConditionalAccess.Receiver); IOperation whenNotNull = Create(boundConditionalAccess.AccessExpression); SyntaxNode syntax = boundConditionalAccess.Syntax; ITypeSymbol? type = boundConditionalAccess.GetPublicTypeSymbol(); bool isImplicit = boundConditionalAccess.WasCompilerGenerated; return new ConditionalAccessOperation(operation, whenNotNull, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) { SyntaxNode syntax = boundConditionalReceiver.Syntax; ITypeSymbol? type = boundConditionalReceiver.GetPublicTypeSymbol(); bool isImplicit = boundConditionalReceiver.WasCompilerGenerated; return new ConditionalAccessInstanceOperation(_semanticModel, syntax, type, isImplicit); } private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) { ImmutableArray<IFieldSymbol> initializedFields = ImmutableArray.Create<IFieldSymbol>(boundFieldEqualsValue.Field.GetPublicSymbol()); IOperation value = Create(boundFieldEqualsValue.Value); SyntaxNode syntax = boundFieldEqualsValue.Syntax; bool isImplicit = boundFieldEqualsValue.WasCompilerGenerated; return new FieldInitializerOperation(initializedFields, boundFieldEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) { ImmutableArray<IPropertySymbol> initializedProperties = ImmutableArray.Create<IPropertySymbol>(boundPropertyEqualsValue.Property.GetPublicSymbol()); IOperation value = Create(boundPropertyEqualsValue.Value); SyntaxNode syntax = boundPropertyEqualsValue.Syntax; bool isImplicit = boundPropertyEqualsValue.WasCompilerGenerated; return new PropertyInitializerOperation(initializedProperties, boundPropertyEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) { IParameterSymbol parameter = boundParameterEqualsValue.Parameter.GetPublicSymbol(); IOperation value = Create(boundParameterEqualsValue.Value); SyntaxNode syntax = boundParameterEqualsValue.Syntax; bool isImplicit = boundParameterEqualsValue.WasCompilerGenerated; return new ParameterInitializerOperation(parameter, boundParameterEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) { ImmutableArray<IOperation> operations = CreateFromArray<BoundStatement, IOperation>(boundBlock.Statements); ImmutableArray<ILocalSymbol> locals = boundBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundBlock.Syntax; bool isImplicit = boundBlock.WasCompilerGenerated; return new BlockOperation(operations, locals, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) { ILabelSymbol target = boundContinueStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Continue; SyntaxNode syntax = boundContinueStatement.Syntax; bool isImplicit = boundContinueStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) { ILabelSymbol target = boundBreakStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Break; SyntaxNode syntax = boundBreakStatement.Syntax; bool isImplicit = boundBreakStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) { IOperation? returnedValue = null; SyntaxNode syntax = boundYieldBreakStatement.Syntax; bool isImplicit = boundYieldBreakStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldBreak, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) { ILabelSymbol target = boundGotoStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.GoTo; SyntaxNode syntax = boundGotoStatement.Syntax; bool isImplicit = boundGotoStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) { SyntaxNode syntax = boundNoOpStatement.Syntax; bool isImplicit = boundNoOpStatement.WasCompilerGenerated; return new EmptyOperation(_semanticModel, syntax, isImplicit); } private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) { IOperation condition = Create(boundIfStatement.Condition); IOperation whenTrue = Create(boundIfStatement.Consequence); IOperation? whenFalse = Create(boundIfStatement.AlternativeOpt); bool isRef = false; SyntaxNode syntax = boundIfStatement.Syntax; ITypeSymbol? type = null; ConstantValue? constantValue = null; bool isImplicit = boundIfStatement.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) { IOperation condition = Create(boundWhileStatement.Condition); IOperation body = Create(boundWhileStatement.Body); ImmutableArray<ILocalSymbol> locals = boundWhileStatement.Locals.GetPublicSymbols(); ILabelSymbol continueLabel = boundWhileStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundWhileStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = true; bool conditionIsUntil = false; SyntaxNode syntax = boundWhileStatement.Syntax; bool isImplicit = boundWhileStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) { IOperation condition = Create(boundDoStatement.Condition); IOperation body = Create(boundDoStatement.Body); ILabelSymbol continueLabel = boundDoStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundDoStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = false; bool conditionIsUntil = false; ImmutableArray<ILocalSymbol> locals = boundDoStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundDoStatement.Syntax; bool isImplicit = boundDoStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) { ImmutableArray<IOperation> before = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Initializer)); IOperation? condition = Create(boundForStatement.Condition); ImmutableArray<IOperation> atLoopBottom = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Increment)); IOperation body = Create(boundForStatement.Body); ImmutableArray<ILocalSymbol> locals = boundForStatement.OuterLocals.GetPublicSymbols(); ImmutableArray<ILocalSymbol> conditionLocals = boundForStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol continueLabel = boundForStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForStatement.Syntax; bool isImplicit = boundForStatement.WasCompilerGenerated; return new ForLoopOperation(before, conditionLocals, condition, atLoopBottom, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) { ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; ForEachLoopOperationInfo? info; if (enumeratorInfoOpt != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var compilation = (CSharpCompilation)_semanticModel.Compilation; var iDisposable = enumeratorInfoOpt.IsAsync ? compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : compilation.GetSpecialType(SpecialType.System_IDisposable); info = new ForEachLoopOperationInfo(enumeratorInfoOpt.ElementType.GetPublicSymbol(), enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), isAsynchronous: enumeratorInfoOpt.IsAsync, needsDispose: enumeratorInfoOpt.NeedsDisposal, knownToImplementIDisposable: enumeratorInfoOpt.NeedsDisposal ? compilation.Conversions. ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, iDisposable, ref discardedUseSiteInfo).IsImplicit : false, enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(), BoundNode.GetConversion(enumeratorInfoOpt.CurrentConversion, enumeratorInfoOpt.CurrentPlaceholder), BoundNode.GetConversion(boundForEachStatement.ElementConversion, boundForEachStatement.ElementPlaceholder), getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorInfo is { Method: { IsExtensionMethod: true } } getEnumeratorInfo ? Operation.SetParentOperation( DeriveArguments( getEnumeratorInfo.Method, getEnumeratorInfo.Arguments, argumentsToParametersOpt: default, getEnumeratorInfo.DefaultArguments, getEnumeratorInfo.Expanded, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), null) : default, disposeArguments: enumeratorInfoOpt.PatternDisposeInfo is object ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default); } else { info = null; } return info; } internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) { if (boundForEachStatement.DeconstructionOpt != null) { return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); } else if (boundForEachStatement.IterationErrorExpressionOpt != null) { return Create(boundForEachStatement.IterationErrorExpressionOpt); } else { Debug.Assert(boundForEachStatement.IterationVariables.Length == 1); var local = boundForEachStatement.IterationVariables[0]; // We use iteration variable type syntax as the underlying syntax node as there is no variable declarator syntax in the syntax tree. var declaratorSyntax = boundForEachStatement.IterationVariableType.Syntax; return new VariableDeclaratorOperation(local.GetPublicSymbol(), initializer: null, ignoredArguments: ImmutableArray<IOperation>.Empty, semanticModel: _semanticModel, syntax: declaratorSyntax, isImplicit: false); } } private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) { IOperation loopControlVariable = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); IOperation collection = Create(boundForEachStatement.Expression); var nextVariables = ImmutableArray<IOperation>.Empty; IOperation body = Create(boundForEachStatement.Body); ForEachLoopOperationInfo? info = GetForEachLoopOperatorInfo(boundForEachStatement); ImmutableArray<ILocalSymbol> locals = boundForEachStatement.IterationVariables.GetPublicSymbols(); ILabelSymbol continueLabel = boundForEachStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForEachStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForEachStatement.Syntax; bool isImplicit = boundForEachStatement.WasCompilerGenerated; bool isAsynchronous = boundForEachStatement.AwaitOpt != null; return new ForEachLoopOperation(loopControlVariable, collection, nextVariables, info, isAsynchronous, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) { var body = (IBlockOperation)Create(boundTryStatement.TryBlock); ImmutableArray<ICatchClauseOperation> catches = CreateFromArray<BoundCatchBlock, ICatchClauseOperation>(boundTryStatement.CatchBlocks); var @finally = (IBlockOperation?)Create(boundTryStatement.FinallyBlockOpt); SyntaxNode syntax = boundTryStatement.Syntax; bool isImplicit = boundTryStatement.WasCompilerGenerated; return new TryOperation(body, catches, @finally, exitLabel: null, _semanticModel, syntax, isImplicit); } private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) { IOperation? exceptionDeclarationOrExpression = CreateVariableDeclarator((BoundLocal?)boundCatchBlock.ExceptionSourceOpt); // The exception filter prologue is introduced during lowering, so should be null here. Debug.Assert(boundCatchBlock.ExceptionFilterPrologueOpt is null); IOperation? filter = Create(boundCatchBlock.ExceptionFilterOpt); IBlockOperation handler = (IBlockOperation)Create(boundCatchBlock.Body); ITypeSymbol exceptionType = boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol() ?? _semanticModel.Compilation.ObjectType; ImmutableArray<ILocalSymbol> locals = boundCatchBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundCatchBlock.Syntax; bool isImplicit = boundCatchBlock.WasCompilerGenerated; return new CatchClauseOperation(exceptionDeclarationOrExpression, exceptionType, locals, filter, handler, _semanticModel, syntax, isImplicit); } private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) { IVariableDeclarationGroupOperation variables = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); IOperation body = Create(boundFixedStatement.Body); ImmutableArray<ILocalSymbol> locals = boundFixedStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundFixedStatement.Syntax; bool isImplicit = boundFixedStatement.WasCompilerGenerated; return new FixedOperation(locals, variables, body, _semanticModel, syntax, isImplicit); } private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) { Debug.Assert((boundUsingStatement.DeclarationsOpt == null) != (boundUsingStatement.ExpressionOpt == null)); Debug.Assert(boundUsingStatement.ExpressionOpt is object || boundUsingStatement.Locals.Length > 0); IOperation resources = Create(boundUsingStatement.DeclarationsOpt ?? (BoundNode)boundUsingStatement.ExpressionOpt!); IOperation body = Create(boundUsingStatement.Body); ImmutableArray<ILocalSymbol> locals = boundUsingStatement.Locals.GetPublicSymbols(); bool isAsynchronous = boundUsingStatement.AwaitOpt != null; DisposeOperationInfo disposeOperationInfo = boundUsingStatement.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default; SyntaxNode syntax = boundUsingStatement.Syntax; bool isImplicit = boundUsingStatement.WasCompilerGenerated; return new UsingOperation(resources, body, locals, isAsynchronous, disposeOperationInfo, _semanticModel, syntax, isImplicit); } private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) { IOperation? thrownObject = Create(boundThrowStatement.ExpressionOpt); SyntaxNode syntax = boundThrowStatement.Syntax; ITypeSymbol? statementType = null; bool isImplicit = boundThrowStatement.WasCompilerGenerated; return new ThrowOperation(thrownObject, _semanticModel, syntax, statementType, isImplicit); } private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) { IOperation? returnedValue = Create(boundReturnStatement.ExpressionOpt); SyntaxNode syntax = boundReturnStatement.Syntax; bool isImplicit = boundReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.Return, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) { IOperation returnedValue = Create(boundYieldReturnStatement.Expression); SyntaxNode syntax = boundYieldReturnStatement.Syntax; bool isImplicit = boundYieldReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldReturn, _semanticModel, syntax, isImplicit); } private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) { // If there is no Enter2 method, then there will be no lock taken reference bool legacyMode = _semanticModel.Compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2) == null; ILocalSymbol? lockTakenSymbol = legacyMode ? null : new SynthesizedLocal((_semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart) as IMethodSymbol).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)_semanticModel.Compilation).GetSpecialType(SpecialType.System_Boolean)), SynthesizedLocalKind.LockTaken, syntaxOpt: boundLockStatement.Argument.Syntax).GetPublicSymbol(); IOperation lockedValue = Create(boundLockStatement.Argument); IOperation body = Create(boundLockStatement.Body); SyntaxNode syntax = boundLockStatement.Syntax; bool isImplicit = boundLockStatement.WasCompilerGenerated; return new LockOperation(lockedValue, body, lockTakenSymbol, _semanticModel, syntax, isImplicit); } private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) { SyntaxNode syntax = boundBadStatement.Syntax; // if child has syntax node point to same syntax node as bad statement, then this invalid statement is implicit bool isImplicit = boundBadStatement.WasCompilerGenerated || boundBadStatement.ChildBoundNodes.Any(e => e?.Syntax == boundBadStatement.Syntax); var children = CreateFromArray<BoundNode, IOperation>(boundBadStatement.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type: null, constantValue: null, isImplicit); } private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) { var node = boundLocalDeclaration.Syntax; var kind = node.Kind(); SyntaxNode varStatement; SyntaxNode varDeclaration; switch (kind) { case SyntaxKind.LocalDeclarationStatement: { var statement = (LocalDeclarationStatementSyntax)node; // this happen for simple int i = 0; // var statement points to LocalDeclarationStatementSyntax varStatement = statement; varDeclaration = statement.Declaration; break; } case SyntaxKind.VariableDeclarator: { // this happen for 'for loop' initializer // We generate a DeclarationGroup for this scenario to maintain tree shape consistency across IOperation. // var statement points to VariableDeclarationSyntax Debug.Assert(node.Parent != null); varStatement = node.Parent; varDeclaration = node.Parent; break; } default: { Debug.Fail($"Unexpected syntax: {kind}"); // otherwise, they points to whatever bound nodes are pointing to. varStatement = varDeclaration = node; break; } } bool multiVariableImplicit = boundLocalDeclaration.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundLocalDeclaration, varDeclaration); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundLocalDeclaration, varDeclaration); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, varDeclaration, multiVariableImplicit); // In the case of a for loop, varStatement and varDeclaration will be the same syntax node. // We can only have one explicit operation, so make sure this node is implicit in that scenario. bool isImplicit = (varStatement == varDeclaration) || boundLocalDeclaration.WasCompilerGenerated; return new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, varStatement, isImplicit); } private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) { // The syntax for the boundMultipleLocalDeclarations can either be a LocalDeclarationStatement or a VariableDeclaration, depending on the context // (using/fixed statements vs variable declaration) // We generate a DeclarationGroup for these scenarios (using/fixed) to maintain tree shape consistency across IOperation. SyntaxNode declarationGroupSyntax = boundMultipleLocalDeclarations.Syntax; SyntaxNode declarationSyntax = declarationGroupSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)declarationGroupSyntax).Declaration : declarationGroupSyntax; bool declarationIsImplicit = boundMultipleLocalDeclarations.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundMultipleLocalDeclarations, declarationSyntax); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundMultipleLocalDeclarations, declarationSyntax); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, declarationSyntax, declarationIsImplicit); // If the syntax was the same, we're in a fixed statement or using statement. We make the Group operation implicit in this scenario, as the // syntax itself is a VariableDeclaration. We do this for using declarations as well, but since that doesn't have a separate parent bound // node, we need to check the current node for that explicitly. bool isImplicit = declarationGroupSyntax == declarationSyntax || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; var variableDeclaration = new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, declarationGroupSyntax, isImplicit); if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations usingDecl) { return new UsingDeclarationOperation( variableDeclaration, isAsynchronous: usingDecl.AwaitOpt is object, disposeInfo: usingDecl.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: usingDecl.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(usingDecl.PatternDisposeInfoOpt, usingDecl.Syntax)) : default, _semanticModel, declarationGroupSyntax, isImplicit: boundMultipleLocalDeclarations.WasCompilerGenerated); } return variableDeclaration; } private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) { ILabelSymbol label = boundLabelStatement.Label.GetPublicSymbol(); SyntaxNode syntax = boundLabelStatement.Syntax; bool isImplicit = boundLabelStatement.WasCompilerGenerated; return new LabeledOperation(label, operation: null, _semanticModel, syntax, isImplicit); } private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) { ILabelSymbol label = boundLabeledStatement.Label.GetPublicSymbol(); IOperation labeledStatement = Create(boundLabeledStatement.Body); SyntaxNode syntax = boundLabeledStatement.Syntax; bool isImplicit = boundLabeledStatement.WasCompilerGenerated; return new LabeledOperation(label, labeledStatement, _semanticModel, syntax, isImplicit); } private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) { // lambda body can point to expression directly and binder can insert expression statement there. and end up statement pointing to // expression syntax node since there is no statement syntax node to point to. this will mark such one as implicit since it doesn't // actually exist in code bool isImplicit = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; SyntaxNode syntax = boundExpressionStatement.Syntax; // If we're creating the tree for a speculatively-bound constructor initializer, there can be a bound sequence as the child node here // that corresponds to the lifetime of any declared variables. IOperation expression = Create(boundExpressionStatement.Expression); if (boundExpressionStatement.Expression is BoundSequence sequence) { Debug.Assert(boundExpressionStatement.Syntax == sequence.Value.Syntax); isImplicit = true; } return new ExpressionStatementOperation(expression, _semanticModel, syntax, isImplicit); } internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) { SyntaxNode syntax = boundTupleExpression.Syntax; bool isImplicit = boundTupleExpression.WasCompilerGenerated; ITypeSymbol? type = boundTupleExpression.GetPublicTypeSymbol(); if (syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { var tupleOperation = CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false); return new DeclarationExpressionOperation(tupleOperation, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } TypeSymbol? naturalType = boundTupleExpression switch { BoundTupleLiteral { Type: var t } => t, BoundConvertedTupleLiteral { SourceTuple: { Type: var t } } => t, BoundConvertedTupleLiteral => null, { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; ImmutableArray<IOperation> elements = CreateFromArray<BoundExpression, IOperation>(boundTupleExpression.Arguments); return new TupleOperation(elements, naturalType.GetPublicSymbol(), _semanticModel, syntax, type, isImplicit); } private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo = null) { Debug.Assert(positionInfo == null || boundInterpolatedString.InterpolationData == null); ImmutableArray<IInterpolatedStringContentOperation> parts = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, positionInfo ?? boundInterpolatedString.InterpolationData?.PositionInfo[0]); SyntaxNode syntax = boundInterpolatedString.Syntax; ITypeSymbol? type = boundInterpolatedString.GetPublicTypeSymbol(); ConstantValue? constantValue = boundInterpolatedString.ConstantValue; bool isImplicit = boundInterpolatedString.WasCompilerGenerated; return new InterpolatedStringOperation(parts, _semanticModel, syntax, type, constantValue, isImplicit); } internal ImmutableArray<IInterpolatedStringContentOperation> CreateBoundInterpolatedStringContentOperation(ImmutableArray<BoundExpression> parts, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo) { return positionInfo is { } info ? createHandlerInterpolatedStringContent(info) : createNonHandlerInterpolatedStringContent(); ImmutableArray<IInterpolatedStringContentOperation> createNonHandlerInterpolatedStringContent() { var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); foreach (var part in parts) { if (part.Kind == BoundKind.StringInsert) { builder.Add((IInterpolatedStringContentOperation)Create(part)); } else { builder.Add(CreateBoundInterpolatedStringTextOperation((BoundLiteral)part)); } } return builder.ToImmutableAndFree(); } ImmutableArray<IInterpolatedStringContentOperation> createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> positionInfo) { // For interpolated string handlers, we want to deconstruct the `AppendLiteral`/`AppendFormatted` calls into // their relevant components. // https://github.com/dotnet/roslyn/issues/54505 we need to handle interpolated strings used as handler conversions. Debug.Assert(parts.Length == positionInfo.Length); var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); for (int i = 0; i < parts.Length; i++) { var part = parts[i]; var currentPosition = positionInfo[i]; BoundExpression value; BoundExpression? alignment; BoundExpression? format; switch (part) { case BoundCall call: (value, alignment, format) = getCallInfo(call.Arguments, call.ArgumentNamesOpt, currentPosition); break; case BoundDynamicInvocation dynamicInvocation: (value, alignment, format) = getCallInfo(dynamicInvocation.Arguments, dynamicInvocation.ArgumentNamesOpt, currentPosition); break; case BoundBadExpression bad: Debug.Assert(bad.ChildBoundNodes.Length == 2 + // initial value + receiver is added to the end (currentPosition.HasAlignment ? 1 : 0) + (currentPosition.HasFormat ? 1 : 0)); value = bad.ChildBoundNodes[0]; if (currentPosition.IsLiteral) { alignment = format = null; } else { alignment = currentPosition.HasAlignment ? bad.ChildBoundNodes[1] : null; format = currentPosition.HasFormat ? bad.ChildBoundNodes[^2] : null; } break; default: throw ExceptionUtilities.UnexpectedValue(part.Kind); } // We are intentionally not checking the part for implicitness here. The part is a generated AppendLiteral or AppendFormatted call, // and will always be marked as CompilerGenerated. However, our existing behavior for non-builder interpolated strings does not mark // the BoundLiteral or BoundStringInsert components as compiler generated. This generates a non-implicit IInterpolatedStringTextOperation // with an implicit literal underneath, and a non-implicit IInterpolationOperation with non-implicit underlying components. bool isImplicit = false; if (currentPosition.IsLiteral) { Debug.Assert(alignment is null); Debug.Assert(format is null); IOperation valueOperation = value switch { BoundLiteral l => CreateBoundLiteralOperation(l, @implicit: true), BoundConversion { Operand: BoundLiteral } c => CreateBoundConversionOperation(c, forceOperandImplicitLiteral: true), _ => throw ExceptionUtilities.UnexpectedValue(value.Kind), }; Debug.Assert(valueOperation.IsImplicit); builder.Add(new InterpolatedStringTextOperation(valueOperation, _semanticModel, part.Syntax, isImplicit)); } else { IOperation valueOperation = Create(value); IOperation? alignmentOperation = Create(alignment); IOperation? formatOperation = Create(format); Debug.Assert(valueOperation.Syntax != part.Syntax); builder.Add(new InterpolationOperation(valueOperation, alignmentOperation, formatOperation, _semanticModel, part.Syntax, isImplicit)); } } return builder.ToImmutableAndFree(); static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) { BoundExpression value = arguments[0]; if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) { // There was no alignment/format component, as binding will qualify those parameters by name return (value, null, null); } else { var alignmentIndex = argumentNamesOpt.IndexOf("alignment"); BoundExpression? alignment = alignmentIndex == -1 ? null : arguments[alignmentIndex]; var formatIndex = argumentNamesOpt.IndexOf("format"); BoundExpression? format = formatIndex == -1 ? null : arguments[formatIndex]; return (value, alignment, format); } } } } private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) { IOperation expression = Create(boundStringInsert.Value); IOperation? alignment = Create(boundStringInsert.Alignment); IOperation? formatString = Create(boundStringInsert.Format); SyntaxNode syntax = boundStringInsert.Syntax; bool isImplicit = boundStringInsert.WasCompilerGenerated; return new InterpolationOperation(expression, alignment, formatString, _semanticModel, syntax, isImplicit); } private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) { IOperation text = CreateBoundLiteralOperation(boundNode, @implicit: true); SyntaxNode syntax = boundNode.Syntax; bool isImplicit = boundNode.WasCompilerGenerated; return new InterpolatedStringTextOperation(text, _semanticModel, syntax, isImplicit); } private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) { IOperation value = Create(boundConstantPattern.Value); SyntaxNode syntax = boundConstantPattern.Syntax; bool isImplicit = boundConstantPattern.WasCompilerGenerated; TypeSymbol inputType = boundConstantPattern.InputType; TypeSymbol narrowedType = boundConstantPattern.NarrowedType; return new ConstantPatternOperation(value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); IOperation value = Create(boundRelationalPattern.Value); SyntaxNode syntax = boundRelationalPattern.Syntax; bool isImplicit = boundRelationalPattern.WasCompilerGenerated; TypeSymbol inputType = boundRelationalPattern.InputType; TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; return new RelationalPatternOperation(operatorKind, value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) { ISymbol? variable = boundDeclarationPattern.Variable.GetPublicSymbol(); if (variable == null && boundDeclarationPattern.VariableAccess?.Kind == BoundKind.DiscardExpression) { variable = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); } ITypeSymbol inputType = boundDeclarationPattern.InputType.GetPublicSymbol(); ITypeSymbol narrowedType = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); bool acceptsNull = boundDeclarationPattern.IsVar; ITypeSymbol? matchedType = acceptsNull ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol(); SyntaxNode syntax = boundDeclarationPattern.Syntax; bool isImplicit = boundDeclarationPattern.WasCompilerGenerated; return new DeclarationPatternOperation(matchedType, acceptsNull, variable, inputType, narrowedType, _semanticModel, syntax, isImplicit); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) { ITypeSymbol matchedType = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundRecursivePattern.Deconstruction is { IsDefault: false } deconstructions ? deconstructions.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; ImmutableArray<IPropertySubpatternOperation> propertySubpatterns = boundRecursivePattern.Properties is { IsDefault: false } properties ? properties.SelectAsArray((p, arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType), (Fac: this, MatchedType: matchedType)) : ImmutableArray<IPropertySubpatternOperation>.Empty; return new RecursivePatternOperation( matchedType, boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, isImplicit: boundRecursivePattern.WasCompilerGenerated); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) { ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundITuplePattern.Subpatterns is { IsDefault: false } subpatterns ? subpatterns.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; return new RecursivePatternOperation( boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns: ImmutableArray<IPropertySubpatternOperation>.Empty, declaredSymbol: null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, isImplicit: boundITuplePattern.WasCompilerGenerated); } private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) { return new TypePatternOperation( matchedType: boundTypePattern.NarrowedType.GetPublicSymbol(), inputType: boundTypePattern.InputType.GetPublicSymbol(), narrowedType: boundTypePattern.NarrowedType.GetPublicSymbol(), semanticModel: _semanticModel, syntax: boundTypePattern.Syntax, isImplicit: boundTypePattern.WasCompilerGenerated); } private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) { return new NegatedPatternOperation( (IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, isImplicit: boundNegatedPattern.WasCompilerGenerated); } private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) { return new BinaryPatternOperation( boundBinaryPattern.Disjunction ? BinaryOperatorKind.Or : BinaryOperatorKind.And, (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, isImplicit: boundBinaryPattern.WasCompilerGenerated); } private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) { IOperation value = Create(boundSwitchStatement.Expression); ImmutableArray<ISwitchCaseOperation> cases = CreateFromArray<BoundSwitchSection, ISwitchCaseOperation>(boundSwitchStatement.SwitchSections); ImmutableArray<ILocalSymbol> locals = boundSwitchStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol exitLabel = boundSwitchStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundSwitchStatement.Syntax; bool isImplicit = boundSwitchStatement.WasCompilerGenerated; return new SwitchOperation(locals, value, cases, exitLabel, _semanticModel, syntax, isImplicit); } private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) { ImmutableArray<ICaseClauseOperation> clauses = CreateFromArray<BoundSwitchLabel, ICaseClauseOperation>(boundSwitchSection.SwitchLabels); ImmutableArray<IOperation> body = CreateFromArray<BoundStatement, IOperation>(boundSwitchSection.Statements); ImmutableArray<ILocalSymbol> locals = boundSwitchSection.Locals.GetPublicSymbols(); return new SwitchCaseOperation(clauses, body, locals, condition: null, _semanticModel, boundSwitchSection.Syntax, isImplicit: boundSwitchSection.WasCompilerGenerated); } private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) { IOperation value = Create(boundSwitchExpression.Expression); ImmutableArray<ISwitchExpressionArmOperation> arms = CreateFromArray<BoundSwitchExpressionArm, ISwitchExpressionArmOperation>(boundSwitchExpression.SwitchArms); bool isExhaustive; if (boundSwitchExpression.DefaultLabel != null) { Debug.Assert(boundSwitchExpression.DefaultLabel is GeneratedLabelSymbol); isExhaustive = false; } else { isExhaustive = true; } return new SwitchExpressionOperation( value, arms, isExhaustive, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); } private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); IOperation? guard = Create(boundSwitchExpressionArm.WhenClause); IOperation value = Create(boundSwitchExpressionArm.Value); return new SwitchExpressionArmOperation( pattern, guard, value, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); } private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) { SyntaxNode syntax = boundSwitchLabel.Syntax; bool isImplicit = boundSwitchLabel.WasCompilerGenerated; LabelSymbol label = boundSwitchLabel.Label; if (boundSwitchLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel) { Debug.Assert(boundSwitchLabel.Pattern.Kind == BoundKind.DiscardPattern); return new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern cp && cp.InputType.IsValidV6SwitchGoverningType()) { return new SingleValueCaseClauseOperation(Create(cp.Value), label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchLabel.Pattern); IOperation? guard = Create(boundSwitchLabel.WhenClause); return new PatternCaseClauseOperation(label.GetPublicSymbol(), pattern, guard, _semanticModel, syntax, isImplicit); } } private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) { IOperation value = Create(boundIsPatternExpression.Expression); IPatternOperation pattern = (IPatternOperation)Create(boundIsPatternExpression.Pattern); SyntaxNode syntax = boundIsPatternExpression.Syntax; ITypeSymbol? type = boundIsPatternExpression.GetPublicTypeSymbol(); bool isImplicit = boundIsPatternExpression.WasCompilerGenerated; return new IsPatternOperation(value, pattern, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) { if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) { // Currently we have no IOperation APIs for different query clauses or continuation. return Create(boundQueryClause.Value); } IOperation operation = Create(boundQueryClause.Value); SyntaxNode syntax = boundQueryClause.Syntax; ITypeSymbol? type = boundQueryClause.GetPublicTypeSymbol(); bool isImplicit = boundQueryClause.WasCompilerGenerated; return new TranslatedQueryOperation(operation, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) { // We do not have operation nodes for the bound range variables, just it's value. return Create(boundRangeVariable.Value); } private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) { return new DiscardOperation( ((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), isImplicit: boundNode.WasCompilerGenerated); } private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) { return new UnaryOperation( UnaryOperatorKind.Hat, Create(boundIndex.Operand), isLifted: boundIndex.Type.IsNullableType(), isChecked: false, operatorMethod: null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), constantValue: null, isImplicit: boundIndex.WasCompilerGenerated); } private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) { IOperation? left = Create(boundRange.LeftOperandOpt); IOperation? right = Create(boundRange.RightOperandOpt); return new RangeOperation( left, right, isLifted: boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), isImplicit: boundRange.WasCompilerGenerated); } private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) { return new DiscardPatternOperation( inputType: boundNode.InputType.GetPublicSymbol(), narrowedType: boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) { // We treat `c is { ... .Prop: <pattern> }` as `c is { ...: { Prop: <pattern> } }` SyntaxNode subpatternSyntax = subpattern.Syntax; BoundPropertySubpatternMember? member = subpattern.Member; IPatternOperation pattern = (IPatternOperation)Create(subpattern.Pattern); if (member is null) { var reference = OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray<IOperation>.Empty, isImplicit: true); return new PropertySubpatternOperation(reference, pattern, _semanticModel, subpatternSyntax, isImplicit: false); } // Create an operation for last property access: // `{ SingleProp: <pattern operation> }` // or // `.LastProp: <pattern operation>` portion (treated as `{ LastProp: <pattern operation> }`) var nameSyntax = member.Syntax; var inputType = getInputType(member, matchedType); IPropertySubpatternOperation? result = createPropertySubpattern(member.Symbol, pattern, inputType, nameSyntax, isSingle: member.Receiver is null); while (member.Receiver is not null) { member = member.Receiver; nameSyntax = member.Syntax; ITypeSymbol previousType = inputType; inputType = getInputType(member, matchedType); // Create an operation for a preceding property access: // { PrecedingProp: <previous pattern operation> } IPatternOperation nestedPattern = new RecursivePatternOperation( matchedType: previousType, deconstructSymbol: null, deconstructionSubpatterns: ImmutableArray<IPatternOperation>.Empty, propertySubpatterns: ImmutableArray.Create(result), declaredSymbol: null, previousType, narrowedType: previousType, semanticModel: _semanticModel, nameSyntax, isImplicit: true); result = createPropertySubpattern(member.Symbol, nestedPattern, inputType, nameSyntax, isSingle: false); } return result; IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation pattern, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) { Debug.Assert(nameSyntax is not null); IOperation reference; switch (symbol) { case FieldSymbol field: { var constantValue = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); reference = new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration: false, createReceiver(), _semanticModel, nameSyntax, type: field.Type.GetPublicSymbol(), constantValue, isImplicit: false); break; } case PropertySymbol property: { reference = new PropertyReferenceOperation(property.GetPublicSymbol(), ImmutableArray<IArgumentOperation>.Empty, createReceiver(), _semanticModel, nameSyntax, type: property.Type.GetPublicSymbol(), isImplicit: false); break; } default: { // We should expose the symbol in this case somehow: // https://github.com/dotnet/roslyn/issues/33175 reference = OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray<IOperation>.Empty, isImplicit: false); break; } } var syntaxForPropertySubpattern = isSingle ? subpatternSyntax : nameSyntax; return new PropertySubpatternOperation(reference, pattern, _semanticModel, syntaxForPropertySubpattern, isImplicit: !isSingle); IOperation? createReceiver() => symbol?.IsStatic == false ? new InstanceReferenceOperation(InstanceReferenceKind.PatternInput, _semanticModel, nameSyntax!, receiverType, isImplicit: true) : null; } static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol matchedType) => member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? matchedType; } private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = placeholder.Syntax; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); bool isImplicit = placeholder.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private ImmutableArray<IArgumentOperation> CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) { // can't be an extension method for dispose Debug.Assert(!patternDisposeInfo.Method.IsStatic); if (patternDisposeInfo.Method.ParameterCount == 0) { return ImmutableArray<IArgumentOperation>.Empty; } Debug.Assert(!patternDisposeInfo.Expanded || patternDisposeInfo.Method.GetParameters().Last().OriginalDefinition.Type.IsSZArray()); var args = DeriveArguments( patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax, invokedAsExtensionMethod: false); return Operation.SetParentOperation(args, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { internal sealed partial class CSharpOperationFactory { private readonly SemanticModel _semanticModel; public CSharpOperationFactory(SemanticModel semanticModel) { _semanticModel = semanticModel; } [return: NotNullIfNotNull("boundNode")] public IOperation? Create(BoundNode? boundNode) { if (boundNode == null) { return null; } switch (boundNode.Kind) { case BoundKind.DeconstructValuePlaceholder: return CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); case BoundKind.DeconstructionAssignmentOperator: return CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); case BoundKind.Call: return CreateBoundCallOperation((BoundCall)boundNode); case BoundKind.Local: return CreateBoundLocalOperation((BoundLocal)boundNode); case BoundKind.FieldAccess: return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); case BoundKind.PropertyAccess: return CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); case BoundKind.IndexerAccess: return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); case BoundKind.EventAccess: return CreateBoundEventAccessOperation((BoundEventAccess)boundNode); case BoundKind.EventAssignmentOperator: return CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); case BoundKind.Parameter: return CreateBoundParameterOperation((BoundParameter)boundNode); case BoundKind.Literal: return CreateBoundLiteralOperation((BoundLiteral)boundNode); case BoundKind.DynamicInvocation: return CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); case BoundKind.DynamicIndexerAccess: return CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); case BoundKind.ObjectCreationExpression: return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); case BoundKind.WithExpression: return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); case BoundKind.DynamicObjectCreationExpression: return CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); case BoundKind.ObjectInitializerExpression: return CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); case BoundKind.CollectionInitializerExpression: return CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); case BoundKind.ObjectInitializerMember: return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); case BoundKind.CollectionElementInitializer: return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); case BoundKind.DynamicObjectInitializerMember: return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); case BoundKind.DynamicMemberAccess: return CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); case BoundKind.DynamicCollectionElementInitializer: return CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); case BoundKind.UnboundLambda: return CreateUnboundLambdaOperation((UnboundLambda)boundNode); case BoundKind.Lambda: return CreateBoundLambdaOperation((BoundLambda)boundNode); case BoundKind.Conversion: return CreateBoundConversionOperation((BoundConversion)boundNode); case BoundKind.AsOperator: return CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); case BoundKind.IsOperator: return CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); case BoundKind.SizeOfOperator: return CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); case BoundKind.TypeOfOperator: return CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); case BoundKind.ArrayCreation: return CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); case BoundKind.ArrayInitialization: return CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); case BoundKind.DefaultLiteral: return CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); case BoundKind.DefaultExpression: return CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); case BoundKind.BaseReference: return CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); case BoundKind.ThisReference: return CreateBoundThisReferenceOperation((BoundThisReference)boundNode); case BoundKind.AssignmentOperator: return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); case BoundKind.CompoundAssignmentOperator: return CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); case BoundKind.IncrementOperator: return CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); case BoundKind.BadExpression: return CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); case BoundKind.NewT: return CreateBoundNewTOperation((BoundNewT)boundNode); case BoundKind.NoPiaObjectCreationExpression: return CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); case BoundKind.UnaryOperator: return CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); case BoundKind.BinaryOperator: case BoundKind.UserDefinedConditionalLogicalOperator: return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); case BoundKind.TupleBinaryOperator: return CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); case BoundKind.ConditionalOperator: return CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); case BoundKind.NullCoalescingOperator: return CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); case BoundKind.AwaitExpression: return CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); case BoundKind.ArrayAccess: return CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); case BoundKind.NameOfOperator: return CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); case BoundKind.ThrowExpression: return CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); case BoundKind.AddressOfOperator: return CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); case BoundKind.ImplicitReceiver: return CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); case BoundKind.ConditionalAccess: return CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); case BoundKind.ConditionalReceiver: return CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); case BoundKind.FieldEqualsValue: return CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); case BoundKind.PropertyEqualsValue: return CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); case BoundKind.ParameterEqualsValue: return CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); case BoundKind.Block: return CreateBoundBlockOperation((BoundBlock)boundNode); case BoundKind.ContinueStatement: return CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); case BoundKind.BreakStatement: return CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); case BoundKind.YieldBreakStatement: return CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); case BoundKind.GotoStatement: return CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); case BoundKind.NoOpStatement: return CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); case BoundKind.IfStatement: return CreateBoundIfStatementOperation((BoundIfStatement)boundNode); case BoundKind.WhileStatement: return CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); case BoundKind.DoStatement: return CreateBoundDoStatementOperation((BoundDoStatement)boundNode); case BoundKind.ForStatement: return CreateBoundForStatementOperation((BoundForStatement)boundNode); case BoundKind.ForEachStatement: return CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); case BoundKind.TryStatement: return CreateBoundTryStatementOperation((BoundTryStatement)boundNode); case BoundKind.CatchBlock: return CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); case BoundKind.FixedStatement: return CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); case BoundKind.UsingStatement: return CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); case BoundKind.ThrowStatement: return CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); case BoundKind.ReturnStatement: return CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); case BoundKind.YieldReturnStatement: return CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); case BoundKind.LockStatement: return CreateBoundLockStatementOperation((BoundLockStatement)boundNode); case BoundKind.BadStatement: return CreateBoundBadStatementOperation((BoundBadStatement)boundNode); case BoundKind.LocalDeclaration: return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); case BoundKind.LabelStatement: return CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); case BoundKind.LabeledStatement: return CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); case BoundKind.ExpressionStatement: return CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return CreateBoundTupleOperation((BoundTupleExpression)boundNode); case BoundKind.UnconvertedInterpolatedString: throw ExceptionUtilities.Unreachable; case BoundKind.InterpolatedString: return CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); case BoundKind.StringInsert: return CreateBoundInterpolationOperation((BoundStringInsert)boundNode); case BoundKind.LocalFunctionStatement: return CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); case BoundKind.AnonymousObjectCreationExpression: return CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); case BoundKind.AnonymousPropertyDeclaration: throw ExceptionUtilities.Unreachable; case BoundKind.ConstantPattern: return CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); case BoundKind.DeclarationPattern: return CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); case BoundKind.RecursivePattern: return CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); case BoundKind.ITuplePattern: return CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); case BoundKind.DiscardPattern: return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); case BoundKind.BinaryPattern: return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); case BoundKind.NegatedPattern: return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); case BoundKind.RelationalPattern: return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); case BoundKind.TypePattern: return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); case BoundKind.SwitchStatement: return CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); case BoundKind.SwitchLabel: return CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); case BoundKind.IsPatternExpression: return CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); case BoundKind.QueryClause: return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); case BoundKind.DelegateCreationExpression: return CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); case BoundKind.RangeVariable: return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); case BoundKind.ConstructorMethodBody: return CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); case BoundKind.NonConstructorMethodBody: return CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); case BoundKind.DiscardExpression: return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); case BoundKind.NullCoalescingAssignmentOperator: return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); case BoundKind.FromEndIndexExpression: return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); case BoundKind.RangeExpression: return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); case BoundKind.SwitchSection: return CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); case BoundKind.UnconvertedConditionalOperator: throw ExceptionUtilities.Unreachable; case BoundKind.UnconvertedSwitchExpression: throw ExceptionUtilities.Unreachable; case BoundKind.ConvertedSwitchExpression: return CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); case BoundKind.SwitchExpressionArm: return CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); case BoundKind.ObjectOrCollectionValuePlaceholder: return CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); case BoundKind.FunctionPointerInvocation: return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); case BoundKind.UnconvertedAddressOfOperator: return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); case BoundKind.InterpolatedStringArgumentPlaceholder: return CreateBoundInterpolatedStringArgumentPlaceholder((BoundInterpolatedStringArgumentPlaceholder)boundNode); case BoundKind.InterpolatedStringHandlerPlaceholder: return CreateBoundInterpolatedStringHandlerPlaceholder((BoundInterpolatedStringHandlerPlaceholder)boundNode); case BoundKind.Attribute: case BoundKind.ArgList: case BoundKind.ArgListOperator: case BoundKind.ConvertedStackAllocExpression: case BoundKind.FixedLocalCollectionInitializer: case BoundKind.GlobalStatementInitializer: case BoundKind.HostObjectMemberReference: case BoundKind.MakeRefOperator: case BoundKind.MethodGroup: case BoundKind.NamespaceExpression: case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PreviousSubmissionReference: case BoundKind.RefTypeOperator: case BoundKind.RefValueOperator: case BoundKind.Sequence: case BoundKind.StackAllocArrayCreation: case BoundKind.TypeExpression: case BoundKind.TypeOrValueExpression: case BoundKind.IndexOrRangePatternIndexerAccess: ConstantValue? constantValue = (boundNode as BoundExpression)?.ConstantValue; bool isImplicit = boundNode.WasCompilerGenerated; if (!isImplicit) { switch (boundNode.Kind) { case BoundKind.FixedLocalCollectionInitializer: isImplicit = true; break; } } ImmutableArray<IOperation> children = GetIOperationChildren(boundNode); return new NoneOperation(children, _semanticModel, boundNode.Syntax, type: null, constantValue, isImplicit: isImplicit); default: // If you're hitting this because the IOperation test hook has failed, see // <roslyn-root>/docs/Compilers/IOperation Test Hook.md for instructions on how to fix. throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } public ImmutableArray<TOperation> CreateFromArray<TBoundNode, TOperation>(ImmutableArray<TBoundNode> boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation { if (boundNodes.IsDefault) { return ImmutableArray<TOperation>.Empty; } var builder = ArrayBuilder<TOperation>.GetInstance(boundNodes.Length); foreach (var node in boundNodes) { builder.AddIfNotNull((TOperation)Create(node)); } return builder.ToImmutableAndFree(); } private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) { return new MethodBodyOperation( (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) { return new ConstructorBodyOperation( boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal ImmutableArray<IOperation> GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) { var children = boundNodeWithChildren.Children; if (children.IsDefaultOrEmpty) { return ImmutableArray<IOperation>.Empty; } var builder = ArrayBuilder<IOperation>.GetInstance(children.Length); foreach (BoundNode? childNode in children) { if (childNode == null) { continue; } IOperation operation = Create(childNode); builder.Add(operation); } return builder.ToImmutableAndFree(); } internal ImmutableArray<IVariableDeclaratorOperation> CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (declarationSyntax as VariableDeclarationSyntax)?.Variables[0] ?? declarationSyntax)); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var multipleDeclaration = (BoundMultipleLocalDeclarationsBase)declaration; var builder = ArrayBuilder<IVariableDeclaratorOperation>.GetInstance(multipleDeclaration.LocalDeclarations.Length); foreach (var decl in multipleDeclaration.LocalDeclarations) { builder.Add((IVariableDeclaratorOperation)CreateVariableDeclaratorInternal(decl, decl.Syntax)); } return builder.ToImmutableAndFree(); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) { SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; ITypeSymbol? type = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructValuePlaceholder.WasCompilerGenerated; return new PlaceholderOperation(PlaceholderKind.Unspecified, _semanticModel, syntax, type, isImplicit); } private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) { IOperation target = Create(boundDeconstructionAssignmentOperator.Left); // Skip the synthetic deconstruction conversion wrapping the right operand. This is a compiler-generated conversion that we don't want to reflect // in the public API because it's an implementation detail. IOperation value = Create(boundDeconstructionAssignmentOperator.Right.Operand); SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; ITypeSymbol? type = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructionAssignmentOperator.WasCompilerGenerated; return new DeconstructionAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCallOperation(BoundCall boundCall) { MethodSymbol targetMethod = boundCall.Method; SyntaxNode syntax = boundCall.Syntax; ITypeSymbol? type = boundCall.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCall.ConstantValue; bool isImplicit = boundCall.WasCompilerGenerated; if (!boundCall.OriginalMethodsOpt.IsDefault || IsMethodInvalid(boundCall.ResultKind, targetMethod)) { ImmutableArray<IOperation> children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCall).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(targetMethod, boundCall.ReceiverOpt); IOperation? receiver = CreateReceiverOperation(boundCall.ReceiverOpt, targetMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCall); return new InvocationOperation(targetMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) { ITypeSymbol? type = boundFunctionPointerInvocation.GetPublicTypeSymbol(); SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; bool isImplicit = boundFunctionPointerInvocation.WasCompilerGenerated; ImmutableArray<IOperation> children; if (boundFunctionPointerInvocation.ResultKind != LookupResultKind.Viable) { children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } children = GetIOperationChildren(boundFunctionPointerInvocation); return new NoneOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) { return new AddressOfOperation( Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); } internal ImmutableArray<IOperation> CreateIgnoredDimensions(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { BoundTypeExpression? declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); return CreateFromArray<BoundExpression, IOperation>(declaredTypeOpt.BoundDimensionsOpt); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var declarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; ImmutableArray<BoundExpression> dimensions; if (declarations.Length > 0) { BoundTypeExpression? declaredTypeOpt = declarations[0].DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); dimensions = declaredTypeOpt.BoundDimensionsOpt; } else { dimensions = ImmutableArray<BoundExpression>.Empty; } return CreateFromArray<BoundExpression, IOperation>(dimensions); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) { ILocalSymbol local = boundLocal.LocalSymbol.GetPublicSymbol(); bool isDeclaration = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; SyntaxNode syntax = boundLocal.Syntax; ITypeSymbol? type = boundLocal.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLocal.ConstantValue; bool isImplicit = boundLocal.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation localReference = CreateBoundLocalOperation(boundLocal, createDeclaration: false); return new DeclarationExpressionOperation(localReference, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } return new LocalReferenceOperation(local, isDeclaration, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) { IFieldSymbol field = boundFieldAccess.FieldSymbol.GetPublicSymbol(); bool isDeclaration = boundFieldAccess.IsDeclaration; SyntaxNode syntax = boundFieldAccess.Syntax; ITypeSymbol? type = boundFieldAccess.GetPublicTypeSymbol(); ConstantValue? constantValue = boundFieldAccess.ConstantValue; bool isImplicit = boundFieldAccess.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation fieldAccess = CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false); return new DeclarationExpressionOperation(fieldAccess, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } IOperation? instance = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); return new FieldReferenceOperation(field, isDeclaration, instance, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) { switch (boundNode) { case BoundPropertyAccess boundPropertyAccess: return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); case BoundObjectInitializerMember boundObjectInitializerMember: return boundObjectInitializerMember.MemberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); case BoundIndexerAccess boundIndexerAccess: return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); default: throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) { IOperation? instance = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); var arguments = ImmutableArray<IArgumentOperation>.Empty; IPropertySymbol property = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); SyntaxNode syntax = boundPropertyAccess.Syntax; ITypeSymbol? type = boundPropertyAccess.GetPublicTypeSymbol(); bool isImplicit = boundPropertyAccess.WasCompilerGenerated; return new PropertyReferenceOperation(property, arguments, instance, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) { PropertySymbol property = boundIndexerAccess.Indexer; SyntaxNode syntax = boundIndexerAccess.Syntax; ITypeSymbol? type = boundIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundIndexerAccess.WasCompilerGenerated; if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundIndexerAccess, isObjectOrCollectionInitializer: false); IOperation? instance = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, instance, _semanticModel, syntax, type, isImplicit); } private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) { IEventSymbol @event = boundEventAccess.EventSymbol.GetPublicSymbol(); IOperation? instance = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); SyntaxNode syntax = boundEventAccess.Syntax; ITypeSymbol? type = boundEventAccess.GetPublicTypeSymbol(); bool isImplicit = boundEventAccess.WasCompilerGenerated; return new EventReferenceOperation(@event, instance, _semanticModel, syntax, type, isImplicit); } private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) { IOperation eventReference = CreateBoundEventAccessOperation(boundEventAssignmentOperator); IOperation handlerValue = Create(boundEventAssignmentOperator.Argument); SyntaxNode syntax = boundEventAssignmentOperator.Syntax; bool adds = boundEventAssignmentOperator.IsAddition; ITypeSymbol? type = boundEventAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundEventAssignmentOperator.WasCompilerGenerated; return new EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, syntax, type, isImplicit); } private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) { IParameterSymbol parameter = boundParameter.ParameterSymbol.GetPublicSymbol(); SyntaxNode syntax = boundParameter.Syntax; ITypeSymbol? type = boundParameter.GetPublicTypeSymbol(); bool isImplicit = boundParameter.WasCompilerGenerated; return new ParameterReferenceOperation(parameter, _semanticModel, syntax, type, isImplicit); } internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) { SyntaxNode syntax = boundLiteral.Syntax; ITypeSymbol? type = boundLiteral.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLiteral.ConstantValue; bool isImplicit = boundLiteral.WasCompilerGenerated || @implicit; return new LiteralOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) { SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; ITypeSymbol? type = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); Debug.Assert(type is not null); bool isImplicit = boundAnonymousObjectCreationExpression.WasCompilerGenerated; ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) { MethodSymbol constructor = boundObjectCreationExpression.Constructor; SyntaxNode syntax = boundObjectCreationExpression.Syntax; ITypeSymbol? type = boundObjectCreationExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundObjectCreationExpression.ConstantValue; bool isImplicit = boundObjectCreationExpression.WasCompilerGenerated; if (boundObjectCreationExpression.ResultKind == LookupResultKind.OverloadResolutionFailure || constructor == null || constructor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } else if (boundObjectCreationExpression.Type.IsAnonymousType) { // Workaround for https://github.com/dotnet/roslyn/issues/28157 Debug.Assert(isImplicit); Debug.Assert(type is not null); ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers( boundObjectCreationExpression.Arguments, declarations: ImmutableArray<BoundAnonymousPropertyDeclaration>.Empty, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundObjectCreationExpression); IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundObjectCreationExpression.InitializerExpressionOpt); return new ObjectCreationOperation(constructor.GetPublicSymbol(), initializer, arguments, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) { IOperation operand = Create(boundWithExpression.Receiver); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); MethodSymbol? constructor = boundWithExpression.CloneMethod; SyntaxNode syntax = boundWithExpression.Syntax; ITypeSymbol? type = boundWithExpression.GetPublicTypeSymbol(); bool isImplicit = boundWithExpression.WasCompilerGenerated; return new WithOperation(operand, constructor.GetPublicSymbol(), initializer, _semanticModel, syntax, type, isImplicit); } private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicObjectCreationExpression.Arguments); ImmutableArray<string> argumentNames = boundDynamicObjectCreationExpression.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicObjectCreationExpression.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; ITypeSymbol? type = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectCreationExpression.WasCompilerGenerated; return new DynamicObjectCreationOperation(initializer, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) { switch (receiver) { case BoundObjectOrCollectionValuePlaceholder implicitReceiver: return CreateBoundDynamicMemberAccessOperation(implicitReceiver, typeArgumentsOpt: ImmutableArray<TypeSymbol>.Empty, memberName: "Add", implicitReceiver.Syntax, type: null, isImplicit: true); case BoundMethodGroup methodGroup: return CreateBoundDynamicMemberAccessOperation(methodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(methodGroup.TypeArgumentsOpt), methodGroup.Name, methodGroup.Syntax, methodGroup.GetPublicTypeSymbol(), methodGroup.WasCompilerGenerated); default: return Create(receiver); } } private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicInvocation.Arguments); ImmutableArray<string> argumentNames = boundDynamicInvocation.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicInvocation.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicInvocation.Syntax; ITypeSymbol? type = boundDynamicInvocation.GetPublicTypeSymbol(); bool isImplicit = boundDynamicInvocation.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicIndexerAccess: return Create(boundDynamicIndexerAccess.Receiver); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } internal ImmutableArray<IOperation> CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicAccess: return CreateFromArray<BoundExpression, IOperation>(boundDynamicAccess.Arguments); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateFromArray<BoundExpression, IOperation>(boundObjectInitializerMember.Arguments); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) { IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); ImmutableArray<string> argumentNames = boundDynamicIndexerAccess.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicIndexerAccess.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; ITypeSymbol? type = boundDynamicIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundDynamicIndexerAccess.WasCompilerGenerated; return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); SyntaxNode syntax = boundObjectInitializerExpression.Syntax; ITypeSymbol? type = boundObjectInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; ITypeSymbol? type = boundCollectionInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundCollectionInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) { Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; SyntaxNode syntax = boundObjectInitializerMember.Syntax; ITypeSymbol? type = boundObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerMember.WasCompilerGenerated; if ((object?)memberSymbol == null) { Debug.Assert(boundObjectInitializerMember.Type.IsDynamic()); IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); ImmutableArray<string> argumentNames = boundObjectInitializerMember.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundObjectInitializerMember.ArgumentRefKindsOpt.NullToEmpty(); return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } switch (memberSymbol.Kind) { case SymbolKind.Field: var field = (FieldSymbol)memberSymbol; bool isDeclaration = false; return new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration, createReceiver(), _semanticModel, syntax, type, constantValue: null, isImplicit); case SymbolKind.Event: var eventSymbol = (EventSymbol)memberSymbol; return new EventReferenceOperation(eventSymbol.GetPublicSymbol(), createReceiver(), _semanticModel, syntax, type, isImplicit); case SymbolKind.Property: var property = (PropertySymbol)memberSymbol; ImmutableArray<IArgumentOperation> arguments; if (!boundObjectInitializerMember.Arguments.IsEmpty) { // In nested member initializers, the property is not actually set. Instead, it is retrieved for a series of Add method calls or nested property setter calls, // so we need to use the getter for this property MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); if (accessor == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } arguments = DeriveArguments(boundObjectInitializerMember, isObjectOrCollectionInitializer); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, createReceiver(), _semanticModel, syntax, type, isImplicit); default: throw ExceptionUtilities.Unreachable; } IOperation? createReceiver() => memberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); } private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) { IOperation instanceReceiver = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); string memberName = boundDynamicObjectInitializerMember.MemberName; ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; ITypeSymbol containingType = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; ITypeSymbol? type = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectInitializerMember.WasCompilerGenerated; return new DynamicMemberReferenceOperation(instanceReceiver, memberName, typeArguments, containingType, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) { MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; IOperation? receiver = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCollectionElementInitializer); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCollectionElementInitializer.ConstantValue; bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; if (IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); return new InvocationOperation(addMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) { return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation( BoundExpression? receiver, ImmutableArray<TypeSymbol> typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) { ITypeSymbol? containingType = null; if (receiver?.Kind == BoundKind.TypeExpression) { containingType = receiver.GetPublicTypeSymbol(); receiver = null; } ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; if (!typeArgumentsOpt.IsDefault) { typeArguments = typeArgumentsOpt.GetPublicSymbols(); } IOperation? instance = Create(receiver); return new DynamicMemberReferenceOperation(instance, memberName, typeArguments, containingType, _semanticModel, syntaxNode, type, isImplicit); } private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundCollectionElementInitializer.Arguments); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames: ImmutableArray<string>.Empty, argumentRefKinds: ImmutableArray<RefKind>.Empty, _semanticModel, syntax, type, isImplicit); } private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) { // We want to ensure that we never see the UnboundLambda node, and that we don't end up having two different IOperation // nodes for the lambda expression. So, we ask the semantic model for the IOperation node for the unbound lambda syntax. // We are counting on the fact that will do the error recovery and actually create the BoundLambda node appropriate for // this syntax node. BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); return Create(boundLambda); } private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) { IMethodSymbol symbol = boundLambda.Symbol.GetPublicSymbol(); IBlockOperation body = (IBlockOperation)Create(boundLambda.Body); SyntaxNode syntax = boundLambda.Syntax; bool isImplicit = boundLambda.WasCompilerGenerated; return new AnonymousFunctionOperation(symbol, body, _semanticModel, syntax, isImplicit); } private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) { IBlockOperation? body = (IBlockOperation?)Create(boundLocalFunctionStatement.Body); IBlockOperation? ignoredBody = boundLocalFunctionStatement is { BlockBody: { }, ExpressionBody: { } exprBody } ? (IBlockOperation?)Create(exprBody) : null; IMethodSymbol symbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); SyntaxNode syntax = boundLocalFunctionStatement.Syntax; bool isImplicit = boundLocalFunctionStatement.WasCompilerGenerated; return new LocalFunctionOperation(symbol, body, ignoredBody, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) { Debug.Assert(!forceOperandImplicitLiteral || boundConversion.Operand is BoundLiteral); bool isImplicit = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; BoundExpression boundOperand = boundConversion.Operand; if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { // https://github.com/dotnet/roslyn/issues/54505 Support interpolation handlers in conversions Debug.Assert(!forceOperandImplicitLiteral); Debug.Assert(boundOperand is BoundInterpolatedString { InterpolationData: not null } or BoundBinaryOperator { InterpolatedStringHandlerData: not null }); return CreateInterpolatedStringHandler(boundConversion); } if (boundConversion.ConversionKind == CSharp.ConversionKind.MethodGroup) { SyntaxNode syntax = boundConversion.Syntax; ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); Debug.Assert(!forceOperandImplicitLiteral); if (boundConversion.Type is FunctionPointerTypeSymbol) { Debug.Assert(boundConversion.SymbolOpt is object); return new AddressOfOperation( CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, type, boundConversion.WasCompilerGenerated); } // We don't check HasErrors on the conversion here because if we actually have a MethodGroup conversion, // overload resolution succeeded. The resulting method could be invalid for other reasons, but we don't // hide the resolved method. IOperation target = CreateDelegateTargetOperation(boundConversion); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { SyntaxNode syntax = boundConversion.Syntax; if (syntax.IsMissing) { // If the underlying syntax IsMissing, then that means we're in case where the compiler generated a piece of syntax to fill in for // an error, such as this case: // // int i = ; // // Semantic model has a special case here that we match: if the underlying syntax is missing, don't create a conversion expression, // and instead directly return the operand, which will be a BoundBadExpression. When we generate a node for the BoundBadExpression, // the resulting IOperation will also have a null Type. Debug.Assert(boundOperand.Kind == BoundKind.BadExpression || ((boundOperand as BoundLambda)?.Body.Statements.SingleOrDefault() as BoundReturnStatement)?. ExpressionOpt?.Kind == BoundKind.BadExpression); Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } BoundConversion correctedConversionNode = boundConversion; Conversion conversion = boundConversion.Conversion; if (boundOperand.Syntax == boundConversion.Syntax) { if (boundOperand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(boundOperand.Type, boundConversion.Type, TypeCompareKind.ConsiderEverything2)) { // Erase this conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } else { // Make this conversion implicit isImplicit = true; } } if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && boundOperand.Kind == BoundKind.Conversion) { var nestedConversion = (BoundConversion)boundOperand; BoundExpression nestedOperand = nestedConversion.Operand; if (nestedConversion.Syntax == nestedOperand.Syntax && nestedConversion.ExplicitCastInCode && nestedOperand.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything2)) { // Let's erase the nested conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion. // We need to use conversion information from the nested conversion because that is where the real conversion // information is stored. conversion = nestedConversion.Conversion; correctedConversionNode = nestedConversion; } } ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConversion.ConstantValue; // If this is a lambda or method group conversion to a delegate type, we return a delegate creation instead of a conversion if ((boundOperand.Kind == BoundKind.Lambda || boundOperand.Kind == BoundKind.UnboundLambda || boundOperand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) { IOperation target = CreateDelegateTargetOperation(correctedConversionNode); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { bool isTryCast = false; // Checked conversions only matter if the conversion is a Numeric conversion. Don't have true unless the conversion is actually numeric. bool isChecked = conversion.IsNumeric && boundConversion.Checked; IOperation operand = forceOperandImplicitLiteral ? CreateBoundLiteralOperation((BoundLiteral)correctedConversionNode.Operand, @implicit: true) : Create(correctedConversionNode.Operand); return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue, isImplicit); } } } private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) { IOperation operand = Create(boundAsOperator.Operand); SyntaxNode syntax = boundAsOperator.Syntax; Conversion conversion = BoundNode.GetConversion(boundAsOperator.OperandConversion, boundAsOperator.OperandPlaceholder); bool isTryCast = true; bool isChecked = false; ITypeSymbol? type = boundAsOperator.GetPublicTypeSymbol(); bool isImplicit = boundAsOperator.WasCompilerGenerated; return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) { IOperation target = CreateDelegateTargetOperation(boundDelegateCreationExpression); SyntaxNode syntax = boundDelegateCreationExpression.Syntax; ITypeSymbol? type = boundDelegateCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDelegateCreationExpression.WasCompilerGenerated; return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) { bool isVirtual = (methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls; IOperation? instance = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); SyntaxNode bindingSyntax = boundMethodGroup.Syntax; ITypeSymbol? bindingType = null; bool isImplicit = boundMethodGroup.WasCompilerGenerated; return new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), isVirtual, instance, _semanticModel, bindingSyntax, bindingType, boundMethodGroup.WasCompilerGenerated); } private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) { IOperation value = Create(boundIsOperator.Operand); ITypeSymbol? typeOperand = boundIsOperator.TargetType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundIsOperator.Syntax; ITypeSymbol? type = boundIsOperator.GetPublicTypeSymbol(); bool isNegated = false; bool isImplicit = boundIsOperator.WasCompilerGenerated; return new IsTypeOperation(value, typeOperand, isNegated, _semanticModel, syntax, type, isImplicit); } private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) { ITypeSymbol? typeOperand = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundSizeOfOperator.Syntax; ITypeSymbol? type = boundSizeOfOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundSizeOfOperator.ConstantValue; bool isImplicit = boundSizeOfOperator.WasCompilerGenerated; return new SizeOfOperation(typeOperand, _semanticModel, syntax, type, constantValue, isImplicit); } private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) { ITypeSymbol? typeOperand = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundTypeOfOperator.Syntax; ITypeSymbol? type = boundTypeOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundTypeOfOperator.WasCompilerGenerated; return new TypeOfOperation(typeOperand, _semanticModel, syntax, type, isImplicit); } private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) { ImmutableArray<IOperation> dimensionSizes = CreateFromArray<BoundExpression, IOperation>(boundArrayCreation.Bounds); IArrayInitializerOperation? arrayInitializer = (IArrayInitializerOperation?)Create(boundArrayCreation.InitializerOpt); SyntaxNode syntax = boundArrayCreation.Syntax; ITypeSymbol? type = boundArrayCreation.GetPublicTypeSymbol(); bool isImplicit = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); return new ArrayCreationOperation(dimensionSizes, arrayInitializer, _semanticModel, syntax, type, isImplicit); } private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) { ImmutableArray<IOperation> elementValues = CreateFromArray<BoundExpression, IOperation>(boundArrayInitialization.Initializers); SyntaxNode syntax = boundArrayInitialization.Syntax; bool isImplicit = boundArrayInitialization.WasCompilerGenerated; return new ArrayInitializerOperation(elementValues, _semanticModel, syntax, isImplicit); } private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) { SyntaxNode syntax = boundDefaultLiteral.Syntax; ConstantValue? constantValue = boundDefaultLiteral.ConstantValue; bool isImplicit = boundDefaultLiteral.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type: null, constantValue, isImplicit); } private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) { SyntaxNode syntax = boundDefaultExpression.Syntax; ITypeSymbol? type = boundDefaultExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundDefaultExpression.ConstantValue; bool isImplicit = boundDefaultExpression.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundBaseReference.Syntax; ITypeSymbol? type = boundBaseReference.GetPublicTypeSymbol(); bool isImplicit = boundBaseReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundThisReference.Syntax; ITypeSymbol? type = boundThisReference.GetPublicTypeSymbol(); bool isImplicit = boundThisReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { return IsMemberInitializer(boundAssignmentOperator) ? (IOperation)CreateBoundMemberInitializerOperation(boundAssignmentOperator) : CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); } private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) => boundAssignmentOperator.Right?.Kind == BoundKind.ObjectInitializerExpression || boundAssignmentOperator.Right?.Kind == BoundKind.CollectionInitializerExpression; private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(!IsMemberInitializer(boundAssignmentOperator)); IOperation target = Create(boundAssignmentOperator.Left); IOperation value = Create(boundAssignmentOperator.Right); bool isRef = boundAssignmentOperator.IsRef; SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundAssignmentOperator.ConstantValue; bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicit); } private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(IsMemberInitializer(boundAssignmentOperator)); IOperation initializedMember = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new MemberInitializerOperation(initializedMember, initializer, _semanticModel, syntax, type, isImplicit); } private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) { IOperation target = Create(boundCompoundAssignmentOperator.Left); IOperation value = Create(boundCompoundAssignmentOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); Conversion inConversion = BoundNode.GetConversion(boundCompoundAssignmentOperator.LeftConversion, boundCompoundAssignmentOperator.LeftPlaceholder); Conversion outConversion = BoundNode.GetConversion(boundCompoundAssignmentOperator.FinalConversion, boundCompoundAssignmentOperator.FinalPlaceholder); bool isLifted = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); bool isChecked = boundCompoundAssignmentOperator.Operator.Kind.IsChecked(); IMethodSymbol operatorMethod = boundCompoundAssignmentOperator.Operator.Method.GetPublicSymbol(); SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; ITypeSymbol? type = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundCompoundAssignmentOperator.WasCompilerGenerated; return new CompoundAssignmentOperation(inConversion, outConversion, operatorKind, isLifted, isChecked, operatorMethod, target, value, _semanticModel, syntax, type, isImplicit); } private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) { OperationKind operationKind = Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? OperationKind.Decrement : OperationKind.Increment; bool isPostfix = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); bool isLifted = boundIncrementOperator.OperatorKind.IsLifted(); bool isChecked = boundIncrementOperator.OperatorKind.IsChecked(); IOperation target = Create(boundIncrementOperator.Operand); IMethodSymbol? operatorMethod = boundIncrementOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundIncrementOperator.Syntax; ITypeSymbol? type = boundIncrementOperator.GetPublicTypeSymbol(); bool isImplicit = boundIncrementOperator.WasCompilerGenerated; return new IncrementOrDecrementOperation(isPostfix, isLifted, isChecked, target, operatorMethod, operationKind, _semanticModel, syntax, type, isImplicit); } private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) { SyntaxNode syntax = boundBadExpression.Syntax; // We match semantic model here: if the expression IsMissing, we have a null type, rather than the ErrorType of the bound node. ITypeSymbol? type = syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol(); // if child has syntax node point to same syntax node as bad expression, then this invalid expression is implicit bool isImplicit = boundBadExpression.WasCompilerGenerated || boundBadExpression.ChildBoundNodes.Any(e => e?.Syntax == boundBadExpression.Syntax); var children = CreateFromArray<BoundExpression, IOperation>(boundBadExpression.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundNewT.InitializerExpressionOpt); SyntaxNode syntax = boundNewT.Syntax; ITypeSymbol? type = boundNewT.GetPublicTypeSymbol(); bool isImplicit = boundNewT.WasCompilerGenerated; return new TypeParameterObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(creation.InitializerExpressionOpt); SyntaxNode syntax = creation.Syntax; ITypeSymbol? type = creation.GetPublicTypeSymbol(); bool isImplicit = creation.WasCompilerGenerated; return new NoPiaObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) { UnaryOperatorKind unaryOperatorKind = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); IOperation operand = Create(boundUnaryOperator.Operand); IMethodSymbol? operatorMethod = boundUnaryOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundUnaryOperator.Syntax; ITypeSymbol? type = boundUnaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundUnaryOperator.ConstantValue; bool isLifted = boundUnaryOperator.OperatorKind.IsLifted(); bool isChecked = boundUnaryOperator.OperatorKind.IsChecked(); bool isImplicit = boundUnaryOperator.WasCompilerGenerated; return new UnaryOperation(unaryOperatorKind, operand, isLifted, isChecked, operatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) { if (boundBinaryOperatorBase is BoundBinaryOperator { InterpolatedStringHandlerData: not null } binary) { return CreateBoundInterpolatedStringBinaryOperator(binary); } // Binary operators can be nested _many_ levels deep, and cause a stack overflow if we manually recurse. // To solve this, we use a manual stack for the left side. var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = boundBinaryOperatorBase; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null and not BoundBinaryOperator { InterpolatedStringHandlerData: not null }); Debug.Assert(stack.Count > 0); IOperation? left = null; while (stack.TryPop(out currentBinary)) { left ??= Create(currentBinary.Left); IOperation right = Create(currentBinary.Right); left = currentBinary switch { BoundBinaryOperator binaryOp => CreateBoundBinaryOperatorOperation(binaryOp, left, right), BoundUserDefinedConditionalLogicalOperator logicalOp => createBoundUserDefinedConditionalLogicalOperator(logicalOp, left, right), { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; } Debug.Assert(left is not null && stack.Count == 0); stack.Free(); return left; IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol operatorMethod = boundBinaryOperator.LogicalOperator.GetPublicSymbol(); IMethodSymbol unaryOperatorMethod = boundBinaryOperator.OperatorKind.Operator() == CSharp.BinaryOperatorKind.And ? boundBinaryOperator.FalseOperator.GetPublicSymbol() : boundBinaryOperator.TrueOperator.GetPublicSymbol(); SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } } private IBinaryOperation CreateBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol? operatorMethod = boundBinaryOperator.Method.GetPublicSymbol(); IMethodSymbol? unaryOperatorMethod = null; // For dynamic logical operator MethodOpt is actually the unary true/false operator if (boundBinaryOperator.Type.IsDynamic() && (operatorKind == BinaryOperatorKind.ConditionalAnd || operatorKind == BinaryOperatorKind.ConditionalOr) && operatorMethod?.Parameters.Length == 1) { unaryOperatorMethod = operatorMethod; operatorMethod = null; } SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundInterpolatedStringBinaryOperator(BoundBinaryOperator boundBinaryOperator) { Debug.Assert(boundBinaryOperator.InterpolatedStringHandlerData is not null); Func<BoundInterpolatedString, int, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createInterpolatedString = createInterpolatedStringOperand; Func<BoundBinaryOperator, IOperation, IOperation, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createBinaryOperator = createBoundBinaryOperatorOperation; return boundBinaryOperator.RewriteInterpolatedStringAddition((this, boundBinaryOperator.InterpolatedStringHandlerData.GetValueOrDefault()), createInterpolatedString, createBinaryOperator); static IInterpolatedStringOperation createInterpolatedStringOperand( BoundInterpolatedString boundInterpolatedString, int i, (CSharpOperationFactory @this, InterpolatedStringHandlerData Data) arg) => [email protected](boundInterpolatedString, arg.Data.PositionInfo[i]); static IBinaryOperation createBoundBinaryOperatorOperation( BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right, (CSharpOperationFactory @this, InterpolatedStringHandlerData _) arg) => [email protected](boundBinaryOperator, left, right); } private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) { IOperation left = Create(boundTupleBinaryOperator.Left); IOperation right = Create(boundTupleBinaryOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); SyntaxNode syntax = boundTupleBinaryOperator.Syntax; ITypeSymbol? type = boundTupleBinaryOperator.GetPublicTypeSymbol(); bool isImplicit = boundTupleBinaryOperator.WasCompilerGenerated; return new TupleBinaryOperation(operatorKind, left, right, _semanticModel, syntax, type, isImplicit); } private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) { IOperation condition = Create(boundConditionalOperator.Condition); IOperation whenTrue = Create(boundConditionalOperator.Consequence); IOperation whenFalse = Create(boundConditionalOperator.Alternative); bool isRef = boundConditionalOperator.IsRef; SyntaxNode syntax = boundConditionalOperator.Syntax; ITypeSymbol? type = boundConditionalOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConditionalOperator.ConstantValue; bool isImplicit = boundConditionalOperator.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) { IOperation value = Create(boundNullCoalescingOperator.LeftOperand); IOperation whenNull = Create(boundNullCoalescingOperator.RightOperand); SyntaxNode syntax = boundNullCoalescingOperator.Syntax; ITypeSymbol? type = boundNullCoalescingOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundNullCoalescingOperator.ConstantValue; bool isImplicit = boundNullCoalescingOperator.WasCompilerGenerated; Conversion valueConversion = BoundNode.GetConversion(boundNullCoalescingOperator.LeftConversion, boundNullCoalescingOperator.LeftPlaceholder); if (valueConversion.Exists && !valueConversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } return new CoalesceOperation(value, whenNull, valueConversion, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) { IOperation target = Create(boundNode.LeftOperand); IOperation value = Create(boundNode.RightOperand); SyntaxNode syntax = boundNode.Syntax; ITypeSymbol? type = boundNode.GetPublicTypeSymbol(); bool isImplicit = boundNode.WasCompilerGenerated; return new CoalesceAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) { IOperation awaitedValue = Create(boundAwaitExpression.Expression); SyntaxNode syntax = boundAwaitExpression.Syntax; ITypeSymbol? type = boundAwaitExpression.GetPublicTypeSymbol(); bool isImplicit = boundAwaitExpression.WasCompilerGenerated; return new AwaitOperation(awaitedValue, _semanticModel, syntax, type, isImplicit); } private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) { IOperation arrayReference = Create(boundArrayAccess.Expression); ImmutableArray<IOperation> indices = CreateFromArray<BoundExpression, IOperation>(boundArrayAccess.Indices); SyntaxNode syntax = boundArrayAccess.Syntax; ITypeSymbol? type = boundArrayAccess.GetPublicTypeSymbol(); bool isImplicit = boundArrayAccess.WasCompilerGenerated; return new ArrayElementReferenceOperation(arrayReference, indices, _semanticModel, syntax, type, isImplicit); } private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) { IOperation argument = Create(boundNameOfOperator.Argument); SyntaxNode syntax = boundNameOfOperator.Syntax; ITypeSymbol? type = boundNameOfOperator.GetPublicTypeSymbol(); ConstantValue constantValue = boundNameOfOperator.ConstantValue; bool isImplicit = boundNameOfOperator.WasCompilerGenerated; return new NameOfOperation(argument, _semanticModel, syntax, type, constantValue, isImplicit); } private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) { IOperation expression = Create(boundThrowExpression.Expression); SyntaxNode syntax = boundThrowExpression.Syntax; ITypeSymbol? type = boundThrowExpression.GetPublicTypeSymbol(); bool isImplicit = boundThrowExpression.WasCompilerGenerated; return new ThrowOperation(expression, _semanticModel, syntax, type, isImplicit); } private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) { IOperation reference = Create(boundAddressOfOperator.Operand); SyntaxNode syntax = boundAddressOfOperator.Syntax; ITypeSymbol? type = boundAddressOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundAddressOfOperator.WasCompilerGenerated; return new AddressOfOperation(reference, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = boundImplicitReceiver.Syntax; ITypeSymbol? type = boundImplicitReceiver.GetPublicTypeSymbol(); bool isImplicit = boundImplicitReceiver.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) { IOperation operation = Create(boundConditionalAccess.Receiver); IOperation whenNotNull = Create(boundConditionalAccess.AccessExpression); SyntaxNode syntax = boundConditionalAccess.Syntax; ITypeSymbol? type = boundConditionalAccess.GetPublicTypeSymbol(); bool isImplicit = boundConditionalAccess.WasCompilerGenerated; return new ConditionalAccessOperation(operation, whenNotNull, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) { SyntaxNode syntax = boundConditionalReceiver.Syntax; ITypeSymbol? type = boundConditionalReceiver.GetPublicTypeSymbol(); bool isImplicit = boundConditionalReceiver.WasCompilerGenerated; return new ConditionalAccessInstanceOperation(_semanticModel, syntax, type, isImplicit); } private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) { ImmutableArray<IFieldSymbol> initializedFields = ImmutableArray.Create<IFieldSymbol>(boundFieldEqualsValue.Field.GetPublicSymbol()); IOperation value = Create(boundFieldEqualsValue.Value); SyntaxNode syntax = boundFieldEqualsValue.Syntax; bool isImplicit = boundFieldEqualsValue.WasCompilerGenerated; return new FieldInitializerOperation(initializedFields, boundFieldEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) { ImmutableArray<IPropertySymbol> initializedProperties = ImmutableArray.Create<IPropertySymbol>(boundPropertyEqualsValue.Property.GetPublicSymbol()); IOperation value = Create(boundPropertyEqualsValue.Value); SyntaxNode syntax = boundPropertyEqualsValue.Syntax; bool isImplicit = boundPropertyEqualsValue.WasCompilerGenerated; return new PropertyInitializerOperation(initializedProperties, boundPropertyEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) { IParameterSymbol parameter = boundParameterEqualsValue.Parameter.GetPublicSymbol(); IOperation value = Create(boundParameterEqualsValue.Value); SyntaxNode syntax = boundParameterEqualsValue.Syntax; bool isImplicit = boundParameterEqualsValue.WasCompilerGenerated; return new ParameterInitializerOperation(parameter, boundParameterEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) { ImmutableArray<IOperation> operations = CreateFromArray<BoundStatement, IOperation>(boundBlock.Statements); ImmutableArray<ILocalSymbol> locals = boundBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundBlock.Syntax; bool isImplicit = boundBlock.WasCompilerGenerated; return new BlockOperation(operations, locals, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) { ILabelSymbol target = boundContinueStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Continue; SyntaxNode syntax = boundContinueStatement.Syntax; bool isImplicit = boundContinueStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) { ILabelSymbol target = boundBreakStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Break; SyntaxNode syntax = boundBreakStatement.Syntax; bool isImplicit = boundBreakStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) { IOperation? returnedValue = null; SyntaxNode syntax = boundYieldBreakStatement.Syntax; bool isImplicit = boundYieldBreakStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldBreak, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) { ILabelSymbol target = boundGotoStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.GoTo; SyntaxNode syntax = boundGotoStatement.Syntax; bool isImplicit = boundGotoStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) { SyntaxNode syntax = boundNoOpStatement.Syntax; bool isImplicit = boundNoOpStatement.WasCompilerGenerated; return new EmptyOperation(_semanticModel, syntax, isImplicit); } private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) { IOperation condition = Create(boundIfStatement.Condition); IOperation whenTrue = Create(boundIfStatement.Consequence); IOperation? whenFalse = Create(boundIfStatement.AlternativeOpt); bool isRef = false; SyntaxNode syntax = boundIfStatement.Syntax; ITypeSymbol? type = null; ConstantValue? constantValue = null; bool isImplicit = boundIfStatement.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) { IOperation condition = Create(boundWhileStatement.Condition); IOperation body = Create(boundWhileStatement.Body); ImmutableArray<ILocalSymbol> locals = boundWhileStatement.Locals.GetPublicSymbols(); ILabelSymbol continueLabel = boundWhileStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundWhileStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = true; bool conditionIsUntil = false; SyntaxNode syntax = boundWhileStatement.Syntax; bool isImplicit = boundWhileStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) { IOperation condition = Create(boundDoStatement.Condition); IOperation body = Create(boundDoStatement.Body); ILabelSymbol continueLabel = boundDoStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundDoStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = false; bool conditionIsUntil = false; ImmutableArray<ILocalSymbol> locals = boundDoStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundDoStatement.Syntax; bool isImplicit = boundDoStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) { ImmutableArray<IOperation> before = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Initializer)); IOperation? condition = Create(boundForStatement.Condition); ImmutableArray<IOperation> atLoopBottom = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Increment)); IOperation body = Create(boundForStatement.Body); ImmutableArray<ILocalSymbol> locals = boundForStatement.OuterLocals.GetPublicSymbols(); ImmutableArray<ILocalSymbol> conditionLocals = boundForStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol continueLabel = boundForStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForStatement.Syntax; bool isImplicit = boundForStatement.WasCompilerGenerated; return new ForLoopOperation(before, conditionLocals, condition, atLoopBottom, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) { ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; ForEachLoopOperationInfo? info; if (enumeratorInfoOpt != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var compilation = (CSharpCompilation)_semanticModel.Compilation; var iDisposable = enumeratorInfoOpt.IsAsync ? compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : compilation.GetSpecialType(SpecialType.System_IDisposable); info = new ForEachLoopOperationInfo(enumeratorInfoOpt.ElementType.GetPublicSymbol(), enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), isAsynchronous: enumeratorInfoOpt.IsAsync, needsDispose: enumeratorInfoOpt.NeedsDisposal, knownToImplementIDisposable: enumeratorInfoOpt.NeedsDisposal ? compilation.Conversions. ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, iDisposable, ref discardedUseSiteInfo).IsImplicit : false, enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(), BoundNode.GetConversion(enumeratorInfoOpt.CurrentConversion, enumeratorInfoOpt.CurrentPlaceholder), BoundNode.GetConversion(boundForEachStatement.ElementConversion, boundForEachStatement.ElementPlaceholder), getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorInfo is { Method: { IsExtensionMethod: true } } getEnumeratorInfo ? Operation.SetParentOperation( DeriveArguments( getEnumeratorInfo.Method, getEnumeratorInfo.Arguments, argumentsToParametersOpt: default, getEnumeratorInfo.DefaultArguments, getEnumeratorInfo.Expanded, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), null) : default, disposeArguments: enumeratorInfoOpt.PatternDisposeInfo is object ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default); } else { info = null; } return info; } internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) { if (boundForEachStatement.DeconstructionOpt != null) { return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); } else if (boundForEachStatement.IterationErrorExpressionOpt != null) { return Create(boundForEachStatement.IterationErrorExpressionOpt); } else { Debug.Assert(boundForEachStatement.IterationVariables.Length == 1); var local = boundForEachStatement.IterationVariables[0]; // We use iteration variable type syntax as the underlying syntax node as there is no variable declarator syntax in the syntax tree. var declaratorSyntax = boundForEachStatement.IterationVariableType.Syntax; return new VariableDeclaratorOperation(local.GetPublicSymbol(), initializer: null, ignoredArguments: ImmutableArray<IOperation>.Empty, semanticModel: _semanticModel, syntax: declaratorSyntax, isImplicit: false); } } private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) { IOperation loopControlVariable = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); IOperation collection = Create(boundForEachStatement.Expression); var nextVariables = ImmutableArray<IOperation>.Empty; IOperation body = Create(boundForEachStatement.Body); ForEachLoopOperationInfo? info = GetForEachLoopOperatorInfo(boundForEachStatement); ImmutableArray<ILocalSymbol> locals = boundForEachStatement.IterationVariables.GetPublicSymbols(); ILabelSymbol continueLabel = boundForEachStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForEachStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForEachStatement.Syntax; bool isImplicit = boundForEachStatement.WasCompilerGenerated; bool isAsynchronous = boundForEachStatement.AwaitOpt != null; return new ForEachLoopOperation(loopControlVariable, collection, nextVariables, info, isAsynchronous, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) { var body = (IBlockOperation)Create(boundTryStatement.TryBlock); ImmutableArray<ICatchClauseOperation> catches = CreateFromArray<BoundCatchBlock, ICatchClauseOperation>(boundTryStatement.CatchBlocks); var @finally = (IBlockOperation?)Create(boundTryStatement.FinallyBlockOpt); SyntaxNode syntax = boundTryStatement.Syntax; bool isImplicit = boundTryStatement.WasCompilerGenerated; return new TryOperation(body, catches, @finally, exitLabel: null, _semanticModel, syntax, isImplicit); } private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) { IOperation? exceptionDeclarationOrExpression = CreateVariableDeclarator((BoundLocal?)boundCatchBlock.ExceptionSourceOpt); // The exception filter prologue is introduced during lowering, so should be null here. Debug.Assert(boundCatchBlock.ExceptionFilterPrologueOpt is null); IOperation? filter = Create(boundCatchBlock.ExceptionFilterOpt); IBlockOperation handler = (IBlockOperation)Create(boundCatchBlock.Body); ITypeSymbol exceptionType = boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol() ?? _semanticModel.Compilation.ObjectType; ImmutableArray<ILocalSymbol> locals = boundCatchBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundCatchBlock.Syntax; bool isImplicit = boundCatchBlock.WasCompilerGenerated; return new CatchClauseOperation(exceptionDeclarationOrExpression, exceptionType, locals, filter, handler, _semanticModel, syntax, isImplicit); } private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) { IVariableDeclarationGroupOperation variables = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); IOperation body = Create(boundFixedStatement.Body); ImmutableArray<ILocalSymbol> locals = boundFixedStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundFixedStatement.Syntax; bool isImplicit = boundFixedStatement.WasCompilerGenerated; return new FixedOperation(locals, variables, body, _semanticModel, syntax, isImplicit); } private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) { Debug.Assert((boundUsingStatement.DeclarationsOpt == null) != (boundUsingStatement.ExpressionOpt == null)); Debug.Assert(boundUsingStatement.ExpressionOpt is object || boundUsingStatement.Locals.Length > 0); IOperation resources = Create(boundUsingStatement.DeclarationsOpt ?? (BoundNode)boundUsingStatement.ExpressionOpt!); IOperation body = Create(boundUsingStatement.Body); ImmutableArray<ILocalSymbol> locals = boundUsingStatement.Locals.GetPublicSymbols(); bool isAsynchronous = boundUsingStatement.AwaitOpt != null; DisposeOperationInfo disposeOperationInfo = boundUsingStatement.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default; SyntaxNode syntax = boundUsingStatement.Syntax; bool isImplicit = boundUsingStatement.WasCompilerGenerated; return new UsingOperation(resources, body, locals, isAsynchronous, disposeOperationInfo, _semanticModel, syntax, isImplicit); } private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) { IOperation? thrownObject = Create(boundThrowStatement.ExpressionOpt); SyntaxNode syntax = boundThrowStatement.Syntax; ITypeSymbol? statementType = null; bool isImplicit = boundThrowStatement.WasCompilerGenerated; return new ThrowOperation(thrownObject, _semanticModel, syntax, statementType, isImplicit); } private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) { IOperation? returnedValue = Create(boundReturnStatement.ExpressionOpt); SyntaxNode syntax = boundReturnStatement.Syntax; bool isImplicit = boundReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.Return, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) { IOperation returnedValue = Create(boundYieldReturnStatement.Expression); SyntaxNode syntax = boundYieldReturnStatement.Syntax; bool isImplicit = boundYieldReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldReturn, _semanticModel, syntax, isImplicit); } private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) { // If there is no Enter2 method, then there will be no lock taken reference bool legacyMode = _semanticModel.Compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2) == null; ILocalSymbol? lockTakenSymbol = legacyMode ? null : new SynthesizedLocal((_semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart) as IMethodSymbol).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)_semanticModel.Compilation).GetSpecialType(SpecialType.System_Boolean)), SynthesizedLocalKind.LockTaken, syntaxOpt: boundLockStatement.Argument.Syntax).GetPublicSymbol(); IOperation lockedValue = Create(boundLockStatement.Argument); IOperation body = Create(boundLockStatement.Body); SyntaxNode syntax = boundLockStatement.Syntax; bool isImplicit = boundLockStatement.WasCompilerGenerated; return new LockOperation(lockedValue, body, lockTakenSymbol, _semanticModel, syntax, isImplicit); } private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) { SyntaxNode syntax = boundBadStatement.Syntax; // if child has syntax node point to same syntax node as bad statement, then this invalid statement is implicit bool isImplicit = boundBadStatement.WasCompilerGenerated || boundBadStatement.ChildBoundNodes.Any(e => e?.Syntax == boundBadStatement.Syntax); var children = CreateFromArray<BoundNode, IOperation>(boundBadStatement.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type: null, constantValue: null, isImplicit); } private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) { var node = boundLocalDeclaration.Syntax; var kind = node.Kind(); SyntaxNode varStatement; SyntaxNode varDeclaration; switch (kind) { case SyntaxKind.LocalDeclarationStatement: { var statement = (LocalDeclarationStatementSyntax)node; // this happen for simple int i = 0; // var statement points to LocalDeclarationStatementSyntax varStatement = statement; varDeclaration = statement.Declaration; break; } case SyntaxKind.VariableDeclarator: { // this happen for 'for loop' initializer // We generate a DeclarationGroup for this scenario to maintain tree shape consistency across IOperation. // var statement points to VariableDeclarationSyntax Debug.Assert(node.Parent != null); varStatement = node.Parent; varDeclaration = node.Parent; break; } default: { Debug.Fail($"Unexpected syntax: {kind}"); // otherwise, they points to whatever bound nodes are pointing to. varStatement = varDeclaration = node; break; } } bool multiVariableImplicit = boundLocalDeclaration.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundLocalDeclaration, varDeclaration); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundLocalDeclaration, varDeclaration); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, varDeclaration, multiVariableImplicit); // In the case of a for loop, varStatement and varDeclaration will be the same syntax node. // We can only have one explicit operation, so make sure this node is implicit in that scenario. bool isImplicit = (varStatement == varDeclaration) || boundLocalDeclaration.WasCompilerGenerated; return new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, varStatement, isImplicit); } private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) { // The syntax for the boundMultipleLocalDeclarations can either be a LocalDeclarationStatement or a VariableDeclaration, depending on the context // (using/fixed statements vs variable declaration) // We generate a DeclarationGroup for these scenarios (using/fixed) to maintain tree shape consistency across IOperation. SyntaxNode declarationGroupSyntax = boundMultipleLocalDeclarations.Syntax; SyntaxNode declarationSyntax = declarationGroupSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)declarationGroupSyntax).Declaration : declarationGroupSyntax; bool declarationIsImplicit = boundMultipleLocalDeclarations.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundMultipleLocalDeclarations, declarationSyntax); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundMultipleLocalDeclarations, declarationSyntax); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, declarationSyntax, declarationIsImplicit); // If the syntax was the same, we're in a fixed statement or using statement. We make the Group operation implicit in this scenario, as the // syntax itself is a VariableDeclaration. We do this for using declarations as well, but since that doesn't have a separate parent bound // node, we need to check the current node for that explicitly. bool isImplicit = declarationGroupSyntax == declarationSyntax || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; var variableDeclaration = new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, declarationGroupSyntax, isImplicit); if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations usingDecl) { return new UsingDeclarationOperation( variableDeclaration, isAsynchronous: usingDecl.AwaitOpt is object, disposeInfo: usingDecl.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: usingDecl.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(usingDecl.PatternDisposeInfoOpt, usingDecl.Syntax)) : default, _semanticModel, declarationGroupSyntax, isImplicit: boundMultipleLocalDeclarations.WasCompilerGenerated); } return variableDeclaration; } private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) { ILabelSymbol label = boundLabelStatement.Label.GetPublicSymbol(); SyntaxNode syntax = boundLabelStatement.Syntax; bool isImplicit = boundLabelStatement.WasCompilerGenerated; return new LabeledOperation(label, operation: null, _semanticModel, syntax, isImplicit); } private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) { ILabelSymbol label = boundLabeledStatement.Label.GetPublicSymbol(); IOperation labeledStatement = Create(boundLabeledStatement.Body); SyntaxNode syntax = boundLabeledStatement.Syntax; bool isImplicit = boundLabeledStatement.WasCompilerGenerated; return new LabeledOperation(label, labeledStatement, _semanticModel, syntax, isImplicit); } private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) { // lambda body can point to expression directly and binder can insert expression statement there. and end up statement pointing to // expression syntax node since there is no statement syntax node to point to. this will mark such one as implicit since it doesn't // actually exist in code bool isImplicit = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; SyntaxNode syntax = boundExpressionStatement.Syntax; // If we're creating the tree for a speculatively-bound constructor initializer, there can be a bound sequence as the child node here // that corresponds to the lifetime of any declared variables. IOperation expression = Create(boundExpressionStatement.Expression); if (boundExpressionStatement.Expression is BoundSequence sequence) { Debug.Assert(boundExpressionStatement.Syntax == sequence.Value.Syntax); isImplicit = true; } return new ExpressionStatementOperation(expression, _semanticModel, syntax, isImplicit); } internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) { SyntaxNode syntax = boundTupleExpression.Syntax; bool isImplicit = boundTupleExpression.WasCompilerGenerated; ITypeSymbol? type = boundTupleExpression.GetPublicTypeSymbol(); if (syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { var tupleOperation = CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false); return new DeclarationExpressionOperation(tupleOperation, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } TypeSymbol? naturalType = boundTupleExpression switch { BoundTupleLiteral { Type: var t } => t, BoundConvertedTupleLiteral { SourceTuple: { Type: var t } } => t, BoundConvertedTupleLiteral => null, { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; ImmutableArray<IOperation> elements = CreateFromArray<BoundExpression, IOperation>(boundTupleExpression.Arguments); return new TupleOperation(elements, naturalType.GetPublicSymbol(), _semanticModel, syntax, type, isImplicit); } private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo = null) { Debug.Assert(positionInfo == null || boundInterpolatedString.InterpolationData == null); ImmutableArray<IInterpolatedStringContentOperation> parts = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, positionInfo ?? boundInterpolatedString.InterpolationData?.PositionInfo[0]); SyntaxNode syntax = boundInterpolatedString.Syntax; ITypeSymbol? type = boundInterpolatedString.GetPublicTypeSymbol(); ConstantValue? constantValue = boundInterpolatedString.ConstantValue; bool isImplicit = boundInterpolatedString.WasCompilerGenerated; return new InterpolatedStringOperation(parts, _semanticModel, syntax, type, constantValue, isImplicit); } internal ImmutableArray<IInterpolatedStringContentOperation> CreateBoundInterpolatedStringContentOperation(ImmutableArray<BoundExpression> parts, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo) { return positionInfo is { } info ? createHandlerInterpolatedStringContent(info) : createNonHandlerInterpolatedStringContent(); ImmutableArray<IInterpolatedStringContentOperation> createNonHandlerInterpolatedStringContent() { var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); foreach (var part in parts) { if (part.Kind == BoundKind.StringInsert) { builder.Add((IInterpolatedStringContentOperation)Create(part)); } else { builder.Add(CreateBoundInterpolatedStringTextOperation((BoundLiteral)part)); } } return builder.ToImmutableAndFree(); } ImmutableArray<IInterpolatedStringContentOperation> createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> positionInfo) { // For interpolated string handlers, we want to deconstruct the `AppendLiteral`/`AppendFormatted` calls into // their relevant components. // https://github.com/dotnet/roslyn/issues/54505 we need to handle interpolated strings used as handler conversions. Debug.Assert(parts.Length == positionInfo.Length); var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); for (int i = 0; i < parts.Length; i++) { var part = parts[i]; var currentPosition = positionInfo[i]; BoundExpression value; BoundExpression? alignment; BoundExpression? format; switch (part) { case BoundCall call: (value, alignment, format) = getCallInfo(call.Arguments, call.ArgumentNamesOpt, currentPosition); break; case BoundDynamicInvocation dynamicInvocation: (value, alignment, format) = getCallInfo(dynamicInvocation.Arguments, dynamicInvocation.ArgumentNamesOpt, currentPosition); break; case BoundBadExpression bad: Debug.Assert(bad.ChildBoundNodes.Length == 2 + // initial value + receiver is added to the end (currentPosition.HasAlignment ? 1 : 0) + (currentPosition.HasFormat ? 1 : 0)); value = bad.ChildBoundNodes[0]; if (currentPosition.IsLiteral) { alignment = format = null; } else { alignment = currentPosition.HasAlignment ? bad.ChildBoundNodes[1] : null; format = currentPosition.HasFormat ? bad.ChildBoundNodes[^2] : null; } break; default: throw ExceptionUtilities.UnexpectedValue(part.Kind); } // We are intentionally not checking the part for implicitness here. The part is a generated AppendLiteral or AppendFormatted call, // and will always be marked as CompilerGenerated. However, our existing behavior for non-builder interpolated strings does not mark // the BoundLiteral or BoundStringInsert components as compiler generated. This generates a non-implicit IInterpolatedStringTextOperation // with an implicit literal underneath, and a non-implicit IInterpolationOperation with non-implicit underlying components. bool isImplicit = false; if (currentPosition.IsLiteral) { Debug.Assert(alignment is null); Debug.Assert(format is null); IOperation valueOperation = value switch { BoundLiteral l => CreateBoundLiteralOperation(l, @implicit: true), BoundConversion { Operand: BoundLiteral } c => CreateBoundConversionOperation(c, forceOperandImplicitLiteral: true), _ => throw ExceptionUtilities.UnexpectedValue(value.Kind), }; Debug.Assert(valueOperation.IsImplicit); builder.Add(new InterpolatedStringTextOperation(valueOperation, _semanticModel, part.Syntax, isImplicit)); } else { IOperation valueOperation = Create(value); IOperation? alignmentOperation = Create(alignment); IOperation? formatOperation = Create(format); Debug.Assert(valueOperation.Syntax != part.Syntax); builder.Add(new InterpolationOperation(valueOperation, alignmentOperation, formatOperation, _semanticModel, part.Syntax, isImplicit)); } } return builder.ToImmutableAndFree(); static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) { BoundExpression value = arguments[0]; if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) { // There was no alignment/format component, as binding will qualify those parameters by name return (value, null, null); } else { var alignmentIndex = argumentNamesOpt.IndexOf("alignment"); BoundExpression? alignment = alignmentIndex == -1 ? null : arguments[alignmentIndex]; var formatIndex = argumentNamesOpt.IndexOf("format"); BoundExpression? format = formatIndex == -1 ? null : arguments[formatIndex]; return (value, alignment, format); } } } } private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) { IOperation expression = Create(boundStringInsert.Value); IOperation? alignment = Create(boundStringInsert.Alignment); IOperation? formatString = Create(boundStringInsert.Format); SyntaxNode syntax = boundStringInsert.Syntax; bool isImplicit = boundStringInsert.WasCompilerGenerated; return new InterpolationOperation(expression, alignment, formatString, _semanticModel, syntax, isImplicit); } private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) { IOperation text = CreateBoundLiteralOperation(boundNode, @implicit: true); SyntaxNode syntax = boundNode.Syntax; bool isImplicit = boundNode.WasCompilerGenerated; return new InterpolatedStringTextOperation(text, _semanticModel, syntax, isImplicit); } private IInterpolatedStringHandlerCreationOperation CreateInterpolatedStringHandler(BoundConversion conversion) { Debug.Assert(conversion.Conversion.IsInterpolatedStringHandler); InterpolatedStringHandlerData interpolationData = conversion.Operand switch { BoundInterpolatedString { InterpolationData: { } data } => data, BoundBinaryOperator { InterpolatedStringHandlerData: { } data } => data, _ => throw ExceptionUtilities.UnexpectedValue(conversion.Operand.Kind) }; var construction = Create(interpolationData.Construction); var content = createContent(conversion.Operand); var isImplicit = conversion.WasCompilerGenerated || !conversion.ExplicitCastInCode; return new InterpolatedStringHandlerCreationOperation( construction, interpolationData.HasTrailingHandlerValidityParameter, interpolationData.UsesBoolReturns, content, _semanticModel, conversion.Syntax, conversion.GetPublicTypeSymbol(), isImplicit); IOperation createContent(BoundExpression current) { switch (current) { case BoundBinaryOperator binaryOperator: var left = createContent(binaryOperator.Left); var right = createContent(binaryOperator.Right); return new InterpolatedStringAdditionOperation(left, right, _semanticModel, current.Syntax, current.WasCompilerGenerated); case BoundInterpolatedString interpolatedString: var parts = interpolatedString.Parts.SelectAsArray( static IInterpolatedStringContentOperation (part, @this) => { var methodName = part switch { BoundCall { Method.Name: var name } => name, BoundDynamicInvocation { Expression: BoundMethodGroup { Name: var name } } => name, { HasErrors: true } => "", _ => throw ExceptionUtilities.UnexpectedValue(part.Kind) }; var operationKind = methodName switch { "" => OperationKind.InterpolatedStringAppendInvalid, BoundInterpolatedString.AppendLiteralMethod => OperationKind.InterpolatedStringAppendLiteral, BoundInterpolatedString.AppendFormattedMethod => OperationKind.InterpolatedStringAppendFormatted, _ => throw ExceptionUtilities.UnexpectedValue(methodName) }; return new InterpolatedStringAppendOperation(@this.Create(part), operationKind, @this._semanticModel, part.Syntax, isImplicit: true); }, this); return new InterpolatedStringOperation( parts, _semanticModel, interpolatedString.Syntax, interpolatedString.GetPublicTypeSymbol(), interpolatedString.ConstantValue, isImplicit: interpolatedString.WasCompilerGenerated); default: throw ExceptionUtilities.UnexpectedValue(current.Kind); } } } private IOperation CreateBoundInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder placeholder) { SyntaxNode syntax = placeholder.Syntax; bool isImplicit = true; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); if (placeholder.ArgumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter) { return new InvalidOperation(ImmutableArray<IOperation>.Empty, _semanticModel, syntax, type, placeholder.ConstantValue, isImplicit); } const int NonArgumentIndex = -1; var (placeholderKind, argumentIndex) = placeholder.ArgumentIndex switch { >= 0 and var index => (InterpolatedStringArgumentPlaceholderKind.CallsiteArgument, index), BoundInterpolatedStringArgumentPlaceholder.InstanceParameter => (InterpolatedStringArgumentPlaceholderKind.CallsiteReceiver, NonArgumentIndex), BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter => (InterpolatedStringArgumentPlaceholderKind.TrailingValidityArgument, NonArgumentIndex), _ => throw ExceptionUtilities.UnexpectedValue(placeholder.ArgumentIndex) }; return new InterpolatedStringHandlerArgumentPlaceholderOperation(argumentIndex, placeholderKind, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder placeholder) { return new InstanceReferenceOperation( InstanceReferenceKind.InterpolatedStringHandler, _semanticModel, placeholder.Syntax, placeholder.GetPublicTypeSymbol(), isImplicit: placeholder.WasCompilerGenerated); } private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) { IOperation value = Create(boundConstantPattern.Value); SyntaxNode syntax = boundConstantPattern.Syntax; bool isImplicit = boundConstantPattern.WasCompilerGenerated; TypeSymbol inputType = boundConstantPattern.InputType; TypeSymbol narrowedType = boundConstantPattern.NarrowedType; return new ConstantPatternOperation(value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); IOperation value = Create(boundRelationalPattern.Value); SyntaxNode syntax = boundRelationalPattern.Syntax; bool isImplicit = boundRelationalPattern.WasCompilerGenerated; TypeSymbol inputType = boundRelationalPattern.InputType; TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; return new RelationalPatternOperation(operatorKind, value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) { ISymbol? variable = boundDeclarationPattern.Variable.GetPublicSymbol(); if (variable == null && boundDeclarationPattern.VariableAccess?.Kind == BoundKind.DiscardExpression) { variable = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); } ITypeSymbol inputType = boundDeclarationPattern.InputType.GetPublicSymbol(); ITypeSymbol narrowedType = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); bool acceptsNull = boundDeclarationPattern.IsVar; ITypeSymbol? matchedType = acceptsNull ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol(); SyntaxNode syntax = boundDeclarationPattern.Syntax; bool isImplicit = boundDeclarationPattern.WasCompilerGenerated; return new DeclarationPatternOperation(matchedType, acceptsNull, variable, inputType, narrowedType, _semanticModel, syntax, isImplicit); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) { ITypeSymbol matchedType = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundRecursivePattern.Deconstruction is { IsDefault: false } deconstructions ? deconstructions.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; ImmutableArray<IPropertySubpatternOperation> propertySubpatterns = boundRecursivePattern.Properties is { IsDefault: false } properties ? properties.SelectAsArray((p, arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType), (Fac: this, MatchedType: matchedType)) : ImmutableArray<IPropertySubpatternOperation>.Empty; return new RecursivePatternOperation( matchedType, boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, isImplicit: boundRecursivePattern.WasCompilerGenerated); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) { ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundITuplePattern.Subpatterns is { IsDefault: false } subpatterns ? subpatterns.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; return new RecursivePatternOperation( boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns: ImmutableArray<IPropertySubpatternOperation>.Empty, declaredSymbol: null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, isImplicit: boundITuplePattern.WasCompilerGenerated); } private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) { return new TypePatternOperation( matchedType: boundTypePattern.NarrowedType.GetPublicSymbol(), inputType: boundTypePattern.InputType.GetPublicSymbol(), narrowedType: boundTypePattern.NarrowedType.GetPublicSymbol(), semanticModel: _semanticModel, syntax: boundTypePattern.Syntax, isImplicit: boundTypePattern.WasCompilerGenerated); } private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) { return new NegatedPatternOperation( (IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, isImplicit: boundNegatedPattern.WasCompilerGenerated); } private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) { return new BinaryPatternOperation( boundBinaryPattern.Disjunction ? BinaryOperatorKind.Or : BinaryOperatorKind.And, (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, isImplicit: boundBinaryPattern.WasCompilerGenerated); } private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) { IOperation value = Create(boundSwitchStatement.Expression); ImmutableArray<ISwitchCaseOperation> cases = CreateFromArray<BoundSwitchSection, ISwitchCaseOperation>(boundSwitchStatement.SwitchSections); ImmutableArray<ILocalSymbol> locals = boundSwitchStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol exitLabel = boundSwitchStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundSwitchStatement.Syntax; bool isImplicit = boundSwitchStatement.WasCompilerGenerated; return new SwitchOperation(locals, value, cases, exitLabel, _semanticModel, syntax, isImplicit); } private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) { ImmutableArray<ICaseClauseOperation> clauses = CreateFromArray<BoundSwitchLabel, ICaseClauseOperation>(boundSwitchSection.SwitchLabels); ImmutableArray<IOperation> body = CreateFromArray<BoundStatement, IOperation>(boundSwitchSection.Statements); ImmutableArray<ILocalSymbol> locals = boundSwitchSection.Locals.GetPublicSymbols(); return new SwitchCaseOperation(clauses, body, locals, condition: null, _semanticModel, boundSwitchSection.Syntax, isImplicit: boundSwitchSection.WasCompilerGenerated); } private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) { IOperation value = Create(boundSwitchExpression.Expression); ImmutableArray<ISwitchExpressionArmOperation> arms = CreateFromArray<BoundSwitchExpressionArm, ISwitchExpressionArmOperation>(boundSwitchExpression.SwitchArms); bool isExhaustive; if (boundSwitchExpression.DefaultLabel != null) { Debug.Assert(boundSwitchExpression.DefaultLabel is GeneratedLabelSymbol); isExhaustive = false; } else { isExhaustive = true; } return new SwitchExpressionOperation( value, arms, isExhaustive, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); } private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); IOperation? guard = Create(boundSwitchExpressionArm.WhenClause); IOperation value = Create(boundSwitchExpressionArm.Value); return new SwitchExpressionArmOperation( pattern, guard, value, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); } private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) { SyntaxNode syntax = boundSwitchLabel.Syntax; bool isImplicit = boundSwitchLabel.WasCompilerGenerated; LabelSymbol label = boundSwitchLabel.Label; if (boundSwitchLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel) { Debug.Assert(boundSwitchLabel.Pattern.Kind == BoundKind.DiscardPattern); return new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern cp && cp.InputType.IsValidV6SwitchGoverningType()) { return new SingleValueCaseClauseOperation(Create(cp.Value), label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchLabel.Pattern); IOperation? guard = Create(boundSwitchLabel.WhenClause); return new PatternCaseClauseOperation(label.GetPublicSymbol(), pattern, guard, _semanticModel, syntax, isImplicit); } } private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) { IOperation value = Create(boundIsPatternExpression.Expression); IPatternOperation pattern = (IPatternOperation)Create(boundIsPatternExpression.Pattern); SyntaxNode syntax = boundIsPatternExpression.Syntax; ITypeSymbol? type = boundIsPatternExpression.GetPublicTypeSymbol(); bool isImplicit = boundIsPatternExpression.WasCompilerGenerated; return new IsPatternOperation(value, pattern, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) { if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) { // Currently we have no IOperation APIs for different query clauses or continuation. return Create(boundQueryClause.Value); } IOperation operation = Create(boundQueryClause.Value); SyntaxNode syntax = boundQueryClause.Syntax; ITypeSymbol? type = boundQueryClause.GetPublicTypeSymbol(); bool isImplicit = boundQueryClause.WasCompilerGenerated; return new TranslatedQueryOperation(operation, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) { // We do not have operation nodes for the bound range variables, just it's value. return Create(boundRangeVariable.Value); } private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) { return new DiscardOperation( ((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), isImplicit: boundNode.WasCompilerGenerated); } private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) { return new UnaryOperation( UnaryOperatorKind.Hat, Create(boundIndex.Operand), isLifted: boundIndex.Type.IsNullableType(), isChecked: false, operatorMethod: null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), constantValue: null, isImplicit: boundIndex.WasCompilerGenerated); } private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) { IOperation? left = Create(boundRange.LeftOperandOpt); IOperation? right = Create(boundRange.RightOperandOpt); return new RangeOperation( left, right, isLifted: boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), isImplicit: boundRange.WasCompilerGenerated); } private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) { return new DiscardPatternOperation( inputType: boundNode.InputType.GetPublicSymbol(), narrowedType: boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) { // We treat `c is { ... .Prop: <pattern> }` as `c is { ...: { Prop: <pattern> } }` SyntaxNode subpatternSyntax = subpattern.Syntax; BoundPropertySubpatternMember? member = subpattern.Member; IPatternOperation pattern = (IPatternOperation)Create(subpattern.Pattern); if (member is null) { var reference = OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray<IOperation>.Empty, isImplicit: true); return new PropertySubpatternOperation(reference, pattern, _semanticModel, subpatternSyntax, isImplicit: false); } // Create an operation for last property access: // `{ SingleProp: <pattern operation> }` // or // `.LastProp: <pattern operation>` portion (treated as `{ LastProp: <pattern operation> }`) var nameSyntax = member.Syntax; var inputType = getInputType(member, matchedType); IPropertySubpatternOperation? result = createPropertySubpattern(member.Symbol, pattern, inputType, nameSyntax, isSingle: member.Receiver is null); while (member.Receiver is not null) { member = member.Receiver; nameSyntax = member.Syntax; ITypeSymbol previousType = inputType; inputType = getInputType(member, matchedType); // Create an operation for a preceding property access: // { PrecedingProp: <previous pattern operation> } IPatternOperation nestedPattern = new RecursivePatternOperation( matchedType: previousType, deconstructSymbol: null, deconstructionSubpatterns: ImmutableArray<IPatternOperation>.Empty, propertySubpatterns: ImmutableArray.Create(result), declaredSymbol: null, previousType, narrowedType: previousType, semanticModel: _semanticModel, nameSyntax, isImplicit: true); result = createPropertySubpattern(member.Symbol, nestedPattern, inputType, nameSyntax, isSingle: false); } return result; IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation pattern, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) { Debug.Assert(nameSyntax is not null); IOperation reference; switch (symbol) { case FieldSymbol field: { var constantValue = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); reference = new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration: false, createReceiver(), _semanticModel, nameSyntax, type: field.Type.GetPublicSymbol(), constantValue, isImplicit: false); break; } case PropertySymbol property: { reference = new PropertyReferenceOperation(property.GetPublicSymbol(), ImmutableArray<IArgumentOperation>.Empty, createReceiver(), _semanticModel, nameSyntax, type: property.Type.GetPublicSymbol(), isImplicit: false); break; } default: { // We should expose the symbol in this case somehow: // https://github.com/dotnet/roslyn/issues/33175 reference = OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray<IOperation>.Empty, isImplicit: false); break; } } var syntaxForPropertySubpattern = isSingle ? subpatternSyntax : nameSyntax; return new PropertySubpatternOperation(reference, pattern, _semanticModel, syntaxForPropertySubpattern, isImplicit: !isSingle); IOperation? createReceiver() => symbol?.IsStatic == false ? new InstanceReferenceOperation(InstanceReferenceKind.PatternInput, _semanticModel, nameSyntax!, receiverType, isImplicit: true) : null; } static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol matchedType) => member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? matchedType; } private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = placeholder.Syntax; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); bool isImplicit = placeholder.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private ImmutableArray<IArgumentOperation> CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) { // can't be an extension method for dispose Debug.Assert(!patternDisposeInfo.Method.IsStatic); if (patternDisposeInfo.Method.ParameterCount == 0) { return ImmutableArray<IArgumentOperation>.Empty; } Debug.Assert(!patternDisposeInfo.Expanded || patternDisposeInfo.Method.GetParameters().Last().OriginalDefinition.Type.IsSZArray()); var args = DeriveArguments( patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax, invokedAsExtensionMethod: false); return Operation.SetParentOperation(args, null); } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IInterpolatedStringOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IInterpolatedStringExpression : SemanticModelTestBase { private static CSharpTestSource GetSource(string code, bool hasDefaultHandler) => hasDefaultHandler ? new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) } : code; [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_Empty(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: """") (Syntax: '$""""') Parts(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_OnlyTextPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""Only text part""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: ""Only text part"") (Syntax: '$""Only text part""') Parts(1): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'Only text part') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Only text part"", IsImplicit) (Syntax: 'Only text part') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_OnlyInterpolationPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""{1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_EmptyInterpolationPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""{}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{}') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Alignment: null FormatString: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1733: Expected expression // Console.WriteLine(/*<bind>*/$"{}"/*</bind>*/); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(8, 40) }; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_TextAndInterpolationParts(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(int x) { Console.WriteLine(/*<bind>*/$""String {x} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x}') Expression: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment(bool hasDefaultHandler) { string source = @" using System; internal class Class { private string x = string.Empty; private int y = 0; public void M() { Console.WriteLine(/*<bind>*/$""String {x,20} and {y:D3} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,20}') Expression: IFieldReferenceOperation: System.String Class.x (OperationKind.FieldReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'x') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y:D3}') Expression: IFieldReferenceOperation: System.Int32 Class.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'y') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InterpolationAndFormatAndAlignment(bool hasDefaultHandler) { string source = @" using System; internal class Class { private string x = string.Empty; private const int y = 0; public void M() { Console.WriteLine(/*<bind>*/$""String {x,y:D3}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x,y:D3}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,y:D3}') Expression: IFieldReferenceOperation: System.String Class.x (OperationKind.FieldReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'x') Alignment: IFieldReferenceOperation: System.Int32 Class.y (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 0) (Syntax: 'y') Instance Receiver: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InvocationInInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { string x = string.Empty; int y = 0; Console.WriteLine(/*<bind>*/$""String {x} and {M2(y)} and constant {1}""/*</bind>*/); } private string M2(int z) => z.ToString(); } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x}') Expression: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{M2(y)}') Expression: IInvocationOperation ( System.String Class.M2(System.Int32 z)) (OperationKind.Invocation, Type: System.String) (Syntax: 'M2(y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (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) Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_NestedInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { string x = string.Empty; int y = 0; Console.WriteLine(/*<bind>*/$""String {M2($""{y}"")}""/*</bind>*/); } private int M2(string z) => Int32.Parse(z); } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {M2($""{y}"")}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{M2($""{y}"")}') Expression: IInvocationOperation ( System.Int32 Class.M2(System.String z)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2($""{y}"")') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: '$""{y}""') IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{y}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y}') Expression: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') Alignment: null FormatString: 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) Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InvalidExpressionInInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(int x) { Console.WriteLine(/*<bind>*/$""String {x1} and constant {Class}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""String {x ... nt {Class}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{x1}') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x1') Children(0) Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{Class}') Expression: IInvalidOperation (OperationKind.Invalid, Type: Class, IsInvalid, IsImplicit) (Syntax: 'Class') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Class') Alignment: null FormatString: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'x1' does not exist in the current context // Console.WriteLine(/*<bind>*/$"String {x1} and constant {Class}"/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 47), // CS0119: 'Class' is a type, which is not valid in the given context // Console.WriteLine(/*<bind>*/$"String {x1} and constant {Class}"/*</bind>*/); Diagnostic(ErrorCode.ERR_BadSKunknown, "Class").WithArguments("Class", "type").WithLocation(8, 65) }; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_Empty_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string p) /*<bind>*/{ p = $""""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $"""";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""""') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: """") (Syntax: '$""""') Parts(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_OnlyTextPart_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string p) /*<bind>*/{ p = $""Only text part""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""Only text part"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""Only text part""') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: ""Only text part"") (Syntax: '$""Only text part""') Parts(1): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'Only text part') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Only text part"", IsImplicit) (Syntax: 'Only text part') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_OnlyInterpolationPart_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string p) /*<bind>*/{ p = $""{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c)}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_MultipleInterpolationParts_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string c2, string p) /*<bind>*/{ p = $""{(a ? b : c)}{c2}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? ... : c)}{c2}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? b : c)}{c2}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c)}{c2}""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{c2}') Expression: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_TextAndInterpolationParts_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, bool a2, string b2, string c2, string p) /*<bind>*/{ p = $""String1 {(a ? b : c)} and String2 {(a2 ? b2 : c2)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""Strin ... b2 : c2)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""Strin ... b2 : c2)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String1 { ... b2 : c2)}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String1 ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String1 "", IsImplicit) (Syntax: 'String1 ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and String2 ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and String2 "", IsImplicit) (Syntax: ' and String2 ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a2 ? b2 : c2)}') Expression: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a2 ? b2 : c2') Alignment: null FormatString: null Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string p) /*<bind>*/{ p = $""{(a ? b : c),20:D3}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? ... c),20:D3}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? ... c),20:D3}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c),20:D3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c),20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow_02(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string b2, string c, string p) /*<bind>*/{ p = $""{b2,20:D3}{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{b2,2 ... ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{b2,2 ... ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b2,20:D3 ... ? b : c)}""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b2,20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b2') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow_03(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string b2, string b3, string c, string p) /*<bind>*/{ p = $""{b2,20:D3}{b3,21:D4}{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] [5] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b3') Value: IParameterReferenceOperation: b3 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b3') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '21') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 21) (Syntax: '21') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{b2,2 ... ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{b2,2 ... ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b2,20:D3 ... ? b : c)}""') Parts(3): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b2,20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b2') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b3,21:D4}') Expression: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b3') Alignment: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 21, IsImplicit) (Syntax: '21') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D4"") (Syntax: ':D4') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_NestedInterpolation_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string a, int? b, int c) /*<bind>*/{ a = $""{$""{b ?? c}""}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.String) (Syntax: 'a') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = $""{$""{b ?? c}""}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'a = $""{$""{b ?? c}""}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{$""{b ?? c}""}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{$""{b ?? c}""}') Expression: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b ?? c}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b ?? c}') Expression: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Alignment: null FormatString: null Alignment: null FormatString: null Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_ConditionalCodeInAlignment_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, int b, int c, string d, string p) /*<bind>*/{ p = $""{d,(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd') Value: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.String) (Syntax: 'd') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = $""{d,(a ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'p = $""{d,(a ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{d,(a ? b : c)}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{d,(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'd') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,18): error CS0150: A constant value is expected // p = $"{d,(a ? b : c)}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(a ? b : c)").WithLocation(8, 18) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_ConditionalCodeInAlignment_Flow_02(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string c2, string p) /*<bind>*/{ p = $""{c2,(a ? b : c):D3}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = $""{c2,( ... : c):D3}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'p = $""{c2,( ... b : c):D3}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{c2,(a ? b : c):D3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{c2,(a ? b : c):D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'c2') Alignment: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,20): error CS0029: Cannot implicitly convert type 'string' to 'int' // p = $"{c2,(a ? b : c):D3}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a ? b : c").WithArguments("string", "int").WithLocation(8, 20) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [Fact] public void InterpolatedStringHandlerConversion_01() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_02() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_03() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_04() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_05() { var code = @" using System.Runtime.CompilerServices; int i = 0; CustomHandler /*<bind>*/c = $""literal{i}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler {} "; var expectedDiagnostics = new[] { // (4,29): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""literal{i}""").WithArguments("CustomHandler", "2").WithLocation(4, 29), // (4,29): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""literal{i}""").WithArguments("CustomHandler", "3").WithLocation(4, 29), // (4,31): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 31), // (4,31): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "literal").WithArguments("?.()").WithLocation(4, 31), // (4,38): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{i}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 38), // (4,38): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{i}").WithArguments("?.()").WithLocation(4, 38) }; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c = $""literal{i}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= $""literal{i}""') IOperation: (OperationKind.None, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""literal{i}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null, IsInvalid) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsInvalid, IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i') Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_06() { var code = @" using System.Runtime.CompilerServices; int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) {} public void AppendFormatted(object o, object alignment, object format) {} public void AppendLiteral(object o) {} } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'literal') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: ':test') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_07() { var code = @" using System.Runtime.CompilerServices; CustomHandler /*<bind>*/c = $""{}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) {} public void AppendFormatted(object o, object alignment, object format) {} public void AppendLiteral(object o) {} } "; var expectedDiagnostics = new[] { // (3,32): error CS1733: Expected expression // CustomHandler /*<bind>*/c = $"{}"/*</bind>*/; Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(3, 32) }; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c = $""{}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= $""{}""') IOperation: (OperationKind.None, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{}') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void DynamicConstruction_01() { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(/*<bind>*/$""literal{d,1:format}""/*</bind>*/); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d, int alignment, string format) { Console.WriteLine(""AppendFormatted""); } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{d,1:format}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'literal') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{d,1:format}') Expression: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""format"") (Syntax: ':format') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void DynamicConstruction_02() { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, /*<bind>*/$""{1}literal""/*</bind>*/); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var expectedDiagnostics = new[] { // (4,16): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, /*<bind>*/$"{1}literal"/*</bind>*/); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, @"$""{1}literal""").WithArguments("CustomHandler").WithLocation(4, 16) }; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{1}literal""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null, IsInvalid) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsInvalid, IsImplicit) (Syntax: 'literal') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void InterpolationEscapeConstantValue_WithDefaultHandler() { var code = @" int i = 1; System.Console.WriteLine(/*<bind>*/$""{{ {i} }}""/*</bind>*/);"; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{{ {i} }}""') Parts(3): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: '{{ ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{ "", IsImplicit) (Syntax: '{{ ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' }}') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" }"", IsImplicit) (Syntax: ' }}') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void InterpolationEscapeConstantValue_WithoutDefaultHandler() { var code = @" int i = 1; System.Console.WriteLine(/*<bind>*/$""{{ {i} }}""/*</bind>*/);"; var expectedDiagnostics = DiagnosticDescription.None; // The difference between this test and the previous one is the constant value of the ILiteralOperations. When handlers are involved, the // constant value is { and }. When they are not involved, the constant values are {{ and }} string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{{ {i} }}""') Parts(3): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: '{{ ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{{ "", IsImplicit) (Syntax: '{{ ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' }}') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" }}"", IsImplicit) (Syntax: ' }}') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" #pragma warning disable CS0219 // Unused local object o1; object o2; object o3; _ = /*<bind>*/$""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1/*</bind>*/; "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... null}"" + 1') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... o3 = null}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... o2 = null}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o1 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o1 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o1 = null') Left: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o1') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o2 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o2 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o2 = null') Left: ILocalReferenceOperation: o2 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o2') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o3 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o3 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o3 = null') Left: ILocalReferenceOperation: o3 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o3') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ParenthesizedInterpolatedStringsAdded() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = /*<bind>*/(($""{i1,1:d}"" + $""{i2,2:f}"") + $""{i3,3:g}"") + ($""{i4,4:h}"" + ($""{i5,5:i}"" + $""{i6,6:j}""))/*</bind>*/; "; var expectedDiagnostics = DiagnosticDescription.None; var expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1,1:d} ... $""{i3,3:g}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1,1:d}"" ... $""{i2,2:f}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1,1:d}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1,1:d}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""d"") (Syntax: ':d') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2,2:f}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2,2:f}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""f"") (Syntax: ':f') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3,3:g}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3,3:g}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""g"") (Syntax: ':g') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4,4:h}"" ... ""{i6,6:j}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4,4:h}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4,4:h}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""h"") (Syntax: ':h') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i5,5:i}"" ... $""{i6,6:j}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5,5:i}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5,5:i}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""i"") (Syntax: ':i') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6,6:j}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6,6:j}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""j"") (Syntax: ':j') "; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IInterpolatedStringExpression : SemanticModelTestBase { private static CSharpTestSource GetSource(string code, bool hasDefaultHandler) => hasDefaultHandler ? new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) } : code; [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_Empty(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: """") (Syntax: '$""""') Parts(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_OnlyTextPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""Only text part""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: ""Only text part"") (Syntax: '$""Only text part""') Parts(1): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'Only text part') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Only text part"", IsImplicit) (Syntax: 'Only text part') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_OnlyInterpolationPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""{1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_EmptyInterpolationPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""{}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{}') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Alignment: null FormatString: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1733: Expected expression // Console.WriteLine(/*<bind>*/$"{}"/*</bind>*/); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(8, 40) }; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_TextAndInterpolationParts(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(int x) { Console.WriteLine(/*<bind>*/$""String {x} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x}') Expression: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment(bool hasDefaultHandler) { string source = @" using System; internal class Class { private string x = string.Empty; private int y = 0; public void M() { Console.WriteLine(/*<bind>*/$""String {x,20} and {y:D3} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,20}') Expression: IFieldReferenceOperation: System.String Class.x (OperationKind.FieldReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'x') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y:D3}') Expression: IFieldReferenceOperation: System.Int32 Class.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'y') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InterpolationAndFormatAndAlignment(bool hasDefaultHandler) { string source = @" using System; internal class Class { private string x = string.Empty; private const int y = 0; public void M() { Console.WriteLine(/*<bind>*/$""String {x,y:D3}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x,y:D3}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,y:D3}') Expression: IFieldReferenceOperation: System.String Class.x (OperationKind.FieldReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'x') Alignment: IFieldReferenceOperation: System.Int32 Class.y (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 0) (Syntax: 'y') Instance Receiver: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InvocationInInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { string x = string.Empty; int y = 0; Console.WriteLine(/*<bind>*/$""String {x} and {M2(y)} and constant {1}""/*</bind>*/); } private string M2(int z) => z.ToString(); } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x}') Expression: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{M2(y)}') Expression: IInvocationOperation ( System.String Class.M2(System.Int32 z)) (OperationKind.Invocation, Type: System.String) (Syntax: 'M2(y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (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) Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_NestedInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { string x = string.Empty; int y = 0; Console.WriteLine(/*<bind>*/$""String {M2($""{y}"")}""/*</bind>*/); } private int M2(string z) => Int32.Parse(z); } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {M2($""{y}"")}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{M2($""{y}"")}') Expression: IInvocationOperation ( System.Int32 Class.M2(System.String z)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2($""{y}"")') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: '$""{y}""') IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{y}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y}') Expression: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') Alignment: null FormatString: 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) Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InvalidExpressionInInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(int x) { Console.WriteLine(/*<bind>*/$""String {x1} and constant {Class}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""String {x ... nt {Class}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{x1}') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x1') Children(0) Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{Class}') Expression: IInvalidOperation (OperationKind.Invalid, Type: Class, IsInvalid, IsImplicit) (Syntax: 'Class') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Class') Alignment: null FormatString: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'x1' does not exist in the current context // Console.WriteLine(/*<bind>*/$"String {x1} and constant {Class}"/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 47), // CS0119: 'Class' is a type, which is not valid in the given context // Console.WriteLine(/*<bind>*/$"String {x1} and constant {Class}"/*</bind>*/); Diagnostic(ErrorCode.ERR_BadSKunknown, "Class").WithArguments("Class", "type").WithLocation(8, 65) }; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_Empty_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string p) /*<bind>*/{ p = $""""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $"""";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""""') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: """") (Syntax: '$""""') Parts(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_OnlyTextPart_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string p) /*<bind>*/{ p = $""Only text part""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""Only text part"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""Only text part""') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: ""Only text part"") (Syntax: '$""Only text part""') Parts(1): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'Only text part') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Only text part"", IsImplicit) (Syntax: 'Only text part') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_OnlyInterpolationPart_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string p) /*<bind>*/{ p = $""{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c)}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_MultipleInterpolationParts_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string c2, string p) /*<bind>*/{ p = $""{(a ? b : c)}{c2}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? ... : c)}{c2}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? b : c)}{c2}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c)}{c2}""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{c2}') Expression: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_TextAndInterpolationParts_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, bool a2, string b2, string c2, string p) /*<bind>*/{ p = $""String1 {(a ? b : c)} and String2 {(a2 ? b2 : c2)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""Strin ... b2 : c2)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""Strin ... b2 : c2)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String1 { ... b2 : c2)}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String1 ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String1 "", IsImplicit) (Syntax: 'String1 ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and String2 ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and String2 "", IsImplicit) (Syntax: ' and String2 ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a2 ? b2 : c2)}') Expression: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a2 ? b2 : c2') Alignment: null FormatString: null Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string p) /*<bind>*/{ p = $""{(a ? b : c),20:D3}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? ... c),20:D3}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? ... c),20:D3}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c),20:D3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c),20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow_02(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string b2, string c, string p) /*<bind>*/{ p = $""{b2,20:D3}{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{b2,2 ... ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{b2,2 ... ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b2,20:D3 ... ? b : c)}""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b2,20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b2') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow_03(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string b2, string b3, string c, string p) /*<bind>*/{ p = $""{b2,20:D3}{b3,21:D4}{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] [5] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b3') Value: IParameterReferenceOperation: b3 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b3') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '21') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 21) (Syntax: '21') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{b2,2 ... ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{b2,2 ... ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b2,20:D3 ... ? b : c)}""') Parts(3): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b2,20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b2') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b3,21:D4}') Expression: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b3') Alignment: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 21, IsImplicit) (Syntax: '21') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D4"") (Syntax: ':D4') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_NestedInterpolation_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string a, int? b, int c) /*<bind>*/{ a = $""{$""{b ?? c}""}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.String) (Syntax: 'a') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = $""{$""{b ?? c}""}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'a = $""{$""{b ?? c}""}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{$""{b ?? c}""}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{$""{b ?? c}""}') Expression: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b ?? c}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b ?? c}') Expression: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Alignment: null FormatString: null Alignment: null FormatString: null Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_ConditionalCodeInAlignment_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, int b, int c, string d, string p) /*<bind>*/{ p = $""{d,(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd') Value: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.String) (Syntax: 'd') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = $""{d,(a ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'p = $""{d,(a ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{d,(a ? b : c)}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{d,(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'd') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,18): error CS0150: A constant value is expected // p = $"{d,(a ? b : c)}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(a ? b : c)").WithLocation(8, 18) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_ConditionalCodeInAlignment_Flow_02(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string c2, string p) /*<bind>*/{ p = $""{c2,(a ? b : c):D3}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = $""{c2,( ... : c):D3}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'p = $""{c2,( ... b : c):D3}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{c2,(a ? b : c):D3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{c2,(a ? b : c):D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'c2') Alignment: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,20): error CS0029: Cannot implicitly convert type 'string' to 'int' // p = $"{c2,(a ? b : c):D3}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a ? b : c").WithArguments("string", "int").WithLocation(8, 20) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [Fact] public void InterpolatedStringHandlerConversion_01() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i,1:test}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i,1:test}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':test') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') 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) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_02() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{i,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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{i,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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i,1}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i,1}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i,1}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i,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) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_03() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i:test}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i:test}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i:test}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{i:test}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{i:test}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i:test}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i:test}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i:test}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i:test}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i:test}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':test') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') 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.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i:test}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i:test}') 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) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_04() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{i}""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{i}""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_05() { var code = @" using System.Runtime.CompilerServices; int i = 0; CustomHandler /*<bind>*/c = $""literal{i}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler {} "; var expectedDiagnostics = new[] { // (4,29): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""literal{i}""").WithArguments("CustomHandler", "2").WithLocation(4, 29), // (4,29): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""literal{i}""").WithArguments("CustomHandler", "3").WithLocation(4, 29), // (4,31): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 31), // (4,31): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "literal").WithArguments("?.()").WithLocation(4, 31), // (4,38): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{i}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 38), // (4,38): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{i}").WithArguments("?.()").WithLocation(4, 38) }; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c = $""literal{i}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= $""literal{i}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') Creation: IInvalidOperation (OperationKind.Invalid, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""literal{i}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendInvalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'literal') AppendCall: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'literal') Children(2): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'literal') Children(1): IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsInvalid) (Syntax: 'literal') IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendInvalid, Type: null, IsInvalid, IsImplicit) (Syntax: '{i}') AppendCall: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{i}') Children(2): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{i}') Children(1): IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_06() { var code = @" using System.Runtime.CompilerServices; int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) {} public void AppendFormatted(object o, object alignment, object format) {} public void AppendLiteral(object o) {} } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.Object o)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'literal') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i,1:test}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, System.Object alignment, System.Object format)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i,1:test}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: 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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':test') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: ':test') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') 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) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_07() { var code = @" using System.Runtime.CompilerServices; CustomHandler /*<bind>*/c = $""{}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) {} public void AppendFormatted(object o, object alignment, object format) {} public void AppendLiteral(object o) {} } "; var expectedDiagnostics = new[] { // (3,32): error CS1733: Expected expression // CustomHandler /*<bind>*/c = $"{}"/*</bind>*/; Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(3, 32) }; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c = $""{}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= $""{}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '$""{}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: '$""{}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '$""{}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '$""{}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsInvalid, IsImplicit) (Syntax: '{}') AppendCall: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '{}') Children(2): IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{}""') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_08() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: True, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( System.Boolean CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i,1:test}') AppendCall: IInvocationOperation ( System.Boolean CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: '{i,1:test}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':test') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') 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) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_09() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true, includeTrailingOutConstructorParameter: true); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: True, HandlerCreationHasSuccessParameter: True) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount, out System.Boolean success)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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: success) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') IInterpolatedStringHandlerArgumentPlaceholderOperation (TrailingValidityArgument) (OperationKind.InterpolatedStringHandlerArgumentPlaceholder, Type: null, IsImplicit) (Syntax: '$""literal{i,1:test}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( System.Boolean CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i,1:test}') AppendCall: IInvocationOperation ( System.Boolean CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: '{i,1:test}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':test') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') 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) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_10() { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(); /*<bind>*/c.M($""literal{c,1:format}"")/*</bind>*/; public class C { public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this() { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInvocationOperation ( void C.M(CustomHandler c)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'c.M($""liter ... 1:format}"")') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: '$""literal{c,1:format}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount, C c)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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: c) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') IInterpolatedStringHandlerArgumentPlaceholderOperation (CallsiteReceiver) (OperationKind.InterpolatedStringHandlerArgumentPlaceholder, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{c,1:format}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{c,1:format}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{c,1:format}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') 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: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':format') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""format"") (Syntax: ':format') 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) "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false), InterpolatedStringHandlerArgumentAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_11() { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(); /*<bind>*/c.M(true, $""literal{c,1:format}"")/*</bind>*/; public class C { public void M(bool b, [InterpolatedStringHandlerArgument(""b"")]CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, bool b, out bool success) : this() { success = true; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInvocationOperation ( void C.M(System.Boolean b, CustomHandler c)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'c.M(true, $ ... 1:format}"")') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'true') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') 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: c) (OperationKind.Argument, Type: null) (Syntax: '$""literal{c,1:format}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: True) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount, System.Boolean b, out System.Boolean success)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(4): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'true') IInterpolatedStringHandlerArgumentPlaceholderOperation (ArgumentIndex: 0) (OperationKind.InterpolatedStringHandlerArgumentPlaceholder, Type: null, IsImplicit) (Syntax: 'true') 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: success) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') IInterpolatedStringHandlerArgumentPlaceholderOperation (TrailingValidityArgument) (OperationKind.InterpolatedStringHandlerArgumentPlaceholder, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{c,1:format}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{c,1:format}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{c,1:format}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') 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: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':format') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""format"") (Syntax: ':format') 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) "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false), InterpolatedStringHandlerArgumentAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversionFlow_01() { var code = @" using System; using System.Runtime.CompilerServices; public class C { public void M(bool b, [InterpolatedStringHandlerArgument("""", ""b"")]CustomHandler c) {} public void M1(C c) /*<bind>*/{ c.M(true, $""literal{c,1:format}""); }/*</bind>*/ } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c, bool b, out bool success) : this() { success = true; } } "; var expectedDiagnostics = DiagnosticDescription.None; // Proper CFG support is tracked by https://github.com/dotnet/roslyn/issues/54718 string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M(true, $ ... :format}"");') Expression: IInvocationOperation ( void C.M(System.Boolean b, CustomHandler c)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'c.M(true, $ ... 1:format}"")') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'true') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') 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: c) (OperationKind.Argument, Type: null) (Syntax: '$""literal{c,1:format}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Children(2): IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount, C c, System.Boolean b, out System.Boolean success)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(5): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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: c) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'true') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'true') 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: success) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '$""literal{c,1:format}""') 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) Initializer: null IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{c,1:format}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{c,1:format}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{c,1:format}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{c,1:format}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') 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: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':format') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""format"") (Syntax: ':format') 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) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false), InterpolatedStringHandlerArgumentAttribute }, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void DynamicConstruction_01() { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; /*<bind>*/M($""literal{d,1:format}"")/*</bind>*/; void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d, int alignment, string format) { Console.WriteLine(""AppendFormatted""); } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInvocationOperation (void M(CustomHandler c)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M($""literal ... 1:format}"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: '$""literal{d,1:format}""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{d,1:format}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{d,1:format}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{d,1:format}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: '$""literal{d,1:format}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""literal{d,1:format}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""literal{d,1:format}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{d,1:format}""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(dynamic d)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{d,1:format}""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: d) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'literal') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'literal') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"") (Syntax: 'literal') 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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{d,1:format}') AppendCall: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic, IsImplicit) (Syntax: '{d,1:format}') Expression: IDynamicMemberReferenceOperation (Member Name: ""AppendFormatted"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null, IsImplicit) (Syntax: '{d,1:format}') Type Arguments(0) Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{d,1:format}""') Arguments(3): ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""format"") (Syntax: ':format') ArgumentNames(3): ""null"" ""alignment"" ""format"" ArgumentRefKinds(0) 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) "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void DynamicConstruction_02() { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; /*<bind>*/M(d, $""{1}literal"")/*</bind>*/; void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var expectedDiagnostics = new[] { // (4,16): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, /*<bind>*/$"{1}literal"/*</bind>*/); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, @"$""{1}literal""").WithArguments("CustomHandler").WithLocation(4, 16) }; string expectedOperationTree = @" IInvocationOperation (void M(dynamic d, CustomHandler c)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(d, $""{1}literal"")') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: d) (OperationKind.Argument, Type: null) (Syntax: 'd') ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') 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: c) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '$""{1}literal""') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{1}literal""') Creation: IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{1}literal""') Arguments(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsInvalid, IsImplicit) (Syntax: '$""{1}literal""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '$""{1}literal""') IInterpolatedStringHandlerArgumentPlaceholderOperation (ArgumentIndex: 0) (OperationKind.InterpolatedStringHandlerArgumentPlaceholder, Type: null, IsImplicit) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(3): None None None Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{1}literal""') Parts(2): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsInvalid, IsImplicit) (Syntax: '{1}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '{1}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{1}literal""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (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.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '{1}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (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.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '{1}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsInvalid, IsImplicit) (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) IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendLiteral, Type: null, IsInvalid, IsImplicit) (Syntax: 'literal') AppendCall: IInvocationOperation ( void CustomHandler.AppendLiteral(System.String literal)) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'literal') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{1}literal""') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literal) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'literal') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsInvalid) (Syntax: 'literal') 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) "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void InterpolationEscapeConstantValue_WithDefaultHandler() { var code = @" int i = 1; System.Console.WriteLine(/*<bind>*/$""{{ {i} }}""/*</bind>*/);"; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{{ {i} }}""') Parts(3): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: '{{ ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{ "", IsImplicit) (Syntax: '{{ ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' }}') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" }"", IsImplicit) (Syntax: ' }}') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void InterpolationEscapeConstantValue_WithoutDefaultHandler() { var code = @" int i = 1; System.Console.WriteLine(/*<bind>*/$""{{ {i} }}""/*</bind>*/);"; var expectedDiagnostics = DiagnosticDescription.None; // The difference between this test and the previous one is the constant value of the ILiteralOperations. When handlers are involved, the // constant value is { and }. When they are not involved, the constant values are {{ and }} string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{{ {i} }}""') Parts(3): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: '{{ ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{{ "", IsImplicit) (Syntax: '{{ ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' }}') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" }}"", IsImplicit) (Syntax: ' }}') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" #pragma warning disable CS0219 // Unused local object o1; object o2; object o3; _ = /*<bind>*/$""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1/*</bind>*/; "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... null}"" + 1') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... o3 = null}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... o2 = null}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o1 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o1 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o1 = null') Left: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o1') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o2 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o2 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o2 = null') Left: ILocalReferenceOperation: o2 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o2') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o3 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o3 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o3 = null') Left: ILocalReferenceOperation: o3 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o3') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ParenthesizedInterpolatedStringsAdded() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = /*<bind>*/(($""{i1,1:d}"" + $""{i2,2:f}"") + $""{i3,3:g}"") + ($""{i4,4:h}"" + ($""{i5,5:i}"" + $""{i6,6:j}""))/*</bind>*/; "; var expectedDiagnostics = DiagnosticDescription.None; var expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1,1:d} ... $""{i3,3:g}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1,1:d}"" ... $""{i2,2:f}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1,1:d}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1,1:d}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""d"") (Syntax: ':d') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2,2:f}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2,2:f}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""f"") (Syntax: ':f') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3,3:g}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3,3:g}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""g"") (Syntax: ':g') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4,4:h}"" ... ""{i6,6:j}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4,4:h}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4,4:h}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""h"") (Syntax: ':h') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i5,5:i}"" ... $""{i6,6:j}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5,5:i}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5,5:i}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""i"") (Syntax: ':i') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6,6:j}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6,6:j}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""j"") (Syntax: ':j') "; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ParenthesizedInterpolatedStringsAdded_CustomHandler() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; CustomHandler /*<bind>*/s = (($""{i1,1:d}"" + $""{i2,2:f}"") + $""{i3,3:g}"") + ($""{i4,4:h}"" + ($""{i5,5:i}"" + $""{i6,6:j}""))/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; var expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = (($""{i1 ... {i6,6:j}""))') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (($""{i1,1 ... {i6,6:j}""))') IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') 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) Initializer: null Content: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Left: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '($""{i1,1:d} ... $""{i3,3:g}""') Left: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i1,1:d}"" ... $""{i2,2:f}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1,1:d}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i1,1:d}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i1,1:d}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') 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: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':d') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""d"") (Syntax: ':d') 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: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2,2:f}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i2,2:f}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i2,2:f}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':f') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""f"") (Syntax: ':f') 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: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3,3:g}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i3,3:g}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i3,3:g}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':g') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""g"") (Syntax: ':g') 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: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i4,4:h}"" ... ""{i6,6:j}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4,4:h}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i4,4:h}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i4,4:h}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i4') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '4') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') 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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':h') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""h"") (Syntax: ':h') 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: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i5,5:i}"" ... $""{i6,6:j}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5,5:i}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i5,5:i}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i5,5:i}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i5') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') 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: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '5') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':i') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""i"") (Syntax: ':i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6,6:j}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i6,6:j}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i6,6:j}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i6') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') 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: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '6') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6') 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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':j') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""j"") (Syntax: ':j') 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) "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ExplicitCastToCustomHandler() { var code = @" int i1 = 1; CustomHandler s = /*<bind>*/(CustomHandler)$""{i1,1:d}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; var expectedOperationTree = @" IInterpolatedStringHandlerCreationOperation (HandlerAppendCallsReturnBool: False, HandlerCreationHasSuccessParameter: False) (OperationKind.InterpolatedStringHandlerCreation, Type: CustomHandler) (Syntax: '(CustomHand ... $""{i1,1:d}""') Creation: IObjectCreationOperation (Constructor: CustomHandler..ctor(System.Int32 literalLength, System.Int32 formattedCount)) (OperationKind.ObjectCreation, Type: CustomHandler, IsImplicit) (Syntax: '$""{i1,1:d}""') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: literalLength) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""{i1,1:d}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '$""{i1,1:d}""') 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: formattedCount) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '$""{i1,1:d}""') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '$""{i1,1:d}""') 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) Initializer: null Content: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1,1:d}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i1,1:d}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i1,1:d}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '$""{i1,1:d}""') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') 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: alignment) (OperationKind.Argument, Type: null, IsImplicit) (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: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: ':d') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""d"") (Syntax: ':d') 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) "; VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Test/Semantic/Semantics/InterpolationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class InterpolationTests : CompilingTestBase { [Fact] public void TestSimpleInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number }.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 }.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 }.""); Console.WriteLine($""Jenny don\'t change your number { number :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}.""); Console.WriteLine($""{number}""); } }"; string expectedOutput = @"Jenny don't change your number 8675309. Jenny don't change your number 8675309 . Jenny don't change your number 8675309. Jenny don't change your number 867-5309. Jenny don't change your number 867-5309 . Jenny don't change your number 867-5309. 8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestOnlyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}""); } }"; string expectedOutput = @"8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}{number}""); } }"; string expectedOutput = @"86753098675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}.""); } }"; string expectedOutput = @"Jenny don't change your number 867-5309 867-5309."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestEmptyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }.""); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,73): error CS1733: Expected expression // Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }."); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73) ); } [Fact] public void TestHalfOpenInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,63): error CS1010: Newline in constant // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63), // (6,5): error CS1010: Newline in constant // } Diagnostic(ErrorCode.ERR_NewlineInConst, "}").WithLocation(6, 5), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 // ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,5): error CS1010: Newline in constant // } Diagnostic(ErrorCode.ERR_NewlineInConst, "}").WithLocation(6, 5), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp03() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 /* ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,60): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, " {").WithLocation(5, 60), // (5,71): error CS1035: End-of-file found, '*/' expected // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71), // (7,2): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2), // (7,2): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void LambdaInInterp() { string source = @"using System; class Program { static void Main(string[] args) { //Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() }); Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}""); } static int number = 8675309; } "; string expectedOutput = @"jenny (408) 867-5309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OneLiteral() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""Hello"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Hello"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } [Fact] public void OneInsert() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; Console.WriteLine( $""{hello}"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldstr ""Hello"" IL_0005: dup IL_0006: brtrue.s IL_000e IL_0008: pop IL_0009: ldstr """" IL_000e: call ""void System.Console.WriteLine(string)"" IL_0013: ret } "); } [Fact] public void TwoInserts() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $""{hello}, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TwoInserts02() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $@""{ hello }, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")] public void DynamicInterpolation() { string source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { dynamic nil = null; dynamic a = new string[] {""Hello"", ""world""}; Console.WriteLine($""<{nil}>""); Console.WriteLine($""<{a}>""); } Expression<Func<string>> M(dynamic d) { return () => $""Dynamic: {d}""; } }"; string expectedOutput = @"<> <System.String[]>"; var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnclosedInterpolation01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31), // (7,5): error CS1010: Newline in constant // } Diagnostic(ErrorCode.ERR_NewlineInConst, "}").WithLocation(7, 5), // (7,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6), // (7,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6), // (8,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2)); } [Fact] public void UnclosedInterpolation02() { string source = @"class Program { static void Main(string[] args) { var x = $"";"; // The precise error messages are not important, but this must be an error. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,19): error CS1010: Newline in constant // var x = $"; Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19), // (5,20): error CS1002: ; expected // var x = $"; Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20) ); } [Fact] public void EmptyFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:}"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8089: Empty format specifier. // Console.WriteLine( $"{3:}" ); Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $"{3:d }" ); Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $@"{3:d Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d ").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS1733: Expected expression // Console.WriteLine( $"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32) ); } [Fact] public void MissingInterpolationExpression02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS1733: Expected expression // Console.WriteLine( $@"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression03() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( "; var normal = "$\""; var verbat = "$@\""; // ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail) Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline01() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" "" } ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline02() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" ""} ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void PreprocessorInsideInterpolation() { string source = @"class Program { static void Main() { var s = $@""{ #region : #endregion 0 }""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void EscapedCurly() { string source = @"class Program { static void Main() { var s1 = $"" \u007B ""; var s2 = $"" \u007D""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string. // var s1 = $" \u007B "; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21), // (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var s2 = $" \u007D"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21) ); } [Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")] public void NoFillIns01() { string source = @"class Program { static void Main() { System.Console.Write($""{{ x }}""); System.Console.WriteLine($@""This is a test""); } }"; string expectedOutput = @"{ x }This is a test"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BadAlignment() { string source = @"class Program { static void Main() { var s = $""{1,1E10}""; var t = $""{1,(int)1E10}""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22), // (5,22): error CS0150: A constant value is expected // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22), // (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override) // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22), // (6,22): error CS0150: A constant value is expected // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22) ); } [Fact] public void NestedInterpolatedVerbatim() { string source = @"using System; class Program { static void Main(string[] args) { var s = $@""{$@""{1}""}""; Console.WriteLine(s); } }"; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } // Since the platform type System.FormattableString is not yet in our platforms (at the // time of writing), we explicitly include the required platform types into the sources under test. private const string formattableString = @" /*============================================================ ** ** Class: FormattableString ** ** ** Purpose: implementation of the FormattableString ** class. ** ===========================================================*/ namespace System { /// <summary> /// A composite format string along with the arguments to be formatted. An instance of this /// type may result from the use of the C# or VB language primitive ""interpolated string"". /// </summary> public abstract class FormattableString : IFormattable { /// <summary> /// The composite format string. /// </summary> public abstract string Format { get; } /// <summary> /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> public abstract object[] GetArguments(); /// <summary> /// The number of arguments to be formatted. /// </summary> public abstract int ArgumentCount { get; } /// <summary> /// Returns one argument to be formatted from argument position <paramref name=""index""/>. /// </summary> public abstract object GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } /// <summary> /// Format the given object in the invariant culture. This static method may be /// imported in C# by /// <code> /// using static System.FormattableString; /// </code>. /// Within the scope /// of that import directive an interpolated string may be formatted in the /// invariant culture by writing, for example, /// <code> /// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"") /// </code> /// </summary> public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException(""formattable""); } return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); } } } /*============================================================ ** ** Class: FormattableStringFactory ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref=""FormattableString""/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format, params object[] arguments) { if (format == null) { throw new ArgumentNullException(""format""); } if (arguments == null) { throw new ArgumentNullException(""arguments""); } return new ConcreteFormattableString(format, arguments); } private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } public override object[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); } } } } "; [Fact] public void TargetType01() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; Console.Write(f is System.FormattableString); } }"; CompileAndVerify(source + formattableString, expectedOutput: "True"); } [Fact] public void TargetType02() { string source = @"using System; interface I1 { void M(String s); } interface I2 { void M(FormattableString s); } interface I3 { void M(IFormattable s); } interface I4 : I1, I2 {} interface I5 : I1, I3 {} interface I6 : I2, I3 {} interface I7 : I1, I2, I3 {} class C : I1, I2, I3, I4, I5, I6, I7 { public void M(String s) { Console.Write(1); } public void M(FormattableString s) { Console.Write(2); } public void M(IFormattable s) { Console.Write(3); } } class Program { public static void Main(string[] args) { C c = new C(); ((I1)c).M($""""); ((I2)c).M($""""); ((I3)c).M($""""); ((I4)c).M($""""); ((I5)c).M($""""); ((I6)c).M($""""); ((I7)c).M($""""); ((C)c).M($""""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "12311211"); } [Fact] public void MissingHelper() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; } }"; CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics( // (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported // IFormattable f = $"test"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26) ); } [Fact] public void AsyncInterp() { string source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { Task<string> hello = Task.FromResult(""Hello""); Task<string> world = Task.FromResult(""world""); M(hello, world).Wait(); } public static async Task M(Task<string> hello, Task<string> world) { Console.WriteLine($""{ await hello }, { await world }!""); } }"; CompileAndVerify( source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty); } [Fact] public void AlignmentExpression() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , -(3+4) }.""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "X = 123 ."); } [Fact] public void AlignmentMagnitude() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , (32768) }.""); Console.WriteLine($""X = { 123 , -(32768) }.""); Console.WriteLine($""X = { 123 , (32767) }.""); Console.WriteLine($""X = { 123 , -(32767) }.""); Console.WriteLine($""X = { 123 , int.MaxValue }.""); Console.WriteLine($""X = { 123 , int.MinValue }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , (32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42), // (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , -(32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41), // (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MaxValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41), // (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MinValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41) ); } [WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")] [Fact] public void InterpolationExpressionMustBeValue01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { String }.""); Console.WriteLine($""X = { null }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS0119: 'string' is a type, which is not valid in the given context // Console.WriteLine($"X = { String }."); Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35) ); } [Fact] public void InterpolationExpressionMustBeValue02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { x=>3 }.""); Console.WriteLine($""X = { Program.Main }.""); Console.WriteLine($""X = { Program.Main(null) }.""); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35), // (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS8917: The delegate type could not be inferred. // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x=>3").WithLocation(5, 35), // (6,35): warning CS8974: Converting method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "Program.Main").WithArguments("Main", "object").WithLocation(6, 35), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib01() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (15,21): error CS0117: 'string' does not contain a definition for 'Format' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib02() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Boolean Format(string format, int arg) { return true; } } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21) ); } [Fact] public void SillyCoreLib01() { var text = @"namespace System { interface IFormattable { } namespace Runtime.CompilerServices { public static class FormattableStringFactory { public static Bozo Create(string format, int arg) { return new Bozo(); } } } public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Bozo Format(string format, int arg) { return new Bozo(); } } public class FormattableString { } public class Bozo { public static implicit operator string(Bozo bozo) { return ""zz""; } public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); } } internal class Program { public static void Main() { var s1 = $""X = { 1 } ""; FormattableString s2 = $""X = { 1 } ""; } } }"; var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var compilation = CompileAndVerify(comp, verify: Verification.Fails); compilation.VerifyIL("System.Program.Main", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldstr ""X = {0} "" IL_0005: ldc.i4.1 IL_0006: call ""System.Bozo string.Format(string, int)"" IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)"" IL_0010: pop IL_0011: ldstr ""X = {0} "" IL_0016: ldc.i4.1 IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)"" IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)"" IL_0021: pop IL_0022: ret }"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax01() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):\}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40), // (6,40): error CS1009: Unrecognized escape sequence // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40) ); } [WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")] [Fact] public void Syntax02() { var text = @"using S = System; class C { void M() { var x = $""{ (S: } }"; // the precise diagnostics do not matter, as long as it is an error and not a crash. Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax03() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):}}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // var x = $"{ Math.Abs(value: 1):}}"; Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18) ); } [WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")] [Fact] public void NoUnexpandedForm() { string source = @"using System; class Program { public static void Main(string[] args) { string[] arr1 = new string[] { ""xyzzy"" }; object[] arr2 = arr1; Console.WriteLine($""-{null}-""); Console.WriteLine($""-{arr1}-""); Console.WriteLine($""-{arr2}-""); } }"; CompileAndVerify(source + formattableString, expectedOutput: @"-- -System.String[]- -System.String[]-"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Dynamic01() { var text = @"class C { const dynamic a = a; string s = $""{0,a}""; }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition // const dynamic a = a; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19), // (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null. // const dynamic a = a; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23), // (4,21): error CS0150: A constant value is expected // string s = $"{0,a}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21) ); } [WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")] [Fact] public void Syntax04() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<string>> e = () => $""\u1{0:\u2}""; Console.WriteLine(e); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,46): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46), // (8,52): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52) ); } [Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")] public void MissingConversionFromFormattableStringToIFormattable() { var text = @"namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) { return null; } } } namespace System { public abstract class FormattableString { } } static class C { static void Main() { System.IFormattable i = $""{""""}""; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics( // (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable' // System.IFormattable i = $"{""}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33) ); } [Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")] [InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")] [InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")] public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents) { var code = @" using System; Console.WriteLine(TwoComponents()); Console.WriteLine(ThreeComponents()); Console.WriteLine(FourComponents()); Console.WriteLine(FiveComponents()); string TwoComponents() { string s1 = ""1""; string s2 = ""2""; return " + twoComponents + @"; } string ThreeComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; return " + threeComponents + @"; } string FourComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; return " + fourComponents + @"; } string FiveComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; string s5 = ""5""; return " + fiveComponents + @"; } "; var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @" 12 123 1234 value:1 value:2 value:3 value:4 value:5 "); verifier.VerifyIL("Program.<<Main>$>g__TwoComponents|0_0()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (string V_0) //s2 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call ""string string.Concat(string, string)"" IL_0011: ret } "); verifier.VerifyIL("Program.<<Main>$>g__ThreeComponents|0_1()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (string V_0, //s2 string V_1) //s3 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldloc.0 IL_0012: ldloc.1 IL_0013: call ""string string.Concat(string, string, string)"" IL_0018: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FourComponents|0_2()", @" { // Code size 32 (0x20) .maxstack 4 .locals init (string V_0, //s2 string V_1, //s3 string V_2) //s4 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldstr ""4"" IL_0016: stloc.2 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""string string.Concat(string, string, string, string)"" IL_001f: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FiveComponents|0_3()", @" { // Code size 89 (0x59) .maxstack 3 .locals init (string V_0, //s1 string V_1, //s2 string V_2, //s3 string V_3, //s4 string V_4, //s5 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5) IL_0000: ldstr ""1"" IL_0005: stloc.0 IL_0006: ldstr ""2"" IL_000b: stloc.1 IL_000c: ldstr ""3"" IL_0011: stloc.2 IL_0012: ldstr ""4"" IL_0017: stloc.3 IL_0018: ldstr ""5"" IL_001d: stloc.s V_4 IL_001f: ldloca.s V_5 IL_0021: ldc.i4.0 IL_0022: ldc.i4.5 IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0030: ldloca.s V_5 IL_0032: ldloc.1 IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0038: ldloca.s V_5 IL_003a: ldloc.2 IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0040: ldloca.s V_5 IL_0042: ldloc.3 IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0048: ldloca.s V_5 IL_004a: ldloc.s V_4 IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0051: ldloca.s V_5 IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0058: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandler_OverloadsAndBoolReturns( bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @"int a = 1; System.Console.WriteLine(" + expression + @");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 80 (0x50) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldstr ""X"" IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.2 IL_0039: ldstr ""Y"" IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: ldloca.s V_1 IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0021: ldloca.s V_1 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 92 (0x5c) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_004d IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: brfalse.s IL_004d IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: brfalse.s IL_004d IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldstr ""X"" IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003b: brfalse.s IL_004d IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: br.s IL_004e IL_004d: ldc.i4.0 IL_004e: pop IL_004f: ldloca.s V_1 IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0056: call ""void System.Console.WriteLine(string)"" IL_005b: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_0051 IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0023: brfalse.s IL_0051 IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: brfalse.s IL_0051 IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldc.i4.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0047 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 88 (0x58) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004b IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: ldc.i4.0 IL_0033: ldstr ""X"" IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: ldloca.s V_1 IL_004d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0052: call ""void System.Console.WriteLine(string)"" IL_0057: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0051 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0051 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: brfalse.s IL_0051 IL_0027: ldloca.s V_1 IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0030: brfalse.s IL_0051 IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 100 (0x64) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0055 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0055 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0027: brfalse.s IL_0055 IL_0029: ldloca.s V_1 IL_002b: ldloc.0 IL_002c: ldc.i4.1 IL_002d: ldnull IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0033: brfalse.s IL_0055 IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.0 IL_0039: ldstr ""X"" IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: brfalse.s IL_0055 IL_0045: ldloca.s V_1 IL_0047: ldloc.0 IL_0048: ldc.i4.2 IL_0049: ldstr ""Y"" IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0053: br.s IL_0056 IL_0055: ldc.i4.0 IL_0056: pop IL_0057: ldloca.s V_1 IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005e: call ""void System.Console.WriteLine(string)"" IL_0063: ret } ", }; } [Fact] public void UseOfSpanInInterpolationHole_CSharp9() { var source = @" using System; ReadOnlySpan<char> span = stackalloc char[1]; Console.WriteLine($""{span}"");"; var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // Console.WriteLine($"{span}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22) ); } [ConditionalTheory(typeof(MonoOrCoreClrOnly))] [CombinatorialData] public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @" using System; ReadOnlySpan<char> a = ""1""; System.Console.WriteLine(" + expression + ");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldstr ""X"" IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: ldstr ""Y"" IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002a: ldloca.s V_1 IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0034: ldloca.s V_1 IL_0036: ldloc.0 IL_0037: ldc.i4.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 101 (0x65) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_0056 IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002a: brfalse.s IL_0056 IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: brfalse.s IL_0056 IL_0037: ldloca.s V_1 IL_0039: ldloc.0 IL_003a: ldstr ""X"" IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0044: brfalse.s IL_0056 IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: pop IL_0058: ldloca.s V_1 IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_005a IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002c: brfalse.s IL_005a IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: brfalse.s IL_005a IL_003a: ldloca.s V_1 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0050 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005a IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005a IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002e: brfalse.s IL_005a IL_0030: ldloca.s V_1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0039: brfalse.s IL_005a IL_003b: ldloca.s V_1 IL_003d: ldloc.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 97 (0x61) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0054 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: ldc.i4.0 IL_0028: ldnull IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: ldloca.s V_1 IL_003a: ldloc.0 IL_003b: ldc.i4.0 IL_003c: ldstr ""X"" IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: ldloca.s V_1 IL_0056: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005b: call ""void System.Console.WriteLine(string)"" IL_0060: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 109 (0x6d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005e IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005e IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0030: brfalse.s IL_005e IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldc.i4.1 IL_0036: ldnull IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_003c: brfalse.s IL_005e IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: ldstr ""X"" IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: brfalse.s IL_005e IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: ldc.i4.2 IL_0052: ldstr ""Y"" IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_005c: br.s IL_005f IL_005e: ldc.i4.0 IL_005f: pop IL_0060: ldloca.s V_1 IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0067: call ""void System.Console.WriteLine(string)"" IL_006c: ret } ", }; } [Theory] [InlineData(@"$""base{Throw()}{a = 2}""")] [InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")] public void BoolReturns_ShortCircuit(string expression) { var source = @" using System; int a = 1; Console.Write(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception();"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false"); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base 1"); } [Theory] [CombinatorialData] public void BoolOutParameter_ShortCircuits(bool useBoolReturns, [CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression) { var source = @" using System; int a = 1; Console.WriteLine(a); Console.WriteLine(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception(); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 1"); } [Theory] [InlineData(@"$""base{await Hole()}""")] [InlineData(@"$""base"" + $""{await Hole()}""")] public void AwaitInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @" { // Code size 164 (0xa4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00a3 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base{0}"" IL_0067: ldloc.1 IL_0068: box ""int"" IL_006d: call ""string string.Format(string, object)"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0090 } catch System.Exception { IL_0079: stloc.3 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0088: ldloc.3 IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008e: leave.s IL_00a3 } IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a3: ret } " : @" { // Code size 174 (0xae) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00ad IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base"" IL_0067: ldstr ""{0}"" IL_006c: ldloc.1 IL_006d: box ""int"" IL_0072: call ""string string.Format(string, object)"" IL_0077: call ""string string.Concat(string, string)"" IL_007c: call ""void System.Console.WriteLine(string)"" IL_0081: leave.s IL_009a } catch System.Exception { IL_0083: stloc.3 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0092: ldloc.3 IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0098: leave.s IL_00ad } IL_009a: ldarg.0 IL_009b: ldc.i4.s -2 IL_009d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00a2: ldarg.0 IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00ad: ret }"); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = await Hole(); Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base value:1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 185 (0xb9) .maxstack 3 .locals init (int V_0, int V_1, //hole System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00b8 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldc.i4.4 IL_0063: ldc.i4.1 IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0069: stloc.3 IL_006a: ldloca.s V_3 IL_006c: ldstr ""base"" IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0076: ldloca.s V_3 IL_0078: ldloc.1 IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_007e: ldloca.s V_3 IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0085: call ""void System.Console.WriteLine(string)"" IL_008a: leave.s IL_00a5 } catch System.Exception { IL_008c: stloc.s V_4 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009c: ldloc.s V_4 IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a3: leave.s IL_00b8 } IL_00a5: ldarg.0 IL_00a6: ldc.i4.s -2 IL_00a8: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00ad: ldarg.0 IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b8: ret } "); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = 2; Test(await M(1), " + expression + @", await M(3)); void Test(int i1, string s, int i2) => Console.WriteLine(s); Task<int> M(int i) { Console.WriteLine(i); return Task.FromResult(1); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 3 base value:2"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 328 (0x148) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0050 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00dc IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: stfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0018: ldc.i4.1 IL_0019: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0023: stloc.2 IL_0024: ldloca.s V_2 IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002b: brtrue.s IL_006c IL_002d: ldarg.0 IL_002e: ldc.i4.0 IL_002f: dup IL_0030: stloc.0 IL_0031: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0036: ldarg.0 IL_0037: ldloc.2 IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003d: ldarg.0 IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0043: ldloca.s V_2 IL_0045: ldarg.0 IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004b: leave IL_0147 IL_0050: ldarg.0 IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0056: stloc.2 IL_0057: ldarg.0 IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0063: ldarg.0 IL_0064: ldc.i4.m1 IL_0065: dup IL_0066: stloc.0 IL_0067: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006c: ldarg.0 IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0079: ldarg.0 IL_007a: ldc.i4.4 IL_007b: ldc.i4.1 IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0081: stloc.3 IL_0082: ldloca.s V_3 IL_0084: ldstr ""base"" IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_008e: ldloca.s V_3 IL_0090: ldarg.0 IL_0091: ldfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_009b: ldloca.s V_3 IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00a2: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_00a7: ldc.i4.3 IL_00a8: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00b2: stloc.2 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00ba: brtrue.s IL_00f8 IL_00bc: ldarg.0 IL_00bd: ldc.i4.1 IL_00be: dup IL_00bf: stloc.0 IL_00c0: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldloc.2 IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00cc: ldarg.0 IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d2: ldloca.s V_2 IL_00d4: ldarg.0 IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_00da: leave.s IL_0147 IL_00dc: ldarg.0 IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e2: stloc.2 IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00ef: ldarg.0 IL_00f0: ldc.i4.m1 IL_00f1: dup IL_00f2: stloc.0 IL_00f3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00f8: ldloca.s V_2 IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ff: stloc.1 IL_0100: ldarg.0 IL_0101: ldfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0106: ldarg.0 IL_0107: ldfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_010c: ldloc.1 IL_010d: call ""void Program.<<Main>$>g__Test|0_0(int, string, int)"" IL_0112: ldarg.0 IL_0113: ldnull IL_0114: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_0119: leave.s IL_0134 } catch System.Exception { IL_011b: stloc.s V_4 IL_011d: ldarg.0 IL_011e: ldc.i4.s -2 IL_0120: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0125: ldarg.0 IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_012b: ldloc.s V_4 IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0132: leave.s IL_0147 } IL_0134: ldarg.0 IL_0135: ldc.i4.s -2 IL_0137: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0147: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void DynamicInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 3 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base"" IL_000c: ldstr ""{0}"" IL_0011: ldloc.0 IL_0012: call ""string string.Format(string, object)"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{hole}base""")] [InlineData(@"$""{hole}"" + $""base""")] public void DynamicInHoles_UsesFormat2(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"1base"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: ldstr ""base"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}base"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Fact] public void ImplicitConversionsInConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(object literalLength, object formattedCount) {} } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerAttribute }); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: box ""int"" IL_000c: newobj ""CustomHandler..ctor(object, object)"" IL_0011: pop IL_0012: ret } "); } [Fact] public void MissingCreate_01() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_02() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_03() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5) ); } [Theory] [InlineData(null)] [InlineData("public string ToStringAndClear(int literalLength) => throw null;")] [InlineData("public void ToStringAndClear() => throw null;")] [InlineData("public static string ToStringAndClear() => throw null;")] public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod) { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; " + toStringAndClearMethod + @" public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5) ); } [Fact] public void ObsoleteCreateMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { [System.Obsolete(""Constructor is obsolete"", error: true)] public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5) ); } [Fact] public void ObsoleteAppendLiteralMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; [System.Obsolete(""AppendLiteral is obsolete"", error: true)] public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7) ); } [Fact] public void ObsoleteAppendFormattedMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; [System.Obsolete(""AppendFormatted is obsolete"", error: true)] public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11) ); } private const string UnmanagedCallersOnlyIl = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } }"; [Fact] public void UnmanagedCallersOnlyAppendFormattedMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance void Dispose () cil managed { ldnull throw } .method public hidebysig virtual instance string ToString () cil managed { ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics( // (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7) ); } [Fact] public void UnmanagedCallersOnlyToStringMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance string ToStringAndClear () cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5) ); } [Theory] [InlineData(@"$""{i}{s}""")] [InlineData(@"$""{i}"" + $""{s}""")] public void UnsupportedArgumentType(string expression) { var source = @" unsafe { int* i = null; var s = new S(); _ = " + expression + @"; } ref struct S { }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (6,11): error CS0306: The type 'int*' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11), // (6,14): error CS0306: The type 'S' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length) ); } [Theory] [InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")] [InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")] public void TargetTypedInterpolationHoles(string expression) { var source = @" bool b = true; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2 value: value:"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 81 (0x51) .maxstack 3 .locals init (bool V_0, //b object V_1, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.0 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloc.0 IL_000c: brfalse.s IL_0017 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: stloc.1 IL_0015: br.s IL_0019 IL_0017: ldnull IL_0018: stloc.1 IL_0019: ldloca.s V_2 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0021: ldloca.s V_2 IL_0023: ldloc.0 IL_0024: brfalse.s IL_002e IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: br.s IL_002f IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0034: ldloca.s V_2 IL_0036: ldnull IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_003c: ldloca.s V_2 IL_003e: ldnull IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0044: ldloca.s V_2 IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Theory] [InlineData(@"$""{(null, default)}{new()}""")] [InlineData(@"$""{(null, default)}"" + $""{new()}""")] public void TargetTypedInterpolationHoles_Errors(string expression) { var source = @"System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object' // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29), // (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29), // (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length) ); } [Fact] public void RefTernary() { var source = @" bool b = true; int i = 1; System.Console.WriteLine($""{(!b ? ref i : ref i)}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); } [Fact] public void NestedInterpolatedStrings_01() { var source = @" int i = 1; System.Console.WriteLine($""{$""{i}""}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0013: ldloca.s V_1 IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret } "); } [Theory] [InlineData(@"$""{$""{i1}""}{$""{i2}""}""")] [InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")] public void NestedInterpolatedStrings_02(string expression) { var source = @" int i1 = 1; int i2 = 2; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 63 (0x3f) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldloca.s V_2 IL_0006: ldc.i4.0 IL_0007: ldc.i4.1 IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0015: ldloca.s V_2 IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001c: ldloca.s V_2 IL_001e: ldc.i4.0 IL_001f: ldc.i4.1 IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0025: ldloca.s V_2 IL_0027: ldloc.1 IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_002d: ldloca.s V_2 IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0034: call ""string string.Concat(string, string)"" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: ret } "); } [Fact] public void ExceptionFilter_01() { var source = @" using System; int i = 1; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = i }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{i}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public int Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 .try { IL_0002: ldstr ""Starting try"" IL_0007: call ""void System.Console.WriteLine(string)"" IL_000c: newobj ""MyException..ctor()"" IL_0011: dup IL_0012: ldloc.0 IL_0013: callvirt ""void MyException.Prop.set"" IL_0018: throw } filter { IL_0019: isinst ""MyException"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldc.i4.0 IL_0023: br.s IL_004f IL_0025: callvirt ""string object.ToString()"" IL_002a: ldloca.s V_1 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0033: ldloca.s V_1 IL_0035: ldloc.0 IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_003b: ldloca.s V_1 IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0042: callvirt ""string string.Trim()"" IL_0047: call ""bool string.op_Equality(string, string)"" IL_004c: ldc.i4.0 IL_004d: cgt.un IL_004f: endfilter } // end filter { // handler IL_0051: pop IL_0052: ldstr ""Caught"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: leave.s IL_005e } IL_005e: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ExceptionFilter_02() { var source = @" using System; ReadOnlySpan<char> s = new char[] { 'i' }; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = s.ToString() }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{s}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public string Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: newarr ""char"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 105 IL_000a: stelem.i2 IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])"" IL_0010: stloc.0 .try { IL_0011: ldstr ""Starting try"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: newobj ""MyException..ctor()"" IL_0020: dup IL_0021: ldloca.s V_0 IL_0023: constrained. ""System.ReadOnlySpan<char>"" IL_0029: callvirt ""string object.ToString()"" IL_002e: callvirt ""void MyException.Prop.set"" IL_0033: throw } filter { IL_0034: isinst ""MyException"" IL_0039: dup IL_003a: brtrue.s IL_0040 IL_003c: pop IL_003d: ldc.i4.0 IL_003e: br.s IL_006a IL_0040: callvirt ""string object.ToString()"" IL_0045: ldloca.s V_1 IL_0047: ldc.i4.0 IL_0048: ldc.i4.1 IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0056: ldloca.s V_1 IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005d: callvirt ""string string.Trim()"" IL_0062: call ""bool string.op_Equality(string, string)"" IL_0067: ldc.i4.0 IL_0068: cgt.un IL_006a: endfilter } // end filter { // handler IL_006c: pop IL_006d: ldstr ""Caught"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0079 } IL_0079: ret } "); } [ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] [InlineData(@"$""{s}{c}""")] [InlineData(@"$""{s}"" + $""{c}""")] public void ImplicitUserDefinedConversionInHole(string expression) { var source = @" using System; S s = default; C c = new C(); Console.WriteLine(" + expression + @"); ref struct S { public static implicit operator ReadOnlySpan<char>(S s) => ""S converted""; } class C { public static implicit operator ReadOnlySpan<char>(C s) => ""C converted""; }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:S converted value:C"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, //s C V_1, //c System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: newobj ""C..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.0 IL_0011: ldc.i4.2 IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0024: ldloca.s V_2 IL_0026: ldloc.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)"" IL_002c: ldloca.s V_2 IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ExplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; Console.WriteLine($""{s}""); ref struct S { public static explicit operator ReadOnlySpan<char>(S s) => ""S converted""; } "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,21): error CS0306: The type 'S' may not be used as a type argument // Console.WriteLine($"{s}"); Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ImplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static implicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var verifier = CompileAndVerify(source, expectedOutput: @" literal:Text value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 52 (0x34) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Text"" IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)"" IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.1 IL_001d: box ""int"" IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0027: ldloca.s V_0 IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } "); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ExplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static explicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct' // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void InvalidBuilderReturnType(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public int AppendLiteral(string s) => 0; public int AppendFormatted(object o) => 0; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21), // (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length) ); } [Fact] public void MissingAppendMethods() { var source = @" using System.Runtime.CompilerServices; CustomHandler c = $""Literal{1}""; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } } "; var comp = CreateCompilation(new[] { source, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,21): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 21), // (4,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Literal").WithArguments("?.()").WithLocation(4, 21), // (4,28): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{1}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 28), // (4,28): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("?.()").WithLocation(4, 28) ); } [Fact] public void MissingBoolType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @"CustomHandler c = $""Literal{1}"";"; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyDiagnostics( // (1,19): error CS0518: Predefined type 'System.Boolean' is not defined or imported // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""Literal{1}""").WithArguments("System.Boolean").WithLocation(1, 19) ); } [Fact] public void MissingVoidType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @" class C { public bool M() { CustomHandler c = $""Literal{1}""; return true; } } "; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Void); comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_01(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length) ); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_02(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(string s) { } public bool AppendFormatted(object o) => true; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length) ); } [Fact] public void MixedBuilderReturnTypes_03() { var source = @" using System; Console.WriteLine($""{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { _builder.AppendLine(""value:"" + o.ToString()); } } }"; CompileAndVerify(source, expectedOutput: "value:1"); } [Fact] public void MixedBuilderReturnTypes_04() { var source = @" using System; using System.Text; using System.Runtime.CompilerServices; Console.WriteLine((CustomHandler)$""l""); [InterpolatedStringHandler] public class CustomHandler { private readonly StringBuilder _builder; public CustomHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public override string ToString() => _builder.ToString(); public bool AppendFormatted(object o) => true; public void AppendLiteral(string s) { _builder.AppendLine(""literal:"" + s.ToString()); } } "; CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l"); } private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler") { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var descendentNodes = tree.GetRoot().DescendantNodes(); var interpolatedString = (ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>() .Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any()) .FirstOrDefault() ?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(interpolatedString); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.Exists); Assert.True(semanticInfo.ImplicitConversion.IsValid); Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler); Assert.Null(semanticInfo.ImplicitConversion.Method); if (interpolatedString is BinaryExpressionSyntax) { Assert.False(semanticInfo.ConstantValue.HasValue); AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString()); } // https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings. } private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput) => CompileAndVerify( compilation, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); [Theory] [CombinatorialData] public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns, [CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression) { var code = @" CustomHandler builder = " + expression + @"; System.Console.WriteLine(builder.ToString());"; var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns); var comp = CreateCompilation(new[] { code, builder }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:Literal value:1 alignment:2 format:f"); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (type, useBoolReturns) switch { (type: "struct", useBoolReturns: true) => @" { // Code size 67 (0x43) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""bool CustomHandler.AppendLiteral(string)"" IL_0015: brfalse.s IL_002c IL_0017: ldloca.s V_1 IL_0019: ldc.i4.1 IL_001a: box ""int"" IL_001f: ldc.i4.2 IL_0020: ldstr ""f"" IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: constrained. ""CustomHandler"" IL_0038: callvirt ""string object.ToString()"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } ", (type: "struct", useBoolReturns: false) => @" { // Code size 61 (0x3d) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(string)"" IL_0015: ldloca.s V_1 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldc.i4.2 IL_001e: ldstr ""f"" IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0028: ldloc.1 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""CustomHandler"" IL_0032: callvirt ""string object.ToString()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } ", (type: "class", useBoolReturns: true) => @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""Literal"" IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0013: brfalse.s IL_0029 IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: box ""int"" IL_001c: ldc.i4.2 IL_001d: ldstr ""f"" IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret } ", (type: "class", useBoolReturns: false) => @" { // Code size 47 (0x2f) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldstr ""Literal"" IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: box ""int"" IL_0019: ldc.i4.2 IL_001a: ldstr ""f"" IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret } ", _ => throw ExceptionUtilities.Unreachable }; } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void CustomHandlerMethodArgument(string expression) { var code = @" M(" + expression + @"); void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"($""{1,2:f}"" + $""Literal"")")] public void ExplicitHandlerCast_InCode(string expression) { var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); syntax = ((CastExpressionSyntax)syntax).Expression; Assert.Equal(expression, syntax.ToString()); semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); // https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: call ""void System.Console.WriteLine(object)"" IL_0029: ret } "); } [Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void HandlerConversionPreferredOverStringForNonConstant(string expression) { var code = @" CultureInfoNormalizer.Normalize(); C.M(" + expression + @"); class C { public static void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.7 IL_0006: ldc.i4.1 IL_0007: newobj ""CustomHandler..ctor(int, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldc.i4.2 IL_0015: ldstr ""f"" IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001f: brfalse.s IL_002e IL_0021: ldloc.0 IL_0022: ldstr ""Literal"" IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: pop IL_0030: ldloc.0 IL_0031: call ""void C.M(CustomHandler)"" IL_0036: ret } "); comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9); verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: ldstr ""Literal"" IL_001a: call ""string string.Concat(string, string)"" IL_001f: call ""void C.M(string)"" IL_0024: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}Literal"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: call ""void C.M(string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler b) { throw null; } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Literal"" IL_0005: call ""void C.M(string)"" IL_000a: ret } "); } [Theory] [InlineData(@"$""{1}{2}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type // [Attr($"{1}{2}")] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2) ); VerifyInterpolatedStringExpression(comp); var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); void validate(ModuleSymbol m) { var attr = m.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => throw null; public static void M(CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); comp.VerifyDiagnostics( // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)' // C.M($""); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_01(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_02(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_03(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'. // C.M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_01(string expression) { var code = @" C.M(" + expression + @", default(CustomHandler)); C.M(default(CustomHandler), " + expression + @"); class C { public static void M<T>(T t1, T t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M($"{1,2:f}Literal", default(CustomHandler)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3), // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_02(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), () => $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_03(string expression) { var code = @" using System; C.M(" + expression + @", default(CustomHandler)); class C { public static void M<T>(T t1, T t2) => Console.WriteLine(t1); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 51 (0x33) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ldnull IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)"" IL_0032: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_04(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2()); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_01(string expression) { var code = @" using System; Func<CustomHandler> f = () => " + expression + @"; Console.WriteLine(f()); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_02(string expression) { var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(() => " + expression + @"); class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } "; // Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string, // so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec). var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); // No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldstr ""{0,2:f}Literal"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldstr ""{0,2:f}"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ldstr ""Literal"" IL_0015: call ""string string.Concat(string, string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_03(string expression) { // Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct // when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to // fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>. var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => throw null; public static void M(Func<CustomHandler> f) => Console.WriteLine(f()); } public partial class CustomHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } public ref struct S { public string Field { get; set; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 35 (0x23) .maxstack 4 .locals init (S V_0) IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldloca.s V_0 IL_000a: initobj ""S"" IL_0010: ldloca.s V_0 IL_0012: ldstr ""Field"" IL_0017: call ""void S.Field.set"" IL_001c: ldloc.0 IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)"" IL_0022: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_04(string expression) { // Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type) var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } public partial class CustomHandler { public void AppendFormatted(S value) => throw null; } public ref struct S { public string Field { get; set; } } namespace System.Runtime.CompilerServices { public ref partial struct DefaultInterpolatedStringHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } } "; string[] source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false), GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11), // (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloca.s V_1 IL_000d: initobj ""S"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""Field"" IL_001a: call ""void S.Field.set"" IL_001f: ldloc.1 IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)"" IL_0025: ldloca.s V_0 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_05(string expression) { var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => throw null; public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_06(string expression) { // Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion // means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec) // and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type // has an identity conversion to the return type of Func<bool, string>, that is preferred. var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @" { // Code size 35 (0x23) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ret } " : @" { // Code size 45 (0x2d) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_07(string expression) { // Same as 5, but with an implicit conversion from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } public partial struct CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_08(string expression) { // Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)' // C.M(b => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void LambdaInference_AmbiguousInOlderLangVersions(string expression) { var code = @" using System; C.M(param => { param = " + expression + @"; }); static class C { public static void M(Action<string> f) => throw null; public static void M(Action<CustomHandler> f) => throw null; } "; var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); // This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04 // We should not be changing binding behavior based on LangVersion. comp.VerifyEmitDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)' // C.M(param => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_01(string expression) { var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06 var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 56 (0x38) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_0024 IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: br.s IL_0032 IL_0024: ldloca.s V_0 IL_0026: initobj ""CustomHandler"" IL_002c: ldloc.0 IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } " : @" { // Code size 66 (0x42) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_002e IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: br.s IL_003c IL_002e: ldloca.s V_0 IL_0030: initobj ""CustomHandler"" IL_0036: ldloc.0 IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_03(string expression) { // Same as 02, but with a target-type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_04(string expression) { // Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07 var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_05(string expression) { // Same 01, but with a conversion from string to CustomHandler and CustomHandler to string. var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another // var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_06(string expression) { // Same 05, but with a target type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0046: call ""void System.Console.WriteLine(string)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_01(string expression) { // Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types // and not on expression conversions, no best type can be found for this switch expression. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string. var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 59 (0x3b) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_0034 IL_0023: ldstr ""{0,2:f}Literal"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } " : @" { // Code size 69 (0x45) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_003e IL_0023: ldstr ""{0,2:f}"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: ldstr ""Literal"" IL_0038: call ""string string.Concat(string, string)"" IL_003d: stloc.0 IL_003e: ldloc.0 IL_003f: call ""void System.Console.WriteLine(string)"" IL_0044: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_03(string expression) { // Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile). var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_04(string expression) { // Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: box ""CustomHandler"" IL_0049: call ""void System.Console.WriteLine(object)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_05(string expression) { // Same as 01, but with conversions in both directions. No best common type can be found. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_06(string expression) { // Same as 05, but with a target type. var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_01(string expression) { var code = @" M(" + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(ref CustomHandler)"" IL_002f: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_02(string expression) { var code = @" M(" + expression + @"); M(ref " + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword // M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3), // (3,7): error CS1510: A ref or out value must be an assignable variable // M(ref $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_03(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 5 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_04(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002f: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void RefOverloadResolution_MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => System.Console.WriteLine(c); public static void M(ref CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); VerifyInterpolatedStringExpression(comp, "CustomHandler1"); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler1 V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler1..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler1.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler1)"" IL_002e: ret } "); } private const string InterpolatedStringHandlerAttributesVB = @" Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerAttribute Inherits Attribute End Class <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute Inherits Attribute Public Sub New(argument As String) Arguments = { argument } End Sub Public Sub New(ParamArray arguments() as String) Me.Arguments = arguments End Sub Public ReadOnly Property Arguments As String() End Class End Namespace "; [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (8,27): error CS8946: 'string' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27) ); var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String) End Sub End Class "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); // Note: there is no compilation error here because the natural type of a string is still string, and // we just bind to that method without checking the handler attribute. var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string' // public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70) ); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'. // public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34), // (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; _ = new C(" + expression + @"); class C { public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11), // (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression) { var code = @" using System.Runtime.CompilerServices; C<CustomHandler>.M(" + expression + @"); public class C<T> { public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20), // (8,27): error CS8946: 'T' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27) ); var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C"); var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler"); var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler))); var cParam = substitutedC.GetMethod("M").Parameters.Single(); Assert.IsType<SubstitutedParameterSymbol>(cParam); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C(Of T) Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var goodCode = @" int i = 10; C.M(i: i, c: " + expression + @"); "; var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @" i:10 literal:text "); verifier.VerifyDiagnostics( // (6,27): warning CS8947: Parameter 'i' occurs after 'c' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to // reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "c").WithLocation(6, 27) ); verifyIL(verifier); var badCode = @"C.M(" + expression + @", 1);"; comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'. // C.M($"", 1); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length), // (6,27): warning CS8947: Parameter 'i' occurs after 'c' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to // reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "c").WithLocation(6, 27) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } void verifyIL(CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 36 (0x24) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldloca.s V_2 IL_0007: ldc.i4.4 IL_0008: ldc.i4.0 IL_0009: ldloc.0 IL_000a: call ""CustomHandler..ctor(int, int, int)"" IL_000f: ldloca.s V_2 IL_0011: ldstr ""text"" IL_0016: call ""bool CustomHandler.AppendLiteral(string)"" IL_001b: pop IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call ""void C.M(CustomHandler, int)"" IL_0023: ret } " : @" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldc.i4.4 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_3 IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000f: stloc.2 IL_0010: ldloc.3 IL_0011: brfalse.s IL_0021 IL_0013: ldloca.s V_2 IL_0015: ldstr ""text"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.2 IL_0024: ldloc.1 IL_0025: call ""void C.M(CustomHandler, int)"" IL_002a: ret } "); } } [Fact] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter 'i' occurs after 'c' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder // parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i = 0) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "c").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter 'i' occurs after 'c' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder // parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "c").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { private CustomHandler(int literalLength, int formattedCount, int i) : this() {} static void InCustomHandler() { C.M(1, " + expression + @"); } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() }); comp.VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8) ); comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics) { var code = @" using System.Runtime.CompilerServices; int i = 0; C.M(" + mRef + @" i, " + expression + @"); public class C { public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression, // (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6)); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this() { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var expectedDiagnostics = extraConstructorArg == "" ? new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5) } : new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)' // C.M(1, $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8) }; var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { comp = CreateCompilation(executableCode, new[] { d }); comp.VerifyDiagnostics(expectedDiagnostics); } static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString(); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" using System; int i = 10; Console.WriteLine(C.M(i, " + expression + @")); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 39 (0x27) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.1 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""CustomHandler..ctor(int, int, int)"" IL_000e: ldloca.s V_1 IL_0010: ldstr ""2"" IL_0015: call ""bool CustomHandler.AppendLiteral(string)"" IL_001a: pop IL_001b: ldloc.1 IL_001c: call ""string C.M(int, CustomHandler)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } " : @" { // Code size 46 (0x2e) .maxstack 5 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: ldloc.0 IL_0007: ldloca.s V_2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0020 IL_0012: ldloca.s V_1 IL_0014: ldstr ""2"" IL_0019: call ""bool CustomHandler.AppendLiteral(string)"" IL_001e: br.s IL_0021 IL_0020: ldc.i4.0 IL_0021: pop IL_0022: ldloc.1 IL_0023: call ""string C.M(int, CustomHandler)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" int i = 10; string s = ""arg""; C.M(i, s, " + expression + @"); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); string expectedOutput = @" i:10 s:arg literal:literal "; var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol verifier) { var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 44 (0x2c) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldloca.s V_3 IL_000f: ldc.i4.7 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloc.2 IL_0013: call ""CustomHandler..ctor(int, int, int, string)"" IL_0018: ldloca.s V_3 IL_001a: ldstr ""literal"" IL_001f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0024: pop IL_0025: ldloc.3 IL_0026: call ""void C.M(int, string, CustomHandler)"" IL_002b: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldc.i4.7 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: ldloc.2 IL_0011: ldloca.s V_4 IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_0018: stloc.3 IL_0019: ldloc.s V_4 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_3 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.3 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; string s = null; object o; C.M(i, ref s, out o, " + expression + @"); Console.WriteLine(s); Console.WriteLine(o); public class C { public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c) { Console.WriteLine(s); o = ""o in M""; s = ""s in M""; Console.Write(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount) { o = null; s = ""s in constructor""; _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" s in constructor i:1 literal:literal s in M o in M "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 67 (0x43) .maxstack 8 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)"" IL_0020: stloc.s V_6 IL_0022: ldloca.s V_6 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: pop IL_002f: ldloc.s V_6 IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_0036: ldloc.1 IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldloc.2 IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: ret } " : @" { // Code size 76 (0x4c) .maxstack 9 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6, bool V_7) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: ldloca.s V_7 IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)"" IL_0022: stloc.s V_6 IL_0024: ldloc.s V_7 IL_0026: brfalse.s IL_0036 IL_0028: ldloca.s V_6 IL_002a: ldstr ""literal"" IL_002f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0034: br.s IL_0037 IL_0036: ldc.i4.0 IL_0037: pop IL_0038: ldloc.s V_6 IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_003f: ldloc.1 IL_0040: call ""void System.Console.WriteLine(string)"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), GetString(), " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt GetString s:str i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 45 (0x2d) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: call ""CustomHandler..ctor(int, int, string, int)"" IL_0019: ldloca.s V_2 IL_001b: ldstr ""literal"" IL_0020: call ""bool CustomHandler.AppendLiteral(string)"" IL_0025: pop IL_0026: ldloc.2 IL_0027: call ""void C.M(int, string, CustomHandler)"" IL_002c: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_3 IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)"" IL_0019: stloc.2 IL_001a: ldloc.3 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_2 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.2 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetC().M(s: GetString(), i: GetInt(), c: " + expression + @"); C GetC() { Console.WriteLine(""GetC""); return new C { Field = 5 }; } int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public int Field; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""c.Field:"" + c.Field.ToString()); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetC GetString GetInt s:str c.Field:5 i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 56 (0x38) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldloca.s V_4 IL_0019: ldc.i4.7 IL_001a: ldc.i4.0 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldloc.2 IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)"" IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""bool CustomHandler.AppendLiteral(string)"" IL_002f: pop IL_0030: ldloc.s V_4 IL_0032: callvirt ""void C.M(int, string, CustomHandler)"" IL_0037: ret } " : @" { // Code size 65 (0x41) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4, bool V_5) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldc.i4.7 IL_0018: ldc.i4.0 IL_0019: ldloc.0 IL_001a: ldloc.1 IL_001b: ldloc.2 IL_001c: ldloca.s V_5 IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)"" IL_0023: stloc.s V_4 IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0037 IL_0029: ldloca.s V_4 IL_002b: ldstr ""literal"" IL_0030: call ""bool CustomHandler.AppendLiteral(string)"" IL_0035: br.s IL_0038 IL_0037: ldc.i4.0 IL_0038: pop IL_0039: ldloc.s V_4 IL_003b: callvirt ""void C.M(int, string, CustomHandler)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), """", " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""i2:"" + i2.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt i1:10 i2:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 43 (0x2b) .maxstack 7 .locals init (int V_0, CustomHandler V_1) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: call ""CustomHandler..ctor(int, int, int, int)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: call ""void C.M(int, string, CustomHandler)"" IL_002a: ret } " : @" { // Code size 50 (0x32) .maxstack 7 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldc.i4.7 IL_000d: ldc.i4.0 IL_000e: ldloc.0 IL_000f: ldloc.0 IL_0010: ldloca.s V_2 IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: brfalse.s IL_0029 IL_001b: ldloca.s V_1 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.1 IL_002c: call ""void C.M(int, string, CustomHandler)"" IL_0031: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, """", " + expression + @"); public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: newobj ""CustomHandler..ctor(int, int)"" IL_000d: call ""void C.M(int, string, CustomHandler)"" IL_0012: ret } " : @" { // Code size 21 (0x15) .maxstack 5 .locals init (bool V_0) IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)"" IL_000f: call ""void C.M(int, string, CustomHandler)"" IL_0014: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { } } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics( (extraConstructorArg == "") ? new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12), // (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12) } : new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12), // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12) } ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); Console.WriteLine(c[10, ""str"", " + expression + @"]); public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: callvirt ""string C.this[int, string, CustomHandler].get"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""string C.this[int, string, CustomHandler].get"" IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); c[10, ""str"", " + expression + @"] = """"; public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: ldstr """" IL_002e: callvirt ""void C.this[int, string, CustomHandler].set"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: ldstr """" IL_0035: callvirt ""void C.this[int, string, CustomHandler].set"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; (new C(5)).M((int)10, ""str"", " + expression + @"); public class C { public int Prop { get; } public C(int i) => Prop = i; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""c.Prop:"" + c.Prop.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 c.Prop:5 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 51 (0x33) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_3 IL_0015: ldc.i4.7 IL_0016: ldc.i4.0 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)"" IL_001f: ldloca.s V_3 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: pop IL_002c: ldloc.3 IL_002d: callvirt ""void C.M(int, string, CustomHandler)"" IL_0032: ret } " : @" { // Code size 59 (0x3b) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: ldloc.1 IL_0017: ldloc.2 IL_0018: ldloca.s V_4 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)"" IL_001f: stloc.3 IL_0020: ldloc.s V_4 IL_0022: brfalse.s IL_0032 IL_0024: ldloca.s V_3 IL_0026: ldstr ""literal"" IL_002b: call ""bool CustomHandler.AppendLiteral(string)"" IL_0030: br.s IL_0033 IL_0032: ldc.i4.0 IL_0033: pop IL_0034: ldloc.3 IL_0035: callvirt ""void C.M(int, string, CustomHandler)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(5, " + expression + @"); public class C { public int Prop { get; } public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" i:5 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 34 (0x22) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldloca.s V_1 IL_0005: ldc.i4.7 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: call ""CustomHandler..ctor(int, int, int)"" IL_000d: ldloca.s V_1 IL_000f: ldstr ""literal"" IL_0014: call ""bool CustomHandler.AppendLiteral(string)"" IL_0019: pop IL_001a: ldloc.1 IL_001b: newobj ""C..ctor(int, CustomHandler)"" IL_0020: pop IL_0021: ret } "); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_RefParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression, [CombinatorialValues("class", "struct")] string receiverType) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public " + receiverType + @" C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(extraConstructorArg != "" ? new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, ref C, out bool)' // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, ref C, out bool)").WithLocation(6, 15), // (6,15): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(6, 15) } : new[] { // (6,15): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(6, 15) }); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC().M(" + expression + @"); " + refness + @" C GetC() => throw null; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC().M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10) ); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); ref C GetC(ref C c) => ref c; public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { _builder.Append(c.I); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var verifier = CompileAndVerify( new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: "1literal:literal", symbolValidator: validator, sourceSymbolValidator: validator, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); verifier.VerifyIL("<top-level-statements-entry-point>", refness == "in" ? @" { // Code size 46 (0x2e) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, in C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: callvirt ""void C.M(CustomHandler)"" IL_002d: ret } " : @" { // Code size 48 (0x30) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldloca.s V_2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.1 IL_0016: ldind.ref IL_0017: call ""CustomHandler..ctor(int, int, C)"" IL_001c: ldloca.s V_2 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: pop IL_0029: ldloc.2 IL_002a: callvirt ""void C.M(CustomHandler)"" IL_002f: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory, CombinatorialData] [WorkItem(56624, "https://github.com/dotnet/roslyn/issues/56624")] public void RefOrOutParameter_AsReceiver([CombinatorialValues("ref", "out")] string parameterRefness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = default; localFunc(" + parameterRefness + @" c); void localFunc(" + parameterRefness + @" C c) { c = new C(1); c.M(" + expression + @"); } public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.Append(c.I); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: "1literal:literal", symbolValidator: validator, sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); verifier.VerifyIL($"Program.<<Main>$>g__localFunc|0_0({parameterRefness} C)", @" { // Code size 43 (0x2b) .maxstack 5 .locals init (C& V_0, CustomHandler V_1) IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int)"" IL_0007: stind.ref IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldind.ref IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldind.ref IL_0012: call ""CustomHandler..ctor(int, int, C)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: callvirt ""void C.M(CustomHandler)"" IL_002a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Rvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(s2, " + expression + @"); public struct S { public int I; public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" s1.I:1 s2.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 6 .locals init (S V_0, //s2 S V_1, S V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: ldloca.s V_1 IL_0013: initobj ""S"" IL_0019: ldloca.s V_1 IL_001b: ldc.i4.2 IL_001c: stfld ""int S.I"" IL_0021: ldloc.1 IL_0022: stloc.0 IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldloc.1 IL_002c: ldloc.2 IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)"" IL_0032: call ""void S.M(S, CustomHandler)"" IL_0037: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Lvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(ref s2, " + expression + @"); public struct S { public int I; public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword // s1.M(ref s2, $""); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByVal(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(s, " + expression + @"); public struct S { public int I; public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.0 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: newobj ""CustomHandler..ctor(int, int, S)"" IL_001b: call ""void S.M(S, CustomHandler)"" IL_0020: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByRef(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(ref s, " + expression + @"); public struct S { public int I; public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 36 (0x24) .maxstack 4 .locals init (S V_0, //s S V_1, S& V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldc.i4.0 IL_0017: ldc.i4.0 IL_0018: ldloc.2 IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)"" IL_001e: call ""void S.M(ref S, CustomHandler)"" IL_0023: ret } "); } [Theory] [CombinatorialData] public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetReceiver().M( GetArg(""Unrelated parameter 1""), GetArg(""Second value""), GetArg(""Unrelated parameter 2""), GetArg(""First value""), " + expression + @", GetArg(""Unrelated parameter 4"")); C GetReceiver() { Console.WriteLine(""GetReceiver""); return new C() { Prop = ""Prop"" }; } string GetArg(string s) { Console.WriteLine(s); return s; } public class C { public string Prop { get; set; } public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""s1:"" + s1); _builder.AppendLine(""c.Prop:"" + c.Prop); _builder.AppendLine(""s2:"" + s2); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @" GetReceiver Unrelated parameter 1 Second value Unrelated parameter 2 First value Handler constructor Unrelated parameter 4 s1:First value c.Prop:Prop s2:Second value literal:literal "); verifier.VerifyDiagnostics(); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$""literal"" + $""""")] public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression) { var code = @" using System; using System.Globalization; using System.Runtime.CompilerServices; int i = 1; C.M(i, " + expression + @"); public class C { public static implicit operator C(int i) => throw null; public static implicit operator C(double d) { Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture)); return new C(); } public override string ToString() => ""C""; public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" 1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 39 (0x27) .maxstack 5 .locals init (double V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: conv.r8 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.7 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""C C.op_Implicit(double)"" IL_000e: call ""CustomHandler..ctor(int, int, C)"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""literal"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: pop IL_0020: ldloc.1 IL_0021: call ""void C.M(double, CustomHandler)"" IL_0026: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { public int Prop { get; set; } public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); return 0; } set { Console.WriteLine(""Indexer setter""); Console.WriteLine(c.ToString()); } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter GetInt2 Indexer setter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 85 (0x55) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.s V_5 IL_0039: stloc.s V_4 IL_003b: ldloc.2 IL_003c: ldloc.3 IL_003d: ldloc.s V_4 IL_003f: ldloc.2 IL_0040: ldloc.3 IL_0041: ldloc.s V_4 IL_0043: callvirt ""int C.this[int, CustomHandler].get"" IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: callvirt ""void C.this[int, CustomHandler].set"" IL_0054: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 95 (0x5f) .maxstack 6 .locals init (int V_0, //i CustomHandler V_1, bool V_2, int V_3, C V_4, int V_5, CustomHandler V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.s V_4 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.3 IL_0010: ldloc.3 IL_0011: stloc.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.3 IL_0016: ldloc.s V_4 IL_0018: ldloca.s V_2 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001f: stloc.1 IL_0020: ldloc.2 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_1 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.1 IL_003f: stloc.s V_6 IL_0041: ldloc.s V_4 IL_0043: ldloc.s V_5 IL_0045: ldloc.s V_6 IL_0047: ldloc.s V_4 IL_0049: ldloc.s V_5 IL_004b: ldloc.s V_6 IL_004d: callvirt ""int C.this[int, CustomHandler].get"" IL_0052: ldc.i4.2 IL_0053: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0058: add IL_0059: callvirt ""void C.this[int, CustomHandler].set"" IL_005e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 91 (0x5b) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_5 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.s V_5 IL_003f: stloc.s V_4 IL_0041: ldloc.2 IL_0042: ldloc.3 IL_0043: ldloc.s V_4 IL_0045: ldloc.2 IL_0046: ldloc.3 IL_0047: ldloc.s V_4 IL_0049: callvirt ""int C.this[int, CustomHandler].get"" IL_004e: ldc.i4.2 IL_004f: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0054: add IL_0055: callvirt ""void C.this[int, CustomHandler].set"" IL_005a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 97 (0x61) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0041 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: brfalse.s IL_0041 IL_0030: ldloca.s V_5 IL_0032: ldloc.0 IL_0033: box ""int"" IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003f: br.s IL_0042 IL_0041: ldc.i4.0 IL_0042: pop IL_0043: ldloc.s V_5 IL_0045: stloc.s V_4 IL_0047: ldloc.2 IL_0048: ldloc.3 IL_0049: ldloc.s V_4 IL_004b: ldloc.2 IL_004c: ldloc.3 IL_004d: ldloc.s V_4 IL_004f: callvirt ""int C.this[int, CustomHandler].get"" IL_0054: ldc.i4.2 IL_0055: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_005a: add IL_005b: callvirt ""void C.this[int, CustomHandler].set"" IL_0060: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); Console.WriteLine(c.ToString()); return ref field; } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.this[int, CustomHandler].get"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 81 (0x51) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: stloc.3 IL_0012: ldc.i4.7 IL_0013: ldc.i4.1 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: ldloca.s V_5 IL_0018: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001d: stloc.s V_4 IL_001f: ldloc.s V_5 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_4 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.3 IL_003f: ldloc.s V_4 IL_0041: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0046: dup IL_0047: ldind.i4 IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: stind.i4 IL_0050: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC().M(GetInt(1), " + expression + @") += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c) { Console.WriteLine(""M""); Console.WriteLine(c.ToString()); return ref field; } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor M arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.M(int, CustomHandler)"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 81 (0x51) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: stloc.3 IL_0012: ldc.i4.7 IL_0013: ldc.i4.1 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: ldloca.s V_5 IL_0018: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001d: stloc.s V_4 IL_001f: ldloc.s V_5 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_4 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.3 IL_003f: ldloc.s V_4 IL_0041: callvirt ""ref int C.M(int, CustomHandler)"" IL_0046: dup IL_0047: ldind.i4 IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: stind.i4 IL_0050: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.M(int, CustomHandler)"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.M(int, CustomHandler)"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression) { var code = @" using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; _ = new C(1) { " + expression + @" }; public class C : IEnumerable<int> { public int Field; public C(int i) { Field = i; } public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c) { Console.WriteLine(c.ToString()); } public IEnumerator<int> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => throw null; } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 5 .locals init (C V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_1 IL_000a: ldc.i4.7 IL_000b: ldc.i4.0 IL_000c: ldloc.0 IL_000d: call ""CustomHandler..ctor(int, int, C)"" IL_0012: ldloca.s V_1 IL_0014: ldstr ""literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: callvirt ""void C.Add(CustomHandler)"" IL_0024: ret } "); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_DictionaryInitializer(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(1) { [" + expression + @"] = 1 }; public class C { public int Field; public C(int i) { Field = i; } public int this[[InterpolatedStringHandlerArgument("""")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 40 (0x28) .maxstack 4 .locals init (C V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_2 IL_0009: ldc.i4.7 IL_000a: ldc.i4.0 IL_000b: ldloc.0 IL_000c: call ""CustomHandler..ctor(int, int, C)"" IL_0011: ldloca.s V_2 IL_0013: ldstr ""literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloc.2 IL_001e: stloc.1 IL_001f: ldloc.0 IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: callvirt ""void C.this[CustomHandler].set"" IL_0027: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler) { Console.WriteLine(handler.ToString()); } } public partial class CustomHandler { private int I = 0; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""int constructor""); I = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""CustomHandler constructor""); _builder.AppendLine(""c.I:"" + c.I.ToString()); " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c) { _builder.AppendLine(""CustomHandler AppendFormatted""); _builder.Append(c.ToString()); " + (useBoolReturns ? "return true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" int constructor CustomHandler constructor CustomHandler AppendFormatted c.I:1 literal:Inner string value:2 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 59 (0x3b) .maxstack 6 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: dup IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: ldc.i4.s 12 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0017: dup IL_0018: ldstr ""Inner string"" IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: box ""int"" IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: call ""void C.M(int, CustomHandler)"" IL_003a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 77 (0x4d) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_0046 IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0031 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0031: ldloc.s V_4 IL_0033: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0038: ldloc.1 IL_0039: ldc.i4.2 IL_003a: box ""int"" IL_003f: ldc.i4.0 IL_0040: ldnull IL_0041: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0046: ldloc.1 IL_0047: call ""void C.M(int, CustomHandler)"" IL_004c: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 68 (0x44) .maxstack 5 .locals init (int V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldc.i4.s 12 IL_0011: ldc.i4.0 IL_0012: ldloc.2 IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0018: dup IL_0019: ldstr ""Inner string"" IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_0029: brfalse.s IL_003b IL_002b: ldloc.1 IL_002c: ldc.i4.2 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.1 IL_003e: call ""void C.M(int, CustomHandler)"" IL_0043: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0033 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ldloc.s V_4 IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_003c: brfalse.s IL_004e IL_003e: ldloc.1 IL_003f: ldc.i4.2 IL_0040: box ""int"" IL_0045: ldc.i4.0 IL_0046: ldnull IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void DiscardsUsedAsParameters(string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(out _, " + expression + @"); public class C { public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) { i = 0; Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount) { i = 1; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 4 .locals init (int V_0, CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: ldstr ""literal"" IL_0013: call ""void CustomHandler.AppendLiteral(string)"" IL_0018: ldloc.1 IL_0019: call ""void C.M(out int, CustomHandler)"" IL_001e: ret } "); } [Fact] public void DiscardsUsedAsParameters_DefinedInVB() { var vb = @" Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler) Console.WriteLine(i) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer) i = 1 End Sub End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @"C.M(out _, $"""");"; var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() }); var verifier = CompileAndVerify(comp, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: call ""void C.M(out int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DisallowedInExpressionTrees(string expression) { var code = @" using System; using System.Linq.Expressions; Expression<Func<CustomHandler>> expr = () => " + expression + @"; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler }); comp.VerifyDiagnostics( // (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion. // Expression<Func<CustomHandler>> expr = () => $""; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46) ); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_01() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_02() { var code = @" using System.Linq.Expressions; Expression e = (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_03() { var code = @" using System; using System.Linq.Expressions; Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_04() { var code = @" using System; using System.Linq.Expressions; Expression e = Func<string, string> () => (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_05() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 167 (0xa7) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldstr ""literal"" IL_0073: ldtoken ""string"" IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0082: ldtoken ""string string.Concat(string, string)"" IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_008c: castclass ""System.Reflection.MethodInfo"" IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0096: ldc.i4.1 IL_0097: newarr ""System.Linq.Expressions.ParameterExpression"" IL_009c: dup IL_009d: ldc.i4.0 IL_009e: ldloc.0 IL_009f: stelem.ref IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a5: pop IL_00a6: ret } "); } [Theory] [CombinatorialData] public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @", " + expression + @"); public class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString()); } public partial class CustomHandler { private int i; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); this.i = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""c.i:"" + c.i.ToString()); " + (validityParameter ? "success = true;" : "") + @" } }"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", }; } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsFormattableString() { var code = @" M($""{1}"" + $""literal""); System.FormattableString s = $""{1}"" + $""literal""; void M(System.FormattableString s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.FormattableString' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.FormattableString").WithLocation(2, 3), // (3,30): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString' // System.FormattableString s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.FormattableString").WithLocation(3, 30) ); } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsIFormattable() { var code = @" M($""{1}"" + $""literal""); System.IFormattable s = $""{1}"" + $""literal""; void M(System.IFormattable s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.IFormattable' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.IFormattable").WithLocation(2, 3), // (3,25): error CS0029: Cannot implicitly convert type 'string' to 'System.IFormattable' // System.IFormattable s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.IFormattable").WithLocation(3, 25) ); } [Theory] [CombinatorialData] public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression) { var code = @" int i; string s; CustomHandler c = " + expression + @"; _ = i.ToString(); _ = o.ToString(); _ = s.ToString(); string M(out object o) { o = null; return null; } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (6,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5), // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else if (useBoolReturns) { comp.VerifyDiagnostics( // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression) { var code = @" int i; CustomHandler c = " + expression + @"; _ = i.ToString(); "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (5,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_01(string expression) { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_02(string expression) { var code = @" using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount) { Console.WriteLine(""d:"" + d.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "d:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: box ""int"" IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)"" IL_0010: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0015: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(dynamic literalLength, int formattedCount) { Console.WriteLine(""ctor""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: newobj ""CustomHandler..ctor(dynamic, int)"" IL_000c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0011: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { Console.WriteLine(""ctor""); } public CustomHandler(dynamic literalLength, int formattedCount) { throw null; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_000c: ret } "); } [Theory] [InlineData(@"$""Literal""")] [InlineData(@"$"""" + $""Literal""")] public void DynamicConstruction_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_0015: ldloc.0 IL_0016: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001b: ret } "); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""""")] public void DynamicConstruction_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 29 (0x1d) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)"" IL_0016: ldloc.0 IL_0017: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001c: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_08(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 128 (0x80) .maxstack 9 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0021: brtrue.s IL_0062 IL_0023: ldc.i4 0x100 IL_0028: ldstr ""AppendFormatted"" IL_002d: ldnull IL_002e: ldtoken ""Program"" IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0038: ldc.i4.2 IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003e: dup IL_003f: ldc.i4.0 IL_0040: ldc.i4.s 9 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.0 IL_004c: ldnull IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0052: stelem.ref IL_0053: 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_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target"" IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0071: ldloca.s V_1 IL_0073: ldloc.0 IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_0079: ldloc.1 IL_007a: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_007f: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_09(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public bool AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); return true; } public bool AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); return true; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 196 (0xc4) .maxstack 11 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)"" IL_001c: brfalse IL_00bb IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0026: brtrue.s IL_004c IL_0028: ldc.i4.0 IL_0029: ldtoken ""bool"" IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0033: ldtoken ""Program"" IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_0060: brtrue.s IL_009d IL_0062: ldc.i4.0 IL_0063: ldstr ""AppendFormatted"" IL_0068: ldnull IL_0069: ldtoken ""Program"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.2 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.s 9 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: dup IL_0085: ldc.i4.1 IL_0086: ldc.i4.0 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.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00ac: ldloca.s V_1 IL_00ae: ldloc.0 IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00b9: br.s IL_00bc IL_00bb: ldc.i4.0 IL_00bc: pop IL_00bd: ldloc.1 IL_00be: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_00c3: ret } "); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_01(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // return $"{s}"; Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_02(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8150: By-value returns may only be used in methods that return by value // return $"{s}"; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return ref " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // return ref $"{s}"; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { S1 s1; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; } public void AppendFormatted(Span<char> s) => this.s1.s = s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s1, " + expression + @"); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9), // (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23) ); } [Theory] [InlineData(@"$""{s1}""")] [InlineData(@"$""{s1}"" + $""""")] public void RefEscape_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public void AppendFormatted(S1 s1) => s1.s = this.s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s, " + expression + @"); } public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_08() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public static CustomHandler M() { Span<char> s = stackalloc char[10]; ref CustomHandler c = ref M2(ref s, $""""); return c; } public static ref CustomHandler M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] ref CustomHandler handler) { return ref handler; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (16,16): error CS8352: Cannot use local 'c' in this context because it may expose referenced variables outside of their declaration scope // return c; Diagnostic(ErrorCode.ERR_EscapeLocal, "c").WithArguments("c").WithLocation(16, 16) ); } [Fact] public void RefEscape_09() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { s1.Handler = this; } public static void M(ref S1 s1) { Span<char> s2 = stackalloc char[10]; M2(ref s1, $""{s2}""); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler handler) { } public void AppendFormatted(Span<char> s) { this.s = s; } } public ref struct S1 { public CustomHandler Handler; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (15,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s2}"")").WithArguments("CustomHandler.M2(ref S1, CustomHandler)", "handler").WithLocation(15, 9), // (15,23): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(15, 23) ); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_01(string expression) { var code = @" int i = 1; System.Console.WriteLine(" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" { value:1 }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""{ "" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldstr "" }"" IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_002b: ldloca.s V_1 IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_02(string expression) { var code = @" int i = 1; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:{ value:1 alignment:0 format: literal: }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 71 (0x47) .maxstack 4 .locals init (int V_0, //i CustomHandler V_1, //c CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_2 IL_000d: ldstr ""{ "" IL_0012: call ""void CustomHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0026: ldloca.s V_2 IL_0028: ldstr "" }"" IL_002d: call ""void CustomHandler.AppendLiteral(string)"" IL_0032: ldloc.2 IL_0033: stloc.1 IL_0034: ldloca.s V_1 IL_0036: constrained. ""CustomHandler"" IL_003c: callvirt ""string object.ToString()"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ret } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 value:2 value:3 4 "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 66 (0x42) .maxstack 3 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 int V_3, //i4 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldc.i4.4 IL_0007: stloc.3 IL_0008: ldloca.s V_4 IL_000a: ldc.i4.0 IL_000b: ldc.i4.3 IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0011: ldloca.s V_4 IL_0013: ldloc.0 IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0019: ldloca.s V_4 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: ldloca.s V_4 IL_0023: ldloc.2 IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0029: ldloca.s V_4 IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0030: ldloca.s V_3 IL_0032: call ""string int.ToString()"" IL_0037: call ""string string.Concat(string, string)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""({i1}),"" + $""[{i2}],"" + $""{{{i3}}}""")] [InlineData(@"($""({i1}),"" + $""[{i2}],"") + $""{{{i3}}}""")] [InlineData(@"$""({i1}),"" + ($""[{i2}],"" + $""{{{i3}}}"")")] public void InterpolatedStringsAddedUnderObjectAddition2(string expression) { var code = $@" int i1 = 1; int i2 = 2; int i3 = 3; System.Console.WriteLine({expression});"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: @" ( value:1 ), [ value:2 ], { value:3 } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition3() { var code = @" #nullable enable using System; try { var s = string.Empty; Console.WriteLine($""{s = null}{s.Length}"" + $""""); } catch (NullReferenceException) { Console.WriteLine(""Null reference exception caught.""); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: "Null reference exception caught.").VerifyIL("<top-level-statements-entry-point>", @" { // Code size 65 (0x41) .maxstack 3 .locals init (string V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) .try { IL_0000: ldsfld ""string string.Empty"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: ldc.i4.2 IL_0008: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldnull IL_0011: dup IL_0012: stloc.0 IL_0013: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0018: ldloca.s V_1 IL_001a: ldloc.0 IL_001b: callvirt ""int string.Length.get"" IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: ldloca.s V_1 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: call ""void System.Console.WriteLine(string)"" IL_0031: leave.s IL_0040 } catch System.NullReferenceException { IL_0033: pop IL_0034: ldstr ""Null reference exception caught."" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: leave.s IL_0040 } IL_0040: ret } ").VerifyDiagnostics( // (9,36): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine($"{s = null}{s.Length}" + $""); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 36) ); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" object o1; object o2; object o3; _ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1; o1.ToString(); o2.ToString(); o3.ToString(); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); comp.VerifyDiagnostics( // (7,1): error CS0165: Use of unassigned local variable 'o2' // o2.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1), // (8,1): error CS0165: Use of unassigned local variable 'o3' // o3.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1) ); } [Theory] [InlineData(@"($""{i1}"" + $""{i2}"") + $""{i3}""")] [InlineData(@"$""{i1}"" + ($""{i2}"" + $""{i3}"")")] public void ParenthesizedAdditiveExpression_01(string expression) { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 82 (0x52) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 CustomHandler V_3, //c CustomHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldloca.s V_4 IL_0008: ldc.i4.0 IL_0009: ldc.i4.3 IL_000a: call ""CustomHandler..ctor(int, int)"" IL_000f: ldloca.s V_4 IL_0011: ldloc.0 IL_0012: box ""int"" IL_0017: ldc.i4.0 IL_0018: ldnull IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001e: ldloca.s V_4 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002d: ldloca.s V_4 IL_002f: ldloc.2 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldloc.s V_4 IL_003e: stloc.3 IL_003f: ldloca.s V_3 IL_0041: constrained. ""CustomHandler"" IL_0047: callvirt ""string object.ToString()"" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_02() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; CustomHandler c = /*<bind>*/((($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}""))) + (($""{i1}"" + ($""{i2}"" + $""{i3}"")) + (($""{i4}"" + $""{i5}"") + $""{i6}""))/*</bind>*/; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: value:4 alignment:0 format: value:5 alignment:0 format: value:6 alignment:0 format: value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: value:4 alignment:0 format: value:5 alignment:0 format: value:6 alignment:0 format: "); verifier.VerifyDiagnostics(); VerifyOperationTreeForTest<BinaryExpressionSyntax>(comp, @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '(($""{i1}"" + ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... ) + $""{i3}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + $""{i2}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + ( ... + $""{i6}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i5}"" + $""{i6}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... + $""{i6}"")') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + ( ... + $""{i3}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i2}"" + $""{i3}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i4}"" + ... ) + $""{i6}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + $""{i5}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null "); } [Fact] public void ParenthesizedAdditiveExpression_03() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = (($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}"")); System.Console.WriteLine(s);"; var verifier = CompileAndVerify(code, expectedOutput: @"123456"); verifier.VerifyDiagnostics(); } [Fact] public void ParenthesizedAdditiveExpression_04() { var code = @" using System.Threading.Tasks; int i1 = 2; int i2 = 3; string s = $""{await GetInt()}"" + ($""{i1}"" + $""{i2}""); System.Console.WriteLine(s); Task<int> GetInt() => Task.FromResult(1); "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }, expectedOutput: @" 1value:2 value:3"); verifier.VerifyDiagnostics(); // Note the two DefaultInterpolatedStringHandlers in the IL here. In a future rewrite step in the LocalRewriter, we can potentially // transform the tree to change its shape and pull out all individual Append calls in a sequence (regardless of the level of the tree) // and combine these and other unequal tree shapes. For now, we're going with a simple solution where, if the entire binary expression // cannot be combined, none of it is. verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 244 (0xf4) .maxstack 4 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldarg.0 IL_000b: ldc.i4.2 IL_000c: stfld ""int Program.<<Main>$>d__0.<i1>5__2"" IL_0011: ldarg.0 IL_0012: ldc.i4.3 IL_0013: stfld ""int Program.<<Main>$>d__0.<i2>5__3"" IL_0018: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__GetInt|0_0()"" IL_001d: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0022: stloc.2 IL_0023: ldloca.s V_2 IL_0025: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002a: brtrue.s IL_006b IL_002c: ldarg.0 IL_002d: ldc.i4.0 IL_002e: dup IL_002f: stloc.0 IL_0030: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0035: ldarg.0 IL_0036: ldloc.2 IL_0037: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003c: ldarg.0 IL_003d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0042: ldloca.s V_2 IL_0044: ldarg.0 IL_0045: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004a: leave IL_00f3 IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0055: stloc.2 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006b: ldloca.s V_2 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.1 IL_0073: ldstr ""{0}"" IL_0078: ldloc.1 IL_0079: box ""int"" IL_007e: call ""string string.Format(string, object)"" IL_0083: ldc.i4.0 IL_0084: ldc.i4.1 IL_0085: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_008a: stloc.3 IL_008b: ldloca.s V_3 IL_008d: ldarg.0 IL_008e: ldfld ""int Program.<<Main>$>d__0.<i1>5__2"" IL_0093: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0098: ldloca.s V_3 IL_009a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_009f: ldc.i4.0 IL_00a0: ldc.i4.1 IL_00a1: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_00a6: stloc.3 IL_00a7: ldloca.s V_3 IL_00a9: ldarg.0 IL_00aa: ldfld ""int Program.<<Main>$>d__0.<i2>5__3"" IL_00af: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_00b4: ldloca.s V_3 IL_00b6: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00bb: call ""string string.Concat(string, string, string)"" IL_00c0: call ""void System.Console.WriteLine(string)"" IL_00c5: leave.s IL_00e0 } catch System.Exception { IL_00c7: stloc.s V_4 IL_00c9: ldarg.0 IL_00ca: ldc.i4.s -2 IL_00cc: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00d1: ldarg.0 IL_00d2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d7: ldloc.s V_4 IL_00d9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00de: leave.s IL_00f3 } IL_00e0: ldarg.0 IL_00e1: ldc.i4.s -2 IL_00e3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00e8: ldarg.0 IL_00e9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00f3: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_05() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = /*<bind>*/((($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}""))) + (($""{i1}"" + ($""{i2}"" + $""{i3}"")) + (($""{i4}"" + $""{i5}"") + $""{i6}""))/*</bind>*/; System.Console.WriteLine(s);"; var comp = CreateCompilation(code); var verifier = CompileAndVerify(comp, expectedOutput: @"123456123456"); verifier.VerifyDiagnostics(); VerifyOperationTreeForTest<BinaryExpressionSyntax>(comp, @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '(($""{i1}"" + ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... ) + $""{i3}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + $""{i2}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + ( ... + $""{i6}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i5}"" + $""{i6}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... + $""{i6}"")') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + ( ... + $""{i3}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i2}"" + $""{i3}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i4}"" + ... ) + $""{i6}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + $""{i5}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_01(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) = (" + initializer + @"); System.Console.Write(c1.ToString()); System.Console.WriteLine(c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 91 (0x5b) .maxstack 4 .locals init (CustomHandler V_0, //c1 CustomHandler V_1, //c2 CustomHandler V_2, CustomHandler V_3) IL_0000: ldloca.s V_3 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_3 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.0 IL_0012: ldnull IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0018: ldloc.3 IL_0019: stloc.2 IL_001a: ldloca.s V_3 IL_001c: ldc.i4.0 IL_001d: ldc.i4.1 IL_001e: call ""CustomHandler..ctor(int, int)"" IL_0023: ldloca.s V_3 IL_0025: ldc.i4.2 IL_0026: box ""int"" IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0032: ldloc.3 IL_0033: ldloc.2 IL_0034: stloc.0 IL_0035: stloc.1 IL_0036: ldloca.s V_0 IL_0038: constrained. ""CustomHandler"" IL_003e: callvirt ""string object.ToString()"" IL_0043: call ""void System.Console.Write(string)"" IL_0048: ldloca.s V_1 IL_004a: constrained. ""CustomHandler"" IL_0050: callvirt ""string object.ToString()"" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ret } "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_02(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) t = (" + initializer + @"); System.Console.Write(t.c1.ToString()); System.Console.WriteLine(t.c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 104 (0x68) .maxstack 6 .locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldc.i4.1 IL_000e: box ""int"" IL_0013: ldc.i4.0 IL_0014: ldnull IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001a: ldloc.1 IL_001b: ldloca.s V_1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.1 IL_001f: call ""CustomHandler..ctor(int, int)"" IL_0024: ldloca.s V_1 IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0033: ldloc.1 IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)"" IL_0039: ldloca.s V_0 IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1"" IL_0040: constrained. ""CustomHandler"" IL_0046: callvirt ""string object.ToString()"" IL_004b: call ""void System.Console.Write(string)"" IL_0050: ldloca.s V_0 IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2"" IL_0057: constrained. ""CustomHandler"" IL_005d: callvirt ""string object.ToString()"" IL_0062: call ""void System.Console.WriteLine(string)"" IL_0067: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{h1}{h2}""")] [InlineData(@"$""{h1}"" + $""{h2}""")] public void RefStructHandler_DynamicInHole(string expression) { var code = @" dynamic h1 = 1; dynamic h2 = 2; CustomHandler c = " + expression + ";"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "ref struct", useBoolReturns: false); var comp = CreateCompilationWithCSharp(new[] { code, handler }); // Note: We don't give any errors when mixing dynamic and ref structs today. If that ever changes, we should get an // error here. This will crash at runtime because of this. comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Literal{1}""")] [InlineData(@"$""Literal"" + $""{1}""")] public void ConversionInParamsArguments(string expression) { var code = @" using System; using System.Linq; M(" + expression + ", " + expression + @"); void M(params CustomHandler[] handlers) { Console.WriteLine(string.Join(Environment.NewLine, handlers.Select(h => h.ToString()))); } "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, expectedOutput: @" literal:Literal value:1 alignment:0 format: literal:Literal value:1 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 100 (0x64) .maxstack 7 .locals init (CustomHandler V_0) IL_0000: ldc.i4.2 IL_0001: newarr ""CustomHandler"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: ldc.i4.7 IL_000b: ldc.i4.1 IL_000c: call ""CustomHandler..ctor(int, int)"" IL_0011: ldloca.s V_0 IL_0013: ldstr ""Literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloca.s V_0 IL_001f: ldc.i4.1 IL_0020: box ""int"" IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002c: ldloc.0 IL_002d: stelem ""CustomHandler"" IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldloca.s V_0 IL_0036: ldc.i4.7 IL_0037: ldc.i4.1 IL_0038: call ""CustomHandler..ctor(int, int)"" IL_003d: ldloca.s V_0 IL_003f: ldstr ""Literal"" IL_0044: call ""void CustomHandler.AppendLiteral(string)"" IL_0049: ldloca.s V_0 IL_004b: ldc.i4.1 IL_004c: box ""int"" IL_0051: ldc.i4.0 IL_0052: ldnull IL_0053: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0058: ldloc.0 IL_0059: stelem ""CustomHandler"" IL_005e: call ""void Program.<<Main>$>g__M|0_0(CustomHandler[])"" IL_0063: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_01(string mod) { var code = @" using System.Runtime.CompilerServices; M($""""); " + mod + @" void M([InterpolatedStringHandlerArgument("""")] CustomHandler c) { } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (6,10): error CS8944: 'M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // void M([InterpolatedStringHandlerArgument("")] CustomHandler c) { } Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M(CustomHandler)").WithLocation(6, 10 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; M(1, $""""); " + mod + @" void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_01(string mod) { var code = @" using System.Runtime.CompilerServices; var a = " + mod + @" ([InterpolatedStringHandlerArgument("""")] CustomHandler c) => { }; a($""""); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,12): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument("""")").WithLocation(4, 12 + mod.Length), // (4,12): error CS8944: 'lambda expression' is not an instance method, the receiver cannot be an interpolated string handler argument. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("lambda expression").WithLocation(4, 12 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; var a = " + mod + @" (int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); a(1, $""""); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) => throw null; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @""); verifier.VerifyDiagnostics( // (5,19): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = (int i, [InterpolatedStringHandlerArgument("i")] CustomHandler c) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument(""i"")").WithLocation(5, 19 + mod.Length) ); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 4 IL_0000: ldsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""System.Action<int, CustomHandler>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: newobj ""CustomHandler..ctor(int, int)"" IL_0027: callvirt ""void System.Action<int, CustomHandler>.Invoke(int, CustomHandler)"" IL_002c: ret } "); } [Fact] public void ArgumentsOnDelegateTypes_01() { var code = @" using System.Runtime.CompilerServices; M m = null; m($""""); delegate void M([InterpolatedStringHandlerArgument("""")] CustomHandler c); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(6, 3), // (8,18): error CS8944: 'M.Invoke(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // delegate void M([InterpolatedStringHandlerArgument("")] CustomHandler c); Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M.Invoke(CustomHandler)").WithLocation(8, 18) ); } [Fact] public void ArgumentsOnDelegateTypes_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Delegate Sub M(<InterpolatedStringHandlerArgument("""")> c As CustomHandler) <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @" M m = null; m($""""); "; var comp = CreateCompilation(code, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(4, 3) ); } [Fact] public void ArgumentsOnDelegateTypes_03() { var code = @" using System; using System.Runtime.CompilerServices; M m = (i, c) => Console.WriteLine(c.ToString()); m(1, $""""); delegate void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 5 .locals init (int V_0) IL_0000: ldsfld ""M Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""M..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""M Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: stloc.0 IL_0021: ldloc.0 IL_0022: ldc.i4.0 IL_0023: ldc.i4.0 IL_0024: ldloc.0 IL_0025: newobj ""CustomHandler..ctor(int, int, int)"" IL_002a: callvirt ""void M.Invoke(int, CustomHandler)"" IL_002f: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_01() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private int _i = 0; public CustomHandler(int literalLength, int formattedCount, int i = 1) => _i = i; public override string ToString() => _i.ToString(); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: ldc.i4.1 IL_0003: newobj ""CustomHandler..ctor(int, int, int)"" IL_0008: call ""void C.M(CustomHandler)"" IL_000d: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_02() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""Literal""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, out bool isValid, int i = 1) { _s = i.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (CustomHandler V_0, bool V_1) IL_0000: ldc.i4.7 IL_0001: ldc.i4.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.1 IL_0005: newobj ""CustomHandler..ctor(int, int, out bool, int)"" IL_000a: stloc.0 IL_000b: ldloc.1 IL_000c: brfalse.s IL_001a IL_000e: ldloca.s V_0 IL_0010: ldstr ""Literal"" IL_0015: call ""void CustomHandler.AppendLiteral(string)"" IL_001a: ldloc.0 IL_001b: call ""void C.M(CustomHandler)"" IL_0020: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_03() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, int i2 = 2) { _s = i1.ToString() + i2.ToString(); } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 5 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldc.i4.2 IL_0007: newobj ""CustomHandler..ctor(int, int, int, int)"" IL_000c: call ""void C.M(int, CustomHandler)"" IL_0011: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_04() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""Literal""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, out bool isValid, int i2 = 2) { _s = i1.ToString() + i2.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.7 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: ldc.i4.2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool, int)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_001e IL_0012: ldloca.s V_1 IL_0014: ldstr ""Literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: call ""void C.M(int, CustomHandler)"" IL_0024: ret } "); } [Fact] public void HandlerExtensionMethod_01() { var code = @" $""Test"".M(); public static class StringExt { public static void M(this CustomHandler handler) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (2,1): error CS1929: 'string' does not contain a definition for 'M' and the best extension method overload 'StringExt.M(CustomHandler)' requires a receiver of type 'CustomHandler' // $"Test".M(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$""Test""").WithArguments("string", "M", "StringExt.M(CustomHandler)", "CustomHandler").WithLocation(2, 1) ); } [Fact] public void HandlerExtensionMethod_02() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument("""")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // s.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(5, 5), // (14,38): error CS8944: 'S1Ext.M(S1, CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M(this S1 s, [InterpolatedStringHandlerArgument("")] CustomHandler c) => throw null; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("S1Ext.M(S1, CustomHandler)").WithLocation(14, 38) ); } [Fact] public void HandlerExtensionMethod_03() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1"); verifier.VerifyDiagnostics(); } [Fact] public void HandlerExtensionMethod_04() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(ref this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(s.Field); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S1 s) : this(literalLength, formattedCount) => s.Field = 2; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 25 (0x19) .maxstack 4 .locals init (S1 V_0, //s S1& V_1) IL_0000: ldloca.s V_0 IL_0002: call ""S1..ctor()"" IL_0007: ldloca.s V_0 IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: ldloc.1 IL_000e: newobj ""CustomHandler..ctor(int, int, ref S1)"" IL_0013: call ""void S1Ext.M(ref S1, CustomHandler)"" IL_0018: ret } "); } [Fact] public void HandlerExtensionMethod_05() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(in this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 25 (0x19) .maxstack 4 .locals init (S1 V_0, //s S1& V_1) IL_0000: ldloca.s V_0 IL_0002: call ""S1..ctor()"" IL_0007: ldloca.s V_0 IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: ldloc.1 IL_000e: newobj ""CustomHandler..ctor(int, int, in S1)"" IL_0013: call ""void S1Ext.M(in S1, CustomHandler)"" IL_0018: ret } "); } [Fact] public void HandlerExtensionMethod_06() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(in this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,1): error CS1620: Argument 3 must be passed with the 'ref' keyword // s.M($""); Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("3", "ref").WithLocation(5, 1) ); } [Fact] public void HandlerExtensionMethod_07() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(ref this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,1): error CS1615: Argument 3 may not be passed with the 'ref' keyword // s.M($""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("3", "ref").WithLocation(5, 1) ); } [Fact] public void NoStandaloneConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,19): error CS7036: There is no argument given that corresponds to the required formal parameter 's' of 'CustomHandler.CustomHandler(int, int, string)' // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("s", "CustomHandler.CustomHandler(int, int, string)").WithLocation(4, 19), // (4,19): error CS1615: Argument 3 may not be passed with the 'out' keyword // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(4, 19) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class InterpolationTests : CompilingTestBase { [Fact] public void TestSimpleInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number }.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 }.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 }.""); Console.WriteLine($""Jenny don\'t change your number { number :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}.""); Console.WriteLine($""{number}""); } }"; string expectedOutput = @"Jenny don't change your number 8675309. Jenny don't change your number 8675309 . Jenny don't change your number 8675309. Jenny don't change your number 867-5309. Jenny don't change your number 867-5309 . Jenny don't change your number 867-5309. 8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestOnlyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}""); } }"; string expectedOutput = @"8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}{number}""); } }"; string expectedOutput = @"86753098675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}.""); } }"; string expectedOutput = @"Jenny don't change your number 867-5309 867-5309."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestEmptyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }.""); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,73): error CS1733: Expected expression // Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }."); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73) ); } [Fact] public void TestHalfOpenInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,63): error CS1010: Newline in constant // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63), // (6,5): error CS1010: Newline in constant // } Diagnostic(ErrorCode.ERR_NewlineInConst, "}").WithLocation(6, 5), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 // ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,5): error CS1010: Newline in constant // } Diagnostic(ErrorCode.ERR_NewlineInConst, "}").WithLocation(6, 5), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp03() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 /* ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,60): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, " {").WithLocation(5, 60), // (5,71): error CS1035: End-of-file found, '*/' expected // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71), // (7,2): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2), // (7,2): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void LambdaInInterp() { string source = @"using System; class Program { static void Main(string[] args) { //Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() }); Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}""); } static int number = 8675309; } "; string expectedOutput = @"jenny (408) 867-5309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OneLiteral() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""Hello"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Hello"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } [Fact] public void OneInsert() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; Console.WriteLine( $""{hello}"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldstr ""Hello"" IL_0005: dup IL_0006: brtrue.s IL_000e IL_0008: pop IL_0009: ldstr """" IL_000e: call ""void System.Console.WriteLine(string)"" IL_0013: ret } "); } [Fact] public void TwoInserts() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $""{hello}, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TwoInserts02() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $@""{ hello }, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")] public void DynamicInterpolation() { string source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { dynamic nil = null; dynamic a = new string[] {""Hello"", ""world""}; Console.WriteLine($""<{nil}>""); Console.WriteLine($""<{a}>""); } Expression<Func<string>> M(dynamic d) { return () => $""Dynamic: {d}""; } }"; string expectedOutput = @"<> <System.String[]>"; var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnclosedInterpolation01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31), // (7,5): error CS1010: Newline in constant // } Diagnostic(ErrorCode.ERR_NewlineInConst, "}").WithLocation(7, 5), // (7,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6), // (7,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6), // (8,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2)); } [Fact] public void UnclosedInterpolation02() { string source = @"class Program { static void Main(string[] args) { var x = $"";"; // The precise error messages are not important, but this must be an error. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,19): error CS1010: Newline in constant // var x = $"; Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19), // (5,20): error CS1002: ; expected // var x = $"; Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20) ); } [Fact] public void EmptyFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:}"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8089: Empty format specifier. // Console.WriteLine( $"{3:}" ); Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $"{3:d }" ); Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $@"{3:d Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d ").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS1733: Expected expression // Console.WriteLine( $"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32) ); } [Fact] public void MissingInterpolationExpression02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS1733: Expected expression // Console.WriteLine( $@"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression03() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( "; var normal = "$\""; var verbat = "$@\""; // ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail) Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline01() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" "" } ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline02() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" ""} ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void PreprocessorInsideInterpolation() { string source = @"class Program { static void Main() { var s = $@""{ #region : #endregion 0 }""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void EscapedCurly() { string source = @"class Program { static void Main() { var s1 = $"" \u007B ""; var s2 = $"" \u007D""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string. // var s1 = $" \u007B "; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21), // (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var s2 = $" \u007D"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21) ); } [Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")] public void NoFillIns01() { string source = @"class Program { static void Main() { System.Console.Write($""{{ x }}""); System.Console.WriteLine($@""This is a test""); } }"; string expectedOutput = @"{ x }This is a test"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BadAlignment() { string source = @"class Program { static void Main() { var s = $""{1,1E10}""; var t = $""{1,(int)1E10}""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22), // (5,22): error CS0150: A constant value is expected // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22), // (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override) // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22), // (6,22): error CS0150: A constant value is expected // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22) ); } [Fact] public void NestedInterpolatedVerbatim() { string source = @"using System; class Program { static void Main(string[] args) { var s = $@""{$@""{1}""}""; Console.WriteLine(s); } }"; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } // Since the platform type System.FormattableString is not yet in our platforms (at the // time of writing), we explicitly include the required platform types into the sources under test. private const string formattableString = @" /*============================================================ ** ** Class: FormattableString ** ** ** Purpose: implementation of the FormattableString ** class. ** ===========================================================*/ namespace System { /// <summary> /// A composite format string along with the arguments to be formatted. An instance of this /// type may result from the use of the C# or VB language primitive ""interpolated string"". /// </summary> public abstract class FormattableString : IFormattable { /// <summary> /// The composite format string. /// </summary> public abstract string Format { get; } /// <summary> /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> public abstract object[] GetArguments(); /// <summary> /// The number of arguments to be formatted. /// </summary> public abstract int ArgumentCount { get; } /// <summary> /// Returns one argument to be formatted from argument position <paramref name=""index""/>. /// </summary> public abstract object GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } /// <summary> /// Format the given object in the invariant culture. This static method may be /// imported in C# by /// <code> /// using static System.FormattableString; /// </code>. /// Within the scope /// of that import directive an interpolated string may be formatted in the /// invariant culture by writing, for example, /// <code> /// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"") /// </code> /// </summary> public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException(""formattable""); } return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); } } } /*============================================================ ** ** Class: FormattableStringFactory ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref=""FormattableString""/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format, params object[] arguments) { if (format == null) { throw new ArgumentNullException(""format""); } if (arguments == null) { throw new ArgumentNullException(""arguments""); } return new ConcreteFormattableString(format, arguments); } private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } public override object[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); } } } } "; [Fact] public void TargetType01() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; Console.Write(f is System.FormattableString); } }"; CompileAndVerify(source + formattableString, expectedOutput: "True"); } [Fact] public void TargetType02() { string source = @"using System; interface I1 { void M(String s); } interface I2 { void M(FormattableString s); } interface I3 { void M(IFormattable s); } interface I4 : I1, I2 {} interface I5 : I1, I3 {} interface I6 : I2, I3 {} interface I7 : I1, I2, I3 {} class C : I1, I2, I3, I4, I5, I6, I7 { public void M(String s) { Console.Write(1); } public void M(FormattableString s) { Console.Write(2); } public void M(IFormattable s) { Console.Write(3); } } class Program { public static void Main(string[] args) { C c = new C(); ((I1)c).M($""""); ((I2)c).M($""""); ((I3)c).M($""""); ((I4)c).M($""""); ((I5)c).M($""""); ((I6)c).M($""""); ((I7)c).M($""""); ((C)c).M($""""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "12311211"); } [Fact] public void MissingHelper() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; } }"; CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics( // (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported // IFormattable f = $"test"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26) ); } [Fact] public void AsyncInterp() { string source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { Task<string> hello = Task.FromResult(""Hello""); Task<string> world = Task.FromResult(""world""); M(hello, world).Wait(); } public static async Task M(Task<string> hello, Task<string> world) { Console.WriteLine($""{ await hello }, { await world }!""); } }"; CompileAndVerify( source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty); } [Fact] public void AlignmentExpression() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , -(3+4) }.""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "X = 123 ."); } [Fact] public void AlignmentMagnitude() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , (32768) }.""); Console.WriteLine($""X = { 123 , -(32768) }.""); Console.WriteLine($""X = { 123 , (32767) }.""); Console.WriteLine($""X = { 123 , -(32767) }.""); Console.WriteLine($""X = { 123 , int.MaxValue }.""); Console.WriteLine($""X = { 123 , int.MinValue }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , (32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42), // (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , -(32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41), // (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MaxValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41), // (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MinValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41) ); } [WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")] [Fact] public void InterpolationExpressionMustBeValue01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { String }.""); Console.WriteLine($""X = { null }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS0119: 'string' is a type, which is not valid in the given context // Console.WriteLine($"X = { String }."); Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35) ); } [Fact] public void InterpolationExpressionMustBeValue02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { x=>3 }.""); Console.WriteLine($""X = { Program.Main }.""); Console.WriteLine($""X = { Program.Main(null) }.""); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35), // (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS8917: The delegate type could not be inferred. // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x=>3").WithLocation(5, 35), // (6,35): warning CS8974: Converting method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "Program.Main").WithArguments("Main", "object").WithLocation(6, 35), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib01() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (15,21): error CS0117: 'string' does not contain a definition for 'Format' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib02() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Boolean Format(string format, int arg) { return true; } } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21) ); } [Fact] public void SillyCoreLib01() { var text = @"namespace System { interface IFormattable { } namespace Runtime.CompilerServices { public static class FormattableStringFactory { public static Bozo Create(string format, int arg) { return new Bozo(); } } } public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Bozo Format(string format, int arg) { return new Bozo(); } } public class FormattableString { } public class Bozo { public static implicit operator string(Bozo bozo) { return ""zz""; } public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); } } internal class Program { public static void Main() { var s1 = $""X = { 1 } ""; FormattableString s2 = $""X = { 1 } ""; } } }"; var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var compilation = CompileAndVerify(comp, verify: Verification.Fails); compilation.VerifyIL("System.Program.Main", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldstr ""X = {0} "" IL_0005: ldc.i4.1 IL_0006: call ""System.Bozo string.Format(string, int)"" IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)"" IL_0010: pop IL_0011: ldstr ""X = {0} "" IL_0016: ldc.i4.1 IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)"" IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)"" IL_0021: pop IL_0022: ret }"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax01() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):\}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40), // (6,40): error CS1009: Unrecognized escape sequence // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40) ); } [WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")] [Fact] public void Syntax02() { var text = @"using S = System; class C { void M() { var x = $""{ (S: } }"; // the precise diagnostics do not matter, as long as it is an error and not a crash. Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax03() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):}}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // var x = $"{ Math.Abs(value: 1):}}"; Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18) ); } [WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")] [Fact] public void NoUnexpandedForm() { string source = @"using System; class Program { public static void Main(string[] args) { string[] arr1 = new string[] { ""xyzzy"" }; object[] arr2 = arr1; Console.WriteLine($""-{null}-""); Console.WriteLine($""-{arr1}-""); Console.WriteLine($""-{arr2}-""); } }"; CompileAndVerify(source + formattableString, expectedOutput: @"-- -System.String[]- -System.String[]-"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Dynamic01() { var text = @"class C { const dynamic a = a; string s = $""{0,a}""; }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition // const dynamic a = a; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19), // (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null. // const dynamic a = a; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23), // (4,21): error CS0150: A constant value is expected // string s = $"{0,a}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21) ); } [WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")] [Fact] public void Syntax04() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<string>> e = () => $""\u1{0:\u2}""; Console.WriteLine(e); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,46): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46), // (8,52): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52) ); } [Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")] public void MissingConversionFromFormattableStringToIFormattable() { var text = @"namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) { return null; } } } namespace System { public abstract class FormattableString { } } static class C { static void Main() { System.IFormattable i = $""{""""}""; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics( // (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable' // System.IFormattable i = $"{""}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33) ); } [Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")] [InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")] [InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")] public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents) { var code = @" using System; Console.WriteLine(TwoComponents()); Console.WriteLine(ThreeComponents()); Console.WriteLine(FourComponents()); Console.WriteLine(FiveComponents()); string TwoComponents() { string s1 = ""1""; string s2 = ""2""; return " + twoComponents + @"; } string ThreeComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; return " + threeComponents + @"; } string FourComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; return " + fourComponents + @"; } string FiveComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; string s5 = ""5""; return " + fiveComponents + @"; } "; var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @" 12 123 1234 value:1 value:2 value:3 value:4 value:5 "); verifier.VerifyIL("Program.<<Main>$>g__TwoComponents|0_0()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (string V_0) //s2 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call ""string string.Concat(string, string)"" IL_0011: ret } "); verifier.VerifyIL("Program.<<Main>$>g__ThreeComponents|0_1()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (string V_0, //s2 string V_1) //s3 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldloc.0 IL_0012: ldloc.1 IL_0013: call ""string string.Concat(string, string, string)"" IL_0018: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FourComponents|0_2()", @" { // Code size 32 (0x20) .maxstack 4 .locals init (string V_0, //s2 string V_1, //s3 string V_2) //s4 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldstr ""4"" IL_0016: stloc.2 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""string string.Concat(string, string, string, string)"" IL_001f: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FiveComponents|0_3()", @" { // Code size 89 (0x59) .maxstack 3 .locals init (string V_0, //s1 string V_1, //s2 string V_2, //s3 string V_3, //s4 string V_4, //s5 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5) IL_0000: ldstr ""1"" IL_0005: stloc.0 IL_0006: ldstr ""2"" IL_000b: stloc.1 IL_000c: ldstr ""3"" IL_0011: stloc.2 IL_0012: ldstr ""4"" IL_0017: stloc.3 IL_0018: ldstr ""5"" IL_001d: stloc.s V_4 IL_001f: ldloca.s V_5 IL_0021: ldc.i4.0 IL_0022: ldc.i4.5 IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0030: ldloca.s V_5 IL_0032: ldloc.1 IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0038: ldloca.s V_5 IL_003a: ldloc.2 IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0040: ldloca.s V_5 IL_0042: ldloc.3 IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0048: ldloca.s V_5 IL_004a: ldloc.s V_4 IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0051: ldloca.s V_5 IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0058: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandler_OverloadsAndBoolReturns( bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @"int a = 1; System.Console.WriteLine(" + expression + @");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 80 (0x50) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldstr ""X"" IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.2 IL_0039: ldstr ""Y"" IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: ldloca.s V_1 IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0021: ldloca.s V_1 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 92 (0x5c) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_004d IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: brfalse.s IL_004d IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: brfalse.s IL_004d IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldstr ""X"" IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003b: brfalse.s IL_004d IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: br.s IL_004e IL_004d: ldc.i4.0 IL_004e: pop IL_004f: ldloca.s V_1 IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0056: call ""void System.Console.WriteLine(string)"" IL_005b: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_0051 IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0023: brfalse.s IL_0051 IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: brfalse.s IL_0051 IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldc.i4.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0047 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 88 (0x58) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004b IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: ldc.i4.0 IL_0033: ldstr ""X"" IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: ldloca.s V_1 IL_004d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0052: call ""void System.Console.WriteLine(string)"" IL_0057: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0051 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0051 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: brfalse.s IL_0051 IL_0027: ldloca.s V_1 IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0030: brfalse.s IL_0051 IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 100 (0x64) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0055 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0055 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0027: brfalse.s IL_0055 IL_0029: ldloca.s V_1 IL_002b: ldloc.0 IL_002c: ldc.i4.1 IL_002d: ldnull IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0033: brfalse.s IL_0055 IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.0 IL_0039: ldstr ""X"" IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: brfalse.s IL_0055 IL_0045: ldloca.s V_1 IL_0047: ldloc.0 IL_0048: ldc.i4.2 IL_0049: ldstr ""Y"" IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0053: br.s IL_0056 IL_0055: ldc.i4.0 IL_0056: pop IL_0057: ldloca.s V_1 IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005e: call ""void System.Console.WriteLine(string)"" IL_0063: ret } ", }; } [Fact] public void UseOfSpanInInterpolationHole_CSharp9() { var source = @" using System; ReadOnlySpan<char> span = stackalloc char[1]; Console.WriteLine($""{span}"");"; var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // Console.WriteLine($"{span}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22) ); } [ConditionalTheory(typeof(MonoOrCoreClrOnly))] [CombinatorialData] public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @" using System; ReadOnlySpan<char> a = ""1""; System.Console.WriteLine(" + expression + ");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldstr ""X"" IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: ldstr ""Y"" IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002a: ldloca.s V_1 IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0034: ldloca.s V_1 IL_0036: ldloc.0 IL_0037: ldc.i4.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 101 (0x65) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_0056 IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002a: brfalse.s IL_0056 IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: brfalse.s IL_0056 IL_0037: ldloca.s V_1 IL_0039: ldloc.0 IL_003a: ldstr ""X"" IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0044: brfalse.s IL_0056 IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: pop IL_0058: ldloca.s V_1 IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_005a IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002c: brfalse.s IL_005a IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: brfalse.s IL_005a IL_003a: ldloca.s V_1 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0050 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005a IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005a IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002e: brfalse.s IL_005a IL_0030: ldloca.s V_1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0039: brfalse.s IL_005a IL_003b: ldloca.s V_1 IL_003d: ldloc.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 97 (0x61) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0054 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: ldc.i4.0 IL_0028: ldnull IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: ldloca.s V_1 IL_003a: ldloc.0 IL_003b: ldc.i4.0 IL_003c: ldstr ""X"" IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: ldloca.s V_1 IL_0056: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005b: call ""void System.Console.WriteLine(string)"" IL_0060: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 109 (0x6d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005e IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005e IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0030: brfalse.s IL_005e IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldc.i4.1 IL_0036: ldnull IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_003c: brfalse.s IL_005e IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: ldstr ""X"" IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: brfalse.s IL_005e IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: ldc.i4.2 IL_0052: ldstr ""Y"" IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_005c: br.s IL_005f IL_005e: ldc.i4.0 IL_005f: pop IL_0060: ldloca.s V_1 IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0067: call ""void System.Console.WriteLine(string)"" IL_006c: ret } ", }; } [Theory] [InlineData(@"$""base{Throw()}{a = 2}""")] [InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")] public void BoolReturns_ShortCircuit(string expression) { var source = @" using System; int a = 1; Console.Write(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception();"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false"); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base 1"); } [Theory] [CombinatorialData] public void BoolOutParameter_ShortCircuits(bool useBoolReturns, [CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression) { var source = @" using System; int a = 1; Console.WriteLine(a); Console.WriteLine(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception(); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 1"); } [Theory] [InlineData(@"$""base{await Hole()}""")] [InlineData(@"$""base"" + $""{await Hole()}""")] public void AwaitInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @" { // Code size 164 (0xa4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00a3 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base{0}"" IL_0067: ldloc.1 IL_0068: box ""int"" IL_006d: call ""string string.Format(string, object)"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0090 } catch System.Exception { IL_0079: stloc.3 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0088: ldloc.3 IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008e: leave.s IL_00a3 } IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a3: ret } " : @" { // Code size 174 (0xae) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00ad IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base"" IL_0067: ldstr ""{0}"" IL_006c: ldloc.1 IL_006d: box ""int"" IL_0072: call ""string string.Format(string, object)"" IL_0077: call ""string string.Concat(string, string)"" IL_007c: call ""void System.Console.WriteLine(string)"" IL_0081: leave.s IL_009a } catch System.Exception { IL_0083: stloc.3 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0092: ldloc.3 IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0098: leave.s IL_00ad } IL_009a: ldarg.0 IL_009b: ldc.i4.s -2 IL_009d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00a2: ldarg.0 IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00ad: ret }"); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = await Hole(); Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base value:1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 185 (0xb9) .maxstack 3 .locals init (int V_0, int V_1, //hole System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00b8 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldc.i4.4 IL_0063: ldc.i4.1 IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0069: stloc.3 IL_006a: ldloca.s V_3 IL_006c: ldstr ""base"" IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0076: ldloca.s V_3 IL_0078: ldloc.1 IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_007e: ldloca.s V_3 IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0085: call ""void System.Console.WriteLine(string)"" IL_008a: leave.s IL_00a5 } catch System.Exception { IL_008c: stloc.s V_4 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009c: ldloc.s V_4 IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a3: leave.s IL_00b8 } IL_00a5: ldarg.0 IL_00a6: ldc.i4.s -2 IL_00a8: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00ad: ldarg.0 IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b8: ret } "); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = 2; Test(await M(1), " + expression + @", await M(3)); void Test(int i1, string s, int i2) => Console.WriteLine(s); Task<int> M(int i) { Console.WriteLine(i); return Task.FromResult(1); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 3 base value:2"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 328 (0x148) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0050 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00dc IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: stfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0018: ldc.i4.1 IL_0019: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0023: stloc.2 IL_0024: ldloca.s V_2 IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002b: brtrue.s IL_006c IL_002d: ldarg.0 IL_002e: ldc.i4.0 IL_002f: dup IL_0030: stloc.0 IL_0031: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0036: ldarg.0 IL_0037: ldloc.2 IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003d: ldarg.0 IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0043: ldloca.s V_2 IL_0045: ldarg.0 IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004b: leave IL_0147 IL_0050: ldarg.0 IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0056: stloc.2 IL_0057: ldarg.0 IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0063: ldarg.0 IL_0064: ldc.i4.m1 IL_0065: dup IL_0066: stloc.0 IL_0067: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006c: ldarg.0 IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0079: ldarg.0 IL_007a: ldc.i4.4 IL_007b: ldc.i4.1 IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0081: stloc.3 IL_0082: ldloca.s V_3 IL_0084: ldstr ""base"" IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_008e: ldloca.s V_3 IL_0090: ldarg.0 IL_0091: ldfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_009b: ldloca.s V_3 IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00a2: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_00a7: ldc.i4.3 IL_00a8: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00b2: stloc.2 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00ba: brtrue.s IL_00f8 IL_00bc: ldarg.0 IL_00bd: ldc.i4.1 IL_00be: dup IL_00bf: stloc.0 IL_00c0: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldloc.2 IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00cc: ldarg.0 IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d2: ldloca.s V_2 IL_00d4: ldarg.0 IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_00da: leave.s IL_0147 IL_00dc: ldarg.0 IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e2: stloc.2 IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00ef: ldarg.0 IL_00f0: ldc.i4.m1 IL_00f1: dup IL_00f2: stloc.0 IL_00f3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00f8: ldloca.s V_2 IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ff: stloc.1 IL_0100: ldarg.0 IL_0101: ldfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0106: ldarg.0 IL_0107: ldfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_010c: ldloc.1 IL_010d: call ""void Program.<<Main>$>g__Test|0_0(int, string, int)"" IL_0112: ldarg.0 IL_0113: ldnull IL_0114: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_0119: leave.s IL_0134 } catch System.Exception { IL_011b: stloc.s V_4 IL_011d: ldarg.0 IL_011e: ldc.i4.s -2 IL_0120: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0125: ldarg.0 IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_012b: ldloc.s V_4 IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0132: leave.s IL_0147 } IL_0134: ldarg.0 IL_0135: ldc.i4.s -2 IL_0137: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0147: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void DynamicInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 3 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base"" IL_000c: ldstr ""{0}"" IL_0011: ldloc.0 IL_0012: call ""string string.Format(string, object)"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{hole}base""")] [InlineData(@"$""{hole}"" + $""base""")] public void DynamicInHoles_UsesFormat2(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"1base"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: ldstr ""base"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}base"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Fact] public void ImplicitConversionsInConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(object literalLength, object formattedCount) {} } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerAttribute }); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: box ""int"" IL_000c: newobj ""CustomHandler..ctor(object, object)"" IL_0011: pop IL_0012: ret } "); } [Fact] public void MissingCreate_01() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_02() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_03() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5) ); } [Theory] [InlineData(null)] [InlineData("public string ToStringAndClear(int literalLength) => throw null;")] [InlineData("public void ToStringAndClear() => throw null;")] [InlineData("public static string ToStringAndClear() => throw null;")] public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod) { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; " + toStringAndClearMethod + @" public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5) ); } [Fact] public void ObsoleteCreateMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { [System.Obsolete(""Constructor is obsolete"", error: true)] public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5) ); } [Fact] public void ObsoleteAppendLiteralMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; [System.Obsolete(""AppendLiteral is obsolete"", error: true)] public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7) ); } [Fact] public void ObsoleteAppendFormattedMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; [System.Obsolete(""AppendFormatted is obsolete"", error: true)] public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11) ); } private const string UnmanagedCallersOnlyIl = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } }"; [Fact] public void UnmanagedCallersOnlyAppendFormattedMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance void Dispose () cil managed { ldnull throw } .method public hidebysig virtual instance string ToString () cil managed { ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics( // (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7) ); } [Fact] public void UnmanagedCallersOnlyToStringMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance string ToStringAndClear () cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5) ); } [Theory] [InlineData(@"$""{i}{s}""")] [InlineData(@"$""{i}"" + $""{s}""")] public void UnsupportedArgumentType(string expression) { var source = @" unsafe { int* i = null; var s = new S(); _ = " + expression + @"; } ref struct S { }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (6,11): error CS0306: The type 'int*' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11), // (6,14): error CS0306: The type 'S' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length) ); } [Theory] [InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")] [InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")] public void TargetTypedInterpolationHoles(string expression) { var source = @" bool b = true; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2 value: value:"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 81 (0x51) .maxstack 3 .locals init (bool V_0, //b object V_1, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.0 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloc.0 IL_000c: brfalse.s IL_0017 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: stloc.1 IL_0015: br.s IL_0019 IL_0017: ldnull IL_0018: stloc.1 IL_0019: ldloca.s V_2 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0021: ldloca.s V_2 IL_0023: ldloc.0 IL_0024: brfalse.s IL_002e IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: br.s IL_002f IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0034: ldloca.s V_2 IL_0036: ldnull IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_003c: ldloca.s V_2 IL_003e: ldnull IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0044: ldloca.s V_2 IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Theory] [InlineData(@"$""{(null, default)}{new()}""")] [InlineData(@"$""{(null, default)}"" + $""{new()}""")] public void TargetTypedInterpolationHoles_Errors(string expression) { var source = @"System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object' // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29), // (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29), // (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length) ); } [Fact] public void RefTernary() { var source = @" bool b = true; int i = 1; System.Console.WriteLine($""{(!b ? ref i : ref i)}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); } [Fact] public void NestedInterpolatedStrings_01() { var source = @" int i = 1; System.Console.WriteLine($""{$""{i}""}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0013: ldloca.s V_1 IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret } "); } [Theory] [InlineData(@"$""{$""{i1}""}{$""{i2}""}""")] [InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")] public void NestedInterpolatedStrings_02(string expression) { var source = @" int i1 = 1; int i2 = 2; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 63 (0x3f) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldloca.s V_2 IL_0006: ldc.i4.0 IL_0007: ldc.i4.1 IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0015: ldloca.s V_2 IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001c: ldloca.s V_2 IL_001e: ldc.i4.0 IL_001f: ldc.i4.1 IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0025: ldloca.s V_2 IL_0027: ldloc.1 IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_002d: ldloca.s V_2 IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0034: call ""string string.Concat(string, string)"" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: ret } "); } [Fact] public void ExceptionFilter_01() { var source = @" using System; int i = 1; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = i }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{i}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public int Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 .try { IL_0002: ldstr ""Starting try"" IL_0007: call ""void System.Console.WriteLine(string)"" IL_000c: newobj ""MyException..ctor()"" IL_0011: dup IL_0012: ldloc.0 IL_0013: callvirt ""void MyException.Prop.set"" IL_0018: throw } filter { IL_0019: isinst ""MyException"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldc.i4.0 IL_0023: br.s IL_004f IL_0025: callvirt ""string object.ToString()"" IL_002a: ldloca.s V_1 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0033: ldloca.s V_1 IL_0035: ldloc.0 IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_003b: ldloca.s V_1 IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0042: callvirt ""string string.Trim()"" IL_0047: call ""bool string.op_Equality(string, string)"" IL_004c: ldc.i4.0 IL_004d: cgt.un IL_004f: endfilter } // end filter { // handler IL_0051: pop IL_0052: ldstr ""Caught"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: leave.s IL_005e } IL_005e: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ExceptionFilter_02() { var source = @" using System; ReadOnlySpan<char> s = new char[] { 'i' }; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = s.ToString() }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{s}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public string Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: newarr ""char"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 105 IL_000a: stelem.i2 IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])"" IL_0010: stloc.0 .try { IL_0011: ldstr ""Starting try"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: newobj ""MyException..ctor()"" IL_0020: dup IL_0021: ldloca.s V_0 IL_0023: constrained. ""System.ReadOnlySpan<char>"" IL_0029: callvirt ""string object.ToString()"" IL_002e: callvirt ""void MyException.Prop.set"" IL_0033: throw } filter { IL_0034: isinst ""MyException"" IL_0039: dup IL_003a: brtrue.s IL_0040 IL_003c: pop IL_003d: ldc.i4.0 IL_003e: br.s IL_006a IL_0040: callvirt ""string object.ToString()"" IL_0045: ldloca.s V_1 IL_0047: ldc.i4.0 IL_0048: ldc.i4.1 IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0056: ldloca.s V_1 IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005d: callvirt ""string string.Trim()"" IL_0062: call ""bool string.op_Equality(string, string)"" IL_0067: ldc.i4.0 IL_0068: cgt.un IL_006a: endfilter } // end filter { // handler IL_006c: pop IL_006d: ldstr ""Caught"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0079 } IL_0079: ret } "); } [ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] [InlineData(@"$""{s}{c}""")] [InlineData(@"$""{s}"" + $""{c}""")] public void ImplicitUserDefinedConversionInHole(string expression) { var source = @" using System; S s = default; C c = new C(); Console.WriteLine(" + expression + @"); ref struct S { public static implicit operator ReadOnlySpan<char>(S s) => ""S converted""; } class C { public static implicit operator ReadOnlySpan<char>(C s) => ""C converted""; }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:S converted value:C"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, //s C V_1, //c System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: newobj ""C..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.0 IL_0011: ldc.i4.2 IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0024: ldloca.s V_2 IL_0026: ldloc.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)"" IL_002c: ldloca.s V_2 IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ExplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; Console.WriteLine($""{s}""); ref struct S { public static explicit operator ReadOnlySpan<char>(S s) => ""S converted""; } "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,21): error CS0306: The type 'S' may not be used as a type argument // Console.WriteLine($"{s}"); Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ImplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static implicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var verifier = CompileAndVerify(source, expectedOutput: @" literal:Text value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 52 (0x34) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Text"" IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)"" IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.1 IL_001d: box ""int"" IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0027: ldloca.s V_0 IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } "); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ExplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static explicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct' // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void InvalidBuilderReturnType(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public int AppendLiteral(string s) => 0; public int AppendFormatted(object o) => 0; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21), // (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length) ); } [Fact] public void MissingAppendMethods() { var source = @" using System.Runtime.CompilerServices; CustomHandler c = $""Literal{1}""; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } } "; var comp = CreateCompilation(new[] { source, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,21): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 21), // (4,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Literal").WithArguments("?.()").WithLocation(4, 21), // (4,28): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{1}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 28), // (4,28): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("?.()").WithLocation(4, 28) ); } [Fact] public void MissingBoolType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @"CustomHandler c = $""Literal{1}"";"; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyDiagnostics( // (1,19): error CS0518: Predefined type 'System.Boolean' is not defined or imported // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""Literal{1}""").WithArguments("System.Boolean").WithLocation(1, 19) ); } [Fact] public void MissingVoidType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @" class C { public bool M() { CustomHandler c = $""Literal{1}""; return true; } } "; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Void); comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_01(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length) ); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_02(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(string s) { } public bool AppendFormatted(object o) => true; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length) ); } [Fact] public void MixedBuilderReturnTypes_03() { var source = @" using System; Console.WriteLine($""{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { _builder.AppendLine(""value:"" + o.ToString()); } } }"; CompileAndVerify(source, expectedOutput: "value:1"); } [Fact] public void MixedBuilderReturnTypes_04() { var source = @" using System; using System.Text; using System.Runtime.CompilerServices; Console.WriteLine((CustomHandler)$""l""); [InterpolatedStringHandler] public class CustomHandler { private readonly StringBuilder _builder; public CustomHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public override string ToString() => _builder.ToString(); public bool AppendFormatted(object o) => true; public void AppendLiteral(string s) { _builder.AppendLine(""literal:"" + s.ToString()); } } "; CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l"); } private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler") { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var descendentNodes = tree.GetRoot().DescendantNodes(); var interpolatedString = (ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>() .Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any()) .FirstOrDefault() ?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(interpolatedString); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.Exists); Assert.True(semanticInfo.ImplicitConversion.IsValid); Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler); Assert.Null(semanticInfo.ImplicitConversion.Method); if (interpolatedString is BinaryExpressionSyntax) { Assert.False(semanticInfo.ConstantValue.HasValue); AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString()); } // https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings. } private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput) => CompileAndVerify( compilation, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); [Theory] [CombinatorialData] public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns, [CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression) { var code = @" CustomHandler builder = " + expression + @"; System.Console.WriteLine(builder.ToString());"; var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns); var comp = CreateCompilation(new[] { code, builder }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:Literal value:1 alignment:2 format:f"); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (type, useBoolReturns) switch { (type: "struct", useBoolReturns: true) => @" { // Code size 67 (0x43) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""bool CustomHandler.AppendLiteral(string)"" IL_0015: brfalse.s IL_002c IL_0017: ldloca.s V_1 IL_0019: ldc.i4.1 IL_001a: box ""int"" IL_001f: ldc.i4.2 IL_0020: ldstr ""f"" IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: constrained. ""CustomHandler"" IL_0038: callvirt ""string object.ToString()"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } ", (type: "struct", useBoolReturns: false) => @" { // Code size 61 (0x3d) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(string)"" IL_0015: ldloca.s V_1 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldc.i4.2 IL_001e: ldstr ""f"" IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0028: ldloc.1 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""CustomHandler"" IL_0032: callvirt ""string object.ToString()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } ", (type: "class", useBoolReturns: true) => @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""Literal"" IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0013: brfalse.s IL_0029 IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: box ""int"" IL_001c: ldc.i4.2 IL_001d: ldstr ""f"" IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret } ", (type: "class", useBoolReturns: false) => @" { // Code size 47 (0x2f) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldstr ""Literal"" IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: box ""int"" IL_0019: ldc.i4.2 IL_001a: ldstr ""f"" IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret } ", _ => throw ExceptionUtilities.Unreachable }; } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void CustomHandlerMethodArgument(string expression) { var code = @" M(" + expression + @"); void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"($""{1,2:f}"" + $""Literal"")")] public void ExplicitHandlerCast_InCode(string expression) { var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); syntax = ((CastExpressionSyntax)syntax).Expression; Assert.Equal(expression, syntax.ToString()); semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); // https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: call ""void System.Console.WriteLine(object)"" IL_0029: ret } "); } [Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void HandlerConversionPreferredOverStringForNonConstant(string expression) { var code = @" CultureInfoNormalizer.Normalize(); C.M(" + expression + @"); class C { public static void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.7 IL_0006: ldc.i4.1 IL_0007: newobj ""CustomHandler..ctor(int, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldc.i4.2 IL_0015: ldstr ""f"" IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001f: brfalse.s IL_002e IL_0021: ldloc.0 IL_0022: ldstr ""Literal"" IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: pop IL_0030: ldloc.0 IL_0031: call ""void C.M(CustomHandler)"" IL_0036: ret } "); comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9); verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: ldstr ""Literal"" IL_001a: call ""string string.Concat(string, string)"" IL_001f: call ""void C.M(string)"" IL_0024: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}Literal"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: call ""void C.M(string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler b) { throw null; } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Literal"" IL_0005: call ""void C.M(string)"" IL_000a: ret } "); } [Theory] [InlineData(@"$""{1}{2}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type // [Attr($"{1}{2}")] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2) ); VerifyInterpolatedStringExpression(comp); var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); void validate(ModuleSymbol m) { var attr = m.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => throw null; public static void M(CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); comp.VerifyDiagnostics( // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)' // C.M($""); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_01(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_02(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_03(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'. // C.M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_01(string expression) { var code = @" C.M(" + expression + @", default(CustomHandler)); C.M(default(CustomHandler), " + expression + @"); class C { public static void M<T>(T t1, T t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M($"{1,2:f}Literal", default(CustomHandler)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3), // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_02(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), () => $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_03(string expression) { var code = @" using System; C.M(" + expression + @", default(CustomHandler)); class C { public static void M<T>(T t1, T t2) => Console.WriteLine(t1); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 51 (0x33) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ldnull IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)"" IL_0032: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_04(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2()); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_01(string expression) { var code = @" using System; Func<CustomHandler> f = () => " + expression + @"; Console.WriteLine(f()); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_02(string expression) { var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(() => " + expression + @"); class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } "; // Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string, // so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec). var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); // No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldstr ""{0,2:f}Literal"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldstr ""{0,2:f}"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ldstr ""Literal"" IL_0015: call ""string string.Concat(string, string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_03(string expression) { // Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct // when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to // fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>. var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => throw null; public static void M(Func<CustomHandler> f) => Console.WriteLine(f()); } public partial class CustomHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } public ref struct S { public string Field { get; set; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 35 (0x23) .maxstack 4 .locals init (S V_0) IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldloca.s V_0 IL_000a: initobj ""S"" IL_0010: ldloca.s V_0 IL_0012: ldstr ""Field"" IL_0017: call ""void S.Field.set"" IL_001c: ldloc.0 IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)"" IL_0022: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_04(string expression) { // Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type) var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } public partial class CustomHandler { public void AppendFormatted(S value) => throw null; } public ref struct S { public string Field { get; set; } } namespace System.Runtime.CompilerServices { public ref partial struct DefaultInterpolatedStringHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } } "; string[] source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false), GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11), // (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloca.s V_1 IL_000d: initobj ""S"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""Field"" IL_001a: call ""void S.Field.set"" IL_001f: ldloc.1 IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)"" IL_0025: ldloca.s V_0 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_05(string expression) { var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => throw null; public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_06(string expression) { // Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion // means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec) // and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type // has an identity conversion to the return type of Func<bool, string>, that is preferred. var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @" { // Code size 35 (0x23) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ret } " : @" { // Code size 45 (0x2d) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_07(string expression) { // Same as 5, but with an implicit conversion from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } public partial struct CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_08(string expression) { // Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)' // C.M(b => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void LambdaInference_AmbiguousInOlderLangVersions(string expression) { var code = @" using System; C.M(param => { param = " + expression + @"; }); static class C { public static void M(Action<string> f) => throw null; public static void M(Action<CustomHandler> f) => throw null; } "; var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); // This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04 // We should not be changing binding behavior based on LangVersion. comp.VerifyEmitDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)' // C.M(param => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_01(string expression) { var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06 var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 56 (0x38) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_0024 IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: br.s IL_0032 IL_0024: ldloca.s V_0 IL_0026: initobj ""CustomHandler"" IL_002c: ldloc.0 IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } " : @" { // Code size 66 (0x42) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_002e IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: br.s IL_003c IL_002e: ldloca.s V_0 IL_0030: initobj ""CustomHandler"" IL_0036: ldloc.0 IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_03(string expression) { // Same as 02, but with a target-type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_04(string expression) { // Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07 var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_05(string expression) { // Same 01, but with a conversion from string to CustomHandler and CustomHandler to string. var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another // var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_06(string expression) { // Same 05, but with a target type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0046: call ""void System.Console.WriteLine(string)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_01(string expression) { // Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types // and not on expression conversions, no best type can be found for this switch expression. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string. var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 59 (0x3b) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_0034 IL_0023: ldstr ""{0,2:f}Literal"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } " : @" { // Code size 69 (0x45) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_003e IL_0023: ldstr ""{0,2:f}"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: ldstr ""Literal"" IL_0038: call ""string string.Concat(string, string)"" IL_003d: stloc.0 IL_003e: ldloc.0 IL_003f: call ""void System.Console.WriteLine(string)"" IL_0044: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_03(string expression) { // Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile). var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_04(string expression) { // Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: box ""CustomHandler"" IL_0049: call ""void System.Console.WriteLine(object)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_05(string expression) { // Same as 01, but with conversions in both directions. No best common type can be found. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_06(string expression) { // Same as 05, but with a target type. var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_01(string expression) { var code = @" M(" + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(ref CustomHandler)"" IL_002f: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_02(string expression) { var code = @" M(" + expression + @"); M(ref " + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword // M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3), // (3,7): error CS1510: A ref or out value must be an assignable variable // M(ref $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_03(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 5 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_04(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002f: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void RefOverloadResolution_MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => System.Console.WriteLine(c); public static void M(ref CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); VerifyInterpolatedStringExpression(comp, "CustomHandler1"); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler1 V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler1..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler1.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler1)"" IL_002e: ret } "); } private const string InterpolatedStringHandlerAttributesVB = @" Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerAttribute Inherits Attribute End Class <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute Inherits Attribute Public Sub New(argument As String) Arguments = { argument } End Sub Public Sub New(ParamArray arguments() as String) Me.Arguments = arguments End Sub Public ReadOnly Property Arguments As String() End Class End Namespace "; [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (8,27): error CS8946: 'string' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27) ); var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String) End Sub End Class "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); // Note: there is no compilation error here because the natural type of a string is still string, and // we just bind to that method without checking the handler attribute. var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string' // public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70) ); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'. // public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34), // (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; _ = new C(" + expression + @"); class C { public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11), // (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression) { var code = @" using System.Runtime.CompilerServices; C<CustomHandler>.M(" + expression + @"); public class C<T> { public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20), // (8,27): error CS8946: 'T' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27) ); var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C"); var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler"); var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler))); var cParam = substitutedC.GetMethod("M").Parameters.Single(); Assert.IsType<SubstitutedParameterSymbol>(cParam); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C(Of T) Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var goodCode = @" int i = 10; C.M(i: i, c: " + expression + @"); "; var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @" i:10 literal:text "); verifier.VerifyDiagnostics( // (6,27): warning CS8947: Parameter 'i' occurs after 'c' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to // reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "c").WithLocation(6, 27) ); verifyIL(verifier); var badCode = @"C.M(" + expression + @", 1);"; comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'. // C.M($"", 1); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length), // (6,27): warning CS8947: Parameter 'i' occurs after 'c' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to // reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "c").WithLocation(6, 27) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } void verifyIL(CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 36 (0x24) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldloca.s V_2 IL_0007: ldc.i4.4 IL_0008: ldc.i4.0 IL_0009: ldloc.0 IL_000a: call ""CustomHandler..ctor(int, int, int)"" IL_000f: ldloca.s V_2 IL_0011: ldstr ""text"" IL_0016: call ""bool CustomHandler.AppendLiteral(string)"" IL_001b: pop IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call ""void C.M(CustomHandler, int)"" IL_0023: ret } " : @" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldc.i4.4 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_3 IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000f: stloc.2 IL_0010: ldloc.3 IL_0011: brfalse.s IL_0021 IL_0013: ldloca.s V_2 IL_0015: ldstr ""text"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.2 IL_0024: ldloc.1 IL_0025: call ""void C.M(CustomHandler, int)"" IL_002a: ret } "); } } [Fact] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter 'i' occurs after 'c' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder // parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i = 0) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "c").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter 'i' occurs after 'c' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder // parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "c").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { private CustomHandler(int literalLength, int formattedCount, int i) : this() {} static void InCustomHandler() { C.M(1, " + expression + @"); } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() }); comp.VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8) ); comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics) { var code = @" using System.Runtime.CompilerServices; int i = 0; C.M(" + mRef + @" i, " + expression + @"); public class C { public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression, // (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6)); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this() { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var expectedDiagnostics = extraConstructorArg == "" ? new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5) } : new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)' // C.M(1, $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8) }; var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { comp = CreateCompilation(executableCode, new[] { d }); comp.VerifyDiagnostics(expectedDiagnostics); } static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString(); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" using System; int i = 10; Console.WriteLine(C.M(i, " + expression + @")); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 39 (0x27) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.1 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""CustomHandler..ctor(int, int, int)"" IL_000e: ldloca.s V_1 IL_0010: ldstr ""2"" IL_0015: call ""bool CustomHandler.AppendLiteral(string)"" IL_001a: pop IL_001b: ldloc.1 IL_001c: call ""string C.M(int, CustomHandler)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } " : @" { // Code size 46 (0x2e) .maxstack 5 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: ldloc.0 IL_0007: ldloca.s V_2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0020 IL_0012: ldloca.s V_1 IL_0014: ldstr ""2"" IL_0019: call ""bool CustomHandler.AppendLiteral(string)"" IL_001e: br.s IL_0021 IL_0020: ldc.i4.0 IL_0021: pop IL_0022: ldloc.1 IL_0023: call ""string C.M(int, CustomHandler)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" int i = 10; string s = ""arg""; C.M(i, s, " + expression + @"); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); string expectedOutput = @" i:10 s:arg literal:literal "; var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol verifier) { var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 44 (0x2c) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldloca.s V_3 IL_000f: ldc.i4.7 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloc.2 IL_0013: call ""CustomHandler..ctor(int, int, int, string)"" IL_0018: ldloca.s V_3 IL_001a: ldstr ""literal"" IL_001f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0024: pop IL_0025: ldloc.3 IL_0026: call ""void C.M(int, string, CustomHandler)"" IL_002b: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldc.i4.7 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: ldloc.2 IL_0011: ldloca.s V_4 IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_0018: stloc.3 IL_0019: ldloc.s V_4 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_3 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.3 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; string s = null; object o; C.M(i, ref s, out o, " + expression + @"); Console.WriteLine(s); Console.WriteLine(o); public class C { public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c) { Console.WriteLine(s); o = ""o in M""; s = ""s in M""; Console.Write(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount) { o = null; s = ""s in constructor""; _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" s in constructor i:1 literal:literal s in M o in M "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 67 (0x43) .maxstack 8 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)"" IL_0020: stloc.s V_6 IL_0022: ldloca.s V_6 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: pop IL_002f: ldloc.s V_6 IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_0036: ldloc.1 IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldloc.2 IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: ret } " : @" { // Code size 76 (0x4c) .maxstack 9 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6, bool V_7) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: ldloca.s V_7 IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)"" IL_0022: stloc.s V_6 IL_0024: ldloc.s V_7 IL_0026: brfalse.s IL_0036 IL_0028: ldloca.s V_6 IL_002a: ldstr ""literal"" IL_002f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0034: br.s IL_0037 IL_0036: ldc.i4.0 IL_0037: pop IL_0038: ldloc.s V_6 IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_003f: ldloc.1 IL_0040: call ""void System.Console.WriteLine(string)"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), GetString(), " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt GetString s:str i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 45 (0x2d) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: call ""CustomHandler..ctor(int, int, string, int)"" IL_0019: ldloca.s V_2 IL_001b: ldstr ""literal"" IL_0020: call ""bool CustomHandler.AppendLiteral(string)"" IL_0025: pop IL_0026: ldloc.2 IL_0027: call ""void C.M(int, string, CustomHandler)"" IL_002c: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_3 IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)"" IL_0019: stloc.2 IL_001a: ldloc.3 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_2 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.2 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetC().M(s: GetString(), i: GetInt(), c: " + expression + @"); C GetC() { Console.WriteLine(""GetC""); return new C { Field = 5 }; } int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public int Field; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""c.Field:"" + c.Field.ToString()); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetC GetString GetInt s:str c.Field:5 i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 56 (0x38) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldloca.s V_4 IL_0019: ldc.i4.7 IL_001a: ldc.i4.0 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldloc.2 IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)"" IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""bool CustomHandler.AppendLiteral(string)"" IL_002f: pop IL_0030: ldloc.s V_4 IL_0032: callvirt ""void C.M(int, string, CustomHandler)"" IL_0037: ret } " : @" { // Code size 65 (0x41) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4, bool V_5) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldc.i4.7 IL_0018: ldc.i4.0 IL_0019: ldloc.0 IL_001a: ldloc.1 IL_001b: ldloc.2 IL_001c: ldloca.s V_5 IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)"" IL_0023: stloc.s V_4 IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0037 IL_0029: ldloca.s V_4 IL_002b: ldstr ""literal"" IL_0030: call ""bool CustomHandler.AppendLiteral(string)"" IL_0035: br.s IL_0038 IL_0037: ldc.i4.0 IL_0038: pop IL_0039: ldloc.s V_4 IL_003b: callvirt ""void C.M(int, string, CustomHandler)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), """", " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""i2:"" + i2.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt i1:10 i2:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 43 (0x2b) .maxstack 7 .locals init (int V_0, CustomHandler V_1) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: call ""CustomHandler..ctor(int, int, int, int)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: call ""void C.M(int, string, CustomHandler)"" IL_002a: ret } " : @" { // Code size 50 (0x32) .maxstack 7 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldc.i4.7 IL_000d: ldc.i4.0 IL_000e: ldloc.0 IL_000f: ldloc.0 IL_0010: ldloca.s V_2 IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: brfalse.s IL_0029 IL_001b: ldloca.s V_1 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.1 IL_002c: call ""void C.M(int, string, CustomHandler)"" IL_0031: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, """", " + expression + @"); public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: newobj ""CustomHandler..ctor(int, int)"" IL_000d: call ""void C.M(int, string, CustomHandler)"" IL_0012: ret } " : @" { // Code size 21 (0x15) .maxstack 5 .locals init (bool V_0) IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)"" IL_000f: call ""void C.M(int, string, CustomHandler)"" IL_0014: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { } } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics( (extraConstructorArg == "") ? new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12), // (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12) } : new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12), // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12) } ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); Console.WriteLine(c[10, ""str"", " + expression + @"]); public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: callvirt ""string C.this[int, string, CustomHandler].get"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""string C.this[int, string, CustomHandler].get"" IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); c[10, ""str"", " + expression + @"] = """"; public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: ldstr """" IL_002e: callvirt ""void C.this[int, string, CustomHandler].set"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: ldstr """" IL_0035: callvirt ""void C.this[int, string, CustomHandler].set"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; (new C(5)).M((int)10, ""str"", " + expression + @"); public class C { public int Prop { get; } public C(int i) => Prop = i; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""c.Prop:"" + c.Prop.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 c.Prop:5 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 51 (0x33) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_3 IL_0015: ldc.i4.7 IL_0016: ldc.i4.0 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)"" IL_001f: ldloca.s V_3 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: pop IL_002c: ldloc.3 IL_002d: callvirt ""void C.M(int, string, CustomHandler)"" IL_0032: ret } " : @" { // Code size 59 (0x3b) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: ldloc.1 IL_0017: ldloc.2 IL_0018: ldloca.s V_4 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)"" IL_001f: stloc.3 IL_0020: ldloc.s V_4 IL_0022: brfalse.s IL_0032 IL_0024: ldloca.s V_3 IL_0026: ldstr ""literal"" IL_002b: call ""bool CustomHandler.AppendLiteral(string)"" IL_0030: br.s IL_0033 IL_0032: ldc.i4.0 IL_0033: pop IL_0034: ldloc.3 IL_0035: callvirt ""void C.M(int, string, CustomHandler)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(5, " + expression + @"); public class C { public int Prop { get; } public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" i:5 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 34 (0x22) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldloca.s V_1 IL_0005: ldc.i4.7 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: call ""CustomHandler..ctor(int, int, int)"" IL_000d: ldloca.s V_1 IL_000f: ldstr ""literal"" IL_0014: call ""bool CustomHandler.AppendLiteral(string)"" IL_0019: pop IL_001a: ldloc.1 IL_001b: newobj ""C..ctor(int, CustomHandler)"" IL_0020: pop IL_0021: ret } "); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_RefParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression, [CombinatorialValues("class", "struct")] string receiverType) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public " + receiverType + @" C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(extraConstructorArg != "" ? new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, ref C, out bool)' // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, ref C, out bool)").WithLocation(6, 15), // (6,15): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(6, 15) } : new[] { // (6,15): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(6, 15) }); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC().M(" + expression + @"); " + refness + @" C GetC() => throw null; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC().M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10) ); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); ref C GetC(ref C c) => ref c; public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { _builder.Append(c.I); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var verifier = CompileAndVerify( new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: "1literal:literal", symbolValidator: validator, sourceSymbolValidator: validator, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); verifier.VerifyIL("<top-level-statements-entry-point>", refness == "in" ? @" { // Code size 46 (0x2e) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, in C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: callvirt ""void C.M(CustomHandler)"" IL_002d: ret } " : @" { // Code size 48 (0x30) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldloca.s V_2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.1 IL_0016: ldind.ref IL_0017: call ""CustomHandler..ctor(int, int, C)"" IL_001c: ldloca.s V_2 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: pop IL_0029: ldloc.2 IL_002a: callvirt ""void C.M(CustomHandler)"" IL_002f: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory, CombinatorialData] [WorkItem(56624, "https://github.com/dotnet/roslyn/issues/56624")] public void RefOrOutParameter_AsReceiver([CombinatorialValues("ref", "out")] string parameterRefness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = default; localFunc(" + parameterRefness + @" c); void localFunc(" + parameterRefness + @" C c) { c = new C(1); c.M(" + expression + @"); } public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.Append(c.I); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: "1literal:literal", symbolValidator: validator, sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); verifier.VerifyIL($"Program.<<Main>$>g__localFunc|0_0({parameterRefness} C)", @" { // Code size 43 (0x2b) .maxstack 5 .locals init (C& V_0, CustomHandler V_1) IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int)"" IL_0007: stind.ref IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldind.ref IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldind.ref IL_0012: call ""CustomHandler..ctor(int, int, C)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: callvirt ""void C.M(CustomHandler)"" IL_002a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Rvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(s2, " + expression + @"); public struct S { public int I; public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" s1.I:1 s2.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 6 .locals init (S V_0, //s2 S V_1, S V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: ldloca.s V_1 IL_0013: initobj ""S"" IL_0019: ldloca.s V_1 IL_001b: ldc.i4.2 IL_001c: stfld ""int S.I"" IL_0021: ldloc.1 IL_0022: stloc.0 IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldloc.1 IL_002c: ldloc.2 IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)"" IL_0032: call ""void S.M(S, CustomHandler)"" IL_0037: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Lvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(ref s2, " + expression + @"); public struct S { public int I; public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword // s1.M(ref s2, $""); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByVal(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(s, " + expression + @"); public struct S { public int I; public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.0 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: newobj ""CustomHandler..ctor(int, int, S)"" IL_001b: call ""void S.M(S, CustomHandler)"" IL_0020: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByRef(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(ref s, " + expression + @"); public struct S { public int I; public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 36 (0x24) .maxstack 4 .locals init (S V_0, //s S V_1, S& V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldc.i4.0 IL_0017: ldc.i4.0 IL_0018: ldloc.2 IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)"" IL_001e: call ""void S.M(ref S, CustomHandler)"" IL_0023: ret } "); } [Theory] [CombinatorialData] public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetReceiver().M( GetArg(""Unrelated parameter 1""), GetArg(""Second value""), GetArg(""Unrelated parameter 2""), GetArg(""First value""), " + expression + @", GetArg(""Unrelated parameter 4"")); C GetReceiver() { Console.WriteLine(""GetReceiver""); return new C() { Prop = ""Prop"" }; } string GetArg(string s) { Console.WriteLine(s); return s; } public class C { public string Prop { get; set; } public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""s1:"" + s1); _builder.AppendLine(""c.Prop:"" + c.Prop); _builder.AppendLine(""s2:"" + s2); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @" GetReceiver Unrelated parameter 1 Second value Unrelated parameter 2 First value Handler constructor Unrelated parameter 4 s1:First value c.Prop:Prop s2:Second value literal:literal "); verifier.VerifyDiagnostics(); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$""literal"" + $""""")] public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression) { var code = @" using System; using System.Globalization; using System.Runtime.CompilerServices; int i = 1; C.M(i, " + expression + @"); public class C { public static implicit operator C(int i) => throw null; public static implicit operator C(double d) { Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture)); return new C(); } public override string ToString() => ""C""; public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" 1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 39 (0x27) .maxstack 5 .locals init (double V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: conv.r8 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.7 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""C C.op_Implicit(double)"" IL_000e: call ""CustomHandler..ctor(int, int, C)"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""literal"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: pop IL_0020: ldloc.1 IL_0021: call ""void C.M(double, CustomHandler)"" IL_0026: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { public int Prop { get; set; } public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); return 0; } set { Console.WriteLine(""Indexer setter""); Console.WriteLine(c.ToString()); } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter GetInt2 Indexer setter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 85 (0x55) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.s V_5 IL_0039: stloc.s V_4 IL_003b: ldloc.2 IL_003c: ldloc.3 IL_003d: ldloc.s V_4 IL_003f: ldloc.2 IL_0040: ldloc.3 IL_0041: ldloc.s V_4 IL_0043: callvirt ""int C.this[int, CustomHandler].get"" IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: callvirt ""void C.this[int, CustomHandler].set"" IL_0054: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 95 (0x5f) .maxstack 6 .locals init (int V_0, //i CustomHandler V_1, bool V_2, int V_3, C V_4, int V_5, CustomHandler V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.s V_4 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.3 IL_0010: ldloc.3 IL_0011: stloc.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.3 IL_0016: ldloc.s V_4 IL_0018: ldloca.s V_2 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001f: stloc.1 IL_0020: ldloc.2 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_1 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.1 IL_003f: stloc.s V_6 IL_0041: ldloc.s V_4 IL_0043: ldloc.s V_5 IL_0045: ldloc.s V_6 IL_0047: ldloc.s V_4 IL_0049: ldloc.s V_5 IL_004b: ldloc.s V_6 IL_004d: callvirt ""int C.this[int, CustomHandler].get"" IL_0052: ldc.i4.2 IL_0053: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0058: add IL_0059: callvirt ""void C.this[int, CustomHandler].set"" IL_005e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 91 (0x5b) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_5 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.s V_5 IL_003f: stloc.s V_4 IL_0041: ldloc.2 IL_0042: ldloc.3 IL_0043: ldloc.s V_4 IL_0045: ldloc.2 IL_0046: ldloc.3 IL_0047: ldloc.s V_4 IL_0049: callvirt ""int C.this[int, CustomHandler].get"" IL_004e: ldc.i4.2 IL_004f: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0054: add IL_0055: callvirt ""void C.this[int, CustomHandler].set"" IL_005a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 97 (0x61) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0041 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: brfalse.s IL_0041 IL_0030: ldloca.s V_5 IL_0032: ldloc.0 IL_0033: box ""int"" IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003f: br.s IL_0042 IL_0041: ldc.i4.0 IL_0042: pop IL_0043: ldloc.s V_5 IL_0045: stloc.s V_4 IL_0047: ldloc.2 IL_0048: ldloc.3 IL_0049: ldloc.s V_4 IL_004b: ldloc.2 IL_004c: ldloc.3 IL_004d: ldloc.s V_4 IL_004f: callvirt ""int C.this[int, CustomHandler].get"" IL_0054: ldc.i4.2 IL_0055: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_005a: add IL_005b: callvirt ""void C.this[int, CustomHandler].set"" IL_0060: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); Console.WriteLine(c.ToString()); return ref field; } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.this[int, CustomHandler].get"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 81 (0x51) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: stloc.3 IL_0012: ldc.i4.7 IL_0013: ldc.i4.1 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: ldloca.s V_5 IL_0018: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001d: stloc.s V_4 IL_001f: ldloc.s V_5 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_4 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.3 IL_003f: ldloc.s V_4 IL_0041: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0046: dup IL_0047: ldind.i4 IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: stind.i4 IL_0050: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC().M(GetInt(1), " + expression + @") += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c) { Console.WriteLine(""M""); Console.WriteLine(c.ToString()); return ref field; } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor M arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.M(int, CustomHandler)"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 81 (0x51) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: stloc.3 IL_0012: ldc.i4.7 IL_0013: ldc.i4.1 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: ldloca.s V_5 IL_0018: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001d: stloc.s V_4 IL_001f: ldloc.s V_5 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_4 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.3 IL_003f: ldloc.s V_4 IL_0041: callvirt ""ref int C.M(int, CustomHandler)"" IL_0046: dup IL_0047: ldind.i4 IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: stind.i4 IL_0050: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.M(int, CustomHandler)"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.M(int, CustomHandler)"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression) { var code = @" using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; _ = new C(1) { " + expression + @" }; public class C : IEnumerable<int> { public int Field; public C(int i) { Field = i; } public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c) { Console.WriteLine(c.ToString()); } public IEnumerator<int> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => throw null; } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 5 .locals init (C V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_1 IL_000a: ldc.i4.7 IL_000b: ldc.i4.0 IL_000c: ldloc.0 IL_000d: call ""CustomHandler..ctor(int, int, C)"" IL_0012: ldloca.s V_1 IL_0014: ldstr ""literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: callvirt ""void C.Add(CustomHandler)"" IL_0024: ret } "); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_DictionaryInitializer(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(1) { [" + expression + @"] = 1 }; public class C { public int Field; public C(int i) { Field = i; } public int this[[InterpolatedStringHandlerArgument("""")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 40 (0x28) .maxstack 4 .locals init (C V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_2 IL_0009: ldc.i4.7 IL_000a: ldc.i4.0 IL_000b: ldloc.0 IL_000c: call ""CustomHandler..ctor(int, int, C)"" IL_0011: ldloca.s V_2 IL_0013: ldstr ""literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloc.2 IL_001e: stloc.1 IL_001f: ldloc.0 IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: callvirt ""void C.this[CustomHandler].set"" IL_0027: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler) { Console.WriteLine(handler.ToString()); } } public partial class CustomHandler { private int I = 0; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""int constructor""); I = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""CustomHandler constructor""); _builder.AppendLine(""c.I:"" + c.I.ToString()); " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c) { _builder.AppendLine(""CustomHandler AppendFormatted""); _builder.Append(c.ToString()); " + (useBoolReturns ? "return true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" int constructor CustomHandler constructor CustomHandler AppendFormatted c.I:1 literal:Inner string value:2 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 59 (0x3b) .maxstack 6 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: dup IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: ldc.i4.s 12 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0017: dup IL_0018: ldstr ""Inner string"" IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: box ""int"" IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: call ""void C.M(int, CustomHandler)"" IL_003a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 77 (0x4d) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_0046 IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0031 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0031: ldloc.s V_4 IL_0033: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0038: ldloc.1 IL_0039: ldc.i4.2 IL_003a: box ""int"" IL_003f: ldc.i4.0 IL_0040: ldnull IL_0041: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0046: ldloc.1 IL_0047: call ""void C.M(int, CustomHandler)"" IL_004c: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 68 (0x44) .maxstack 5 .locals init (int V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldc.i4.s 12 IL_0011: ldc.i4.0 IL_0012: ldloc.2 IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0018: dup IL_0019: ldstr ""Inner string"" IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_0029: brfalse.s IL_003b IL_002b: ldloc.1 IL_002c: ldc.i4.2 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.1 IL_003e: call ""void C.M(int, CustomHandler)"" IL_0043: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0033 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ldloc.s V_4 IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_003c: brfalse.s IL_004e IL_003e: ldloc.1 IL_003f: ldc.i4.2 IL_0040: box ""int"" IL_0045: ldc.i4.0 IL_0046: ldnull IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void DiscardsUsedAsParameters(string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(out _, " + expression + @"); public class C { public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) { i = 0; Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount) { i = 1; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 4 .locals init (int V_0, CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: ldstr ""literal"" IL_0013: call ""void CustomHandler.AppendLiteral(string)"" IL_0018: ldloc.1 IL_0019: call ""void C.M(out int, CustomHandler)"" IL_001e: ret } "); } [Fact] public void DiscardsUsedAsParameters_DefinedInVB() { var vb = @" Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler) Console.WriteLine(i) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer) i = 1 End Sub End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @"C.M(out _, $"""");"; var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() }); var verifier = CompileAndVerify(comp, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: call ""void C.M(out int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DisallowedInExpressionTrees(string expression) { var code = @" using System; using System.Linq.Expressions; Expression<Func<CustomHandler>> expr = () => " + expression + @"; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler }); comp.VerifyDiagnostics( // (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion. // Expression<Func<CustomHandler>> expr = () => $""; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46) ); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_01() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_02() { var code = @" using System.Linq.Expressions; Expression e = (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_03() { var code = @" using System; using System.Linq.Expressions; Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_04() { var code = @" using System; using System.Linq.Expressions; Expression e = Func<string, string> () => (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_05() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 167 (0xa7) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldstr ""literal"" IL_0073: ldtoken ""string"" IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0082: ldtoken ""string string.Concat(string, string)"" IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_008c: castclass ""System.Reflection.MethodInfo"" IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0096: ldc.i4.1 IL_0097: newarr ""System.Linq.Expressions.ParameterExpression"" IL_009c: dup IL_009d: ldc.i4.0 IL_009e: ldloc.0 IL_009f: stelem.ref IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a5: pop IL_00a6: ret } "); } [Theory] [CombinatorialData] public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @", " + expression + @"); public class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString()); } public partial class CustomHandler { private int i; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); this.i = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""c.i:"" + c.i.ToString()); " + (validityParameter ? "success = true;" : "") + @" } }"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", }; } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsFormattableString() { var code = @" M($""{1}"" + $""literal""); System.FormattableString s = $""{1}"" + $""literal""; void M(System.FormattableString s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.FormattableString' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.FormattableString").WithLocation(2, 3), // (3,30): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString' // System.FormattableString s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.FormattableString").WithLocation(3, 30) ); } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsIFormattable() { var code = @" M($""{1}"" + $""literal""); System.IFormattable s = $""{1}"" + $""literal""; void M(System.IFormattable s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.IFormattable' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.IFormattable").WithLocation(2, 3), // (3,25): error CS0029: Cannot implicitly convert type 'string' to 'System.IFormattable' // System.IFormattable s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.IFormattable").WithLocation(3, 25) ); } [Theory] [CombinatorialData] public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression) { var code = @" int i; string s; CustomHandler c = " + expression + @"; _ = i.ToString(); _ = o.ToString(); _ = s.ToString(); string M(out object o) { o = null; return null; } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (6,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5), // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else if (useBoolReturns) { comp.VerifyDiagnostics( // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression) { var code = @" int i; CustomHandler c = " + expression + @"; _ = i.ToString(); "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (5,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_01(string expression) { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_02(string expression) { var code = @" using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount) { Console.WriteLine(""d:"" + d.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "d:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: box ""int"" IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)"" IL_0010: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0015: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(dynamic literalLength, int formattedCount) { Console.WriteLine(""ctor""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: newobj ""CustomHandler..ctor(dynamic, int)"" IL_000c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0011: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { Console.WriteLine(""ctor""); } public CustomHandler(dynamic literalLength, int formattedCount) { throw null; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_000c: ret } "); } [Theory] [InlineData(@"$""Literal""")] [InlineData(@"$"""" + $""Literal""")] public void DynamicConstruction_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_0015: ldloc.0 IL_0016: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001b: ret } "); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""""")] public void DynamicConstruction_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 29 (0x1d) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)"" IL_0016: ldloc.0 IL_0017: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001c: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_08(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 128 (0x80) .maxstack 9 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0021: brtrue.s IL_0062 IL_0023: ldc.i4 0x100 IL_0028: ldstr ""AppendFormatted"" IL_002d: ldnull IL_002e: ldtoken ""Program"" IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0038: ldc.i4.2 IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003e: dup IL_003f: ldc.i4.0 IL_0040: ldc.i4.s 9 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.0 IL_004c: ldnull IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0052: stelem.ref IL_0053: 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_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target"" IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0071: ldloca.s V_1 IL_0073: ldloc.0 IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_0079: ldloc.1 IL_007a: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_007f: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_09(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public bool AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); return true; } public bool AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); return true; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 196 (0xc4) .maxstack 11 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)"" IL_001c: brfalse IL_00bb IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0026: brtrue.s IL_004c IL_0028: ldc.i4.0 IL_0029: ldtoken ""bool"" IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0033: ldtoken ""Program"" IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_0060: brtrue.s IL_009d IL_0062: ldc.i4.0 IL_0063: ldstr ""AppendFormatted"" IL_0068: ldnull IL_0069: ldtoken ""Program"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.2 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.s 9 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: dup IL_0085: ldc.i4.1 IL_0086: ldc.i4.0 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.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00ac: ldloca.s V_1 IL_00ae: ldloc.0 IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00b9: br.s IL_00bc IL_00bb: ldc.i4.0 IL_00bc: pop IL_00bd: ldloc.1 IL_00be: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_00c3: ret } "); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_01(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // return $"{s}"; Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_02(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8150: By-value returns may only be used in methods that return by value // return $"{s}"; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return ref " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // return ref $"{s}"; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { S1 s1; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; } public void AppendFormatted(Span<char> s) => this.s1.s = s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s1, " + expression + @"); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9), // (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23) ); } [Theory] [InlineData(@"$""{s1}""")] [InlineData(@"$""{s1}"" + $""""")] public void RefEscape_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public void AppendFormatted(S1 s1) => s1.s = this.s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s, " + expression + @"); } public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_08() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public static CustomHandler M() { Span<char> s = stackalloc char[10]; ref CustomHandler c = ref M2(ref s, $""""); return c; } public static ref CustomHandler M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] ref CustomHandler handler) { return ref handler; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (16,16): error CS8352: Cannot use local 'c' in this context because it may expose referenced variables outside of their declaration scope // return c; Diagnostic(ErrorCode.ERR_EscapeLocal, "c").WithArguments("c").WithLocation(16, 16) ); } [Fact] public void RefEscape_09() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { s1.Handler = this; } public static void M(ref S1 s1) { Span<char> s2 = stackalloc char[10]; M2(ref s1, $""{s2}""); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler handler) { } public void AppendFormatted(Span<char> s) { this.s = s; } } public ref struct S1 { public CustomHandler Handler; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (15,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s2}"")").WithArguments("CustomHandler.M2(ref S1, CustomHandler)", "handler").WithLocation(15, 9), // (15,23): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(15, 23) ); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_01(string expression) { var code = @" int i = 1; System.Console.WriteLine(" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" { value:1 }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""{ "" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldstr "" }"" IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_002b: ldloca.s V_1 IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_02(string expression) { var code = @" int i = 1; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:{ value:1 alignment:0 format: literal: }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 71 (0x47) .maxstack 4 .locals init (int V_0, //i CustomHandler V_1, //c CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_2 IL_000d: ldstr ""{ "" IL_0012: call ""void CustomHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0026: ldloca.s V_2 IL_0028: ldstr "" }"" IL_002d: call ""void CustomHandler.AppendLiteral(string)"" IL_0032: ldloc.2 IL_0033: stloc.1 IL_0034: ldloca.s V_1 IL_0036: constrained. ""CustomHandler"" IL_003c: callvirt ""string object.ToString()"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ret } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 value:2 value:3 4 "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 66 (0x42) .maxstack 3 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 int V_3, //i4 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldc.i4.4 IL_0007: stloc.3 IL_0008: ldloca.s V_4 IL_000a: ldc.i4.0 IL_000b: ldc.i4.3 IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0011: ldloca.s V_4 IL_0013: ldloc.0 IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0019: ldloca.s V_4 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: ldloca.s V_4 IL_0023: ldloc.2 IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0029: ldloca.s V_4 IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0030: ldloca.s V_3 IL_0032: call ""string int.ToString()"" IL_0037: call ""string string.Concat(string, string)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""({i1}),"" + $""[{i2}],"" + $""{{{i3}}}""")] [InlineData(@"($""({i1}),"" + $""[{i2}],"") + $""{{{i3}}}""")] [InlineData(@"$""({i1}),"" + ($""[{i2}],"" + $""{{{i3}}}"")")] public void InterpolatedStringsAddedUnderObjectAddition2(string expression) { var code = $@" int i1 = 1; int i2 = 2; int i3 = 3; System.Console.WriteLine({expression});"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: @" ( value:1 ), [ value:2 ], { value:3 } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition3() { var code = @" #nullable enable using System; try { var s = string.Empty; Console.WriteLine($""{s = null}{s.Length}"" + $""""); } catch (NullReferenceException) { Console.WriteLine(""Null reference exception caught.""); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: "Null reference exception caught.").VerifyIL("<top-level-statements-entry-point>", @" { // Code size 65 (0x41) .maxstack 3 .locals init (string V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) .try { IL_0000: ldsfld ""string string.Empty"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: ldc.i4.2 IL_0008: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldnull IL_0011: dup IL_0012: stloc.0 IL_0013: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0018: ldloca.s V_1 IL_001a: ldloc.0 IL_001b: callvirt ""int string.Length.get"" IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: ldloca.s V_1 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: call ""void System.Console.WriteLine(string)"" IL_0031: leave.s IL_0040 } catch System.NullReferenceException { IL_0033: pop IL_0034: ldstr ""Null reference exception caught."" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: leave.s IL_0040 } IL_0040: ret } ").VerifyDiagnostics( // (9,36): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine($"{s = null}{s.Length}" + $""); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 36) ); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" object o1; object o2; object o3; _ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1; o1.ToString(); o2.ToString(); o3.ToString(); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); comp.VerifyDiagnostics( // (7,1): error CS0165: Use of unassigned local variable 'o2' // o2.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1), // (8,1): error CS0165: Use of unassigned local variable 'o3' // o3.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1) ); } [Theory] [InlineData(@"($""{i1}"" + $""{i2}"") + $""{i3}""")] [InlineData(@"$""{i1}"" + ($""{i2}"" + $""{i3}"")")] public void ParenthesizedAdditiveExpression_01(string expression) { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 82 (0x52) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 CustomHandler V_3, //c CustomHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldloca.s V_4 IL_0008: ldc.i4.0 IL_0009: ldc.i4.3 IL_000a: call ""CustomHandler..ctor(int, int)"" IL_000f: ldloca.s V_4 IL_0011: ldloc.0 IL_0012: box ""int"" IL_0017: ldc.i4.0 IL_0018: ldnull IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001e: ldloca.s V_4 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002d: ldloca.s V_4 IL_002f: ldloc.2 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldloc.s V_4 IL_003e: stloc.3 IL_003f: ldloca.s V_3 IL_0041: constrained. ""CustomHandler"" IL_0047: callvirt ""string object.ToString()"" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_02() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; CustomHandler c = /*<bind>*/((($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}""))) + (($""{i1}"" + ($""{i2}"" + $""{i3}"")) + (($""{i4}"" + $""{i5}"") + $""{i6}""))/*</bind>*/; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: value:4 alignment:0 format: value:5 alignment:0 format: value:6 alignment:0 format: value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: value:4 alignment:0 format: value:5 alignment:0 format: value:6 alignment:0 format: "); verifier.VerifyDiagnostics(); VerifyOperationTreeForTest<BinaryExpressionSyntax>(comp, @" IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Left: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '(($""{i1}"" + ... + $""{i6}""))') Left: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '($""{i1}"" + ... ) + $""{i3}""') Left: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i1}"" + $""{i2}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i1}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i1}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') 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.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i1}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i1}') 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.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i1}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i1}') 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: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i2}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i2}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i2}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i2}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i2}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i2}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i3}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i3}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i3}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i3}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i3}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i3}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i4}"" + ( ... + $""{i6}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i4}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i4}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i4') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i4}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i4}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i4}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i4}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i5}"" + $""{i6}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i5}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i5}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i5') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') 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.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i5}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i5}') 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.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i5}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i5}') 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: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i6}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i6}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i6') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') 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.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i6}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i6}') 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.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i6}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i6}') 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: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '($""{i1}"" + ... + $""{i6}"")') Left: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i1}"" + ( ... + $""{i3}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i1}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i1}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') 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.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i1}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i1}') 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.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i1}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i1}') 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: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i2}"" + $""{i3}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i2}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i2}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i2}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i2}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i2}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i2}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i3}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i3}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i3}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i3}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i3}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i3}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '($""{i4}"" + ... ) + $""{i6}""') Left: IInterpolatedStringAdditionOperation (OperationKind.InterpolatedStringAddition, Type: null) (Syntax: '$""{i4}"" + $""{i5}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i4}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i4}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i4') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i4}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i4}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i4}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i4}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i5}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i5}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i5') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') 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.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i5}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i5}') 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.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i5}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i5}') 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: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolatedStringAppendOperation (OperationKind.InterpolatedStringAppendFormatted, Type: null, IsImplicit) (Syntax: '{i6}') AppendCall: IInvocationOperation ( void CustomHandler.AppendFormatted(System.Object o, [System.Int32 alignment = 0], [System.String format = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{i6}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: InterpolatedStringHandler) (OperationKind.InstanceReference, Type: CustomHandler, IsImplicit) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i6') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') 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.DefaultValue, Matching Parameter: alignment) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i6}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{i6}') 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.DefaultValue, Matching Parameter: format) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '{i6}') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: '{i6}') 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 ParenthesizedAdditiveExpression_03() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = (($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}"")); System.Console.WriteLine(s);"; var verifier = CompileAndVerify(code, expectedOutput: @"123456"); verifier.VerifyDiagnostics(); } [Fact] public void ParenthesizedAdditiveExpression_04() { var code = @" using System.Threading.Tasks; int i1 = 2; int i2 = 3; string s = $""{await GetInt()}"" + ($""{i1}"" + $""{i2}""); System.Console.WriteLine(s); Task<int> GetInt() => Task.FromResult(1); "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }, expectedOutput: @" 1value:2 value:3"); verifier.VerifyDiagnostics(); // Note the two DefaultInterpolatedStringHandlers in the IL here. In a future rewrite step in the LocalRewriter, we can potentially // transform the tree to change its shape and pull out all individual Append calls in a sequence (regardless of the level of the tree) // and combine these and other unequal tree shapes. For now, we're going with a simple solution where, if the entire binary expression // cannot be combined, none of it is. verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 244 (0xf4) .maxstack 4 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldarg.0 IL_000b: ldc.i4.2 IL_000c: stfld ""int Program.<<Main>$>d__0.<i1>5__2"" IL_0011: ldarg.0 IL_0012: ldc.i4.3 IL_0013: stfld ""int Program.<<Main>$>d__0.<i2>5__3"" IL_0018: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__GetInt|0_0()"" IL_001d: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0022: stloc.2 IL_0023: ldloca.s V_2 IL_0025: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002a: brtrue.s IL_006b IL_002c: ldarg.0 IL_002d: ldc.i4.0 IL_002e: dup IL_002f: stloc.0 IL_0030: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0035: ldarg.0 IL_0036: ldloc.2 IL_0037: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003c: ldarg.0 IL_003d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0042: ldloca.s V_2 IL_0044: ldarg.0 IL_0045: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004a: leave IL_00f3 IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0055: stloc.2 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006b: ldloca.s V_2 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.1 IL_0073: ldstr ""{0}"" IL_0078: ldloc.1 IL_0079: box ""int"" IL_007e: call ""string string.Format(string, object)"" IL_0083: ldc.i4.0 IL_0084: ldc.i4.1 IL_0085: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_008a: stloc.3 IL_008b: ldloca.s V_3 IL_008d: ldarg.0 IL_008e: ldfld ""int Program.<<Main>$>d__0.<i1>5__2"" IL_0093: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0098: ldloca.s V_3 IL_009a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_009f: ldc.i4.0 IL_00a0: ldc.i4.1 IL_00a1: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_00a6: stloc.3 IL_00a7: ldloca.s V_3 IL_00a9: ldarg.0 IL_00aa: ldfld ""int Program.<<Main>$>d__0.<i2>5__3"" IL_00af: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_00b4: ldloca.s V_3 IL_00b6: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00bb: call ""string string.Concat(string, string, string)"" IL_00c0: call ""void System.Console.WriteLine(string)"" IL_00c5: leave.s IL_00e0 } catch System.Exception { IL_00c7: stloc.s V_4 IL_00c9: ldarg.0 IL_00ca: ldc.i4.s -2 IL_00cc: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00d1: ldarg.0 IL_00d2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d7: ldloc.s V_4 IL_00d9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00de: leave.s IL_00f3 } IL_00e0: ldarg.0 IL_00e1: ldc.i4.s -2 IL_00e3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00e8: ldarg.0 IL_00e9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00f3: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_05() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = /*<bind>*/((($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}""))) + (($""{i1}"" + ($""{i2}"" + $""{i3}"")) + (($""{i4}"" + $""{i5}"") + $""{i6}""))/*</bind>*/; System.Console.WriteLine(s);"; var comp = CreateCompilation(code); var verifier = CompileAndVerify(comp, expectedOutput: @"123456123456"); verifier.VerifyDiagnostics(); VerifyOperationTreeForTest<BinaryExpressionSyntax>(comp, @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '(($""{i1}"" + ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... ) + $""{i3}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + $""{i2}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + ( ... + $""{i6}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i5}"" + $""{i6}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... + $""{i6}"")') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + ( ... + $""{i3}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i2}"" + $""{i3}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i4}"" + ... ) + $""{i6}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + $""{i5}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_01(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) = (" + initializer + @"); System.Console.Write(c1.ToString()); System.Console.WriteLine(c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 91 (0x5b) .maxstack 4 .locals init (CustomHandler V_0, //c1 CustomHandler V_1, //c2 CustomHandler V_2, CustomHandler V_3) IL_0000: ldloca.s V_3 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_3 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.0 IL_0012: ldnull IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0018: ldloc.3 IL_0019: stloc.2 IL_001a: ldloca.s V_3 IL_001c: ldc.i4.0 IL_001d: ldc.i4.1 IL_001e: call ""CustomHandler..ctor(int, int)"" IL_0023: ldloca.s V_3 IL_0025: ldc.i4.2 IL_0026: box ""int"" IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0032: ldloc.3 IL_0033: ldloc.2 IL_0034: stloc.0 IL_0035: stloc.1 IL_0036: ldloca.s V_0 IL_0038: constrained. ""CustomHandler"" IL_003e: callvirt ""string object.ToString()"" IL_0043: call ""void System.Console.Write(string)"" IL_0048: ldloca.s V_1 IL_004a: constrained. ""CustomHandler"" IL_0050: callvirt ""string object.ToString()"" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ret } "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_02(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) t = (" + initializer + @"); System.Console.Write(t.c1.ToString()); System.Console.WriteLine(t.c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 104 (0x68) .maxstack 6 .locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldc.i4.1 IL_000e: box ""int"" IL_0013: ldc.i4.0 IL_0014: ldnull IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001a: ldloc.1 IL_001b: ldloca.s V_1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.1 IL_001f: call ""CustomHandler..ctor(int, int)"" IL_0024: ldloca.s V_1 IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0033: ldloc.1 IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)"" IL_0039: ldloca.s V_0 IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1"" IL_0040: constrained. ""CustomHandler"" IL_0046: callvirt ""string object.ToString()"" IL_004b: call ""void System.Console.Write(string)"" IL_0050: ldloca.s V_0 IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2"" IL_0057: constrained. ""CustomHandler"" IL_005d: callvirt ""string object.ToString()"" IL_0062: call ""void System.Console.WriteLine(string)"" IL_0067: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{h1}{h2}""")] [InlineData(@"$""{h1}"" + $""{h2}""")] public void RefStructHandler_DynamicInHole(string expression) { var code = @" dynamic h1 = 1; dynamic h2 = 2; CustomHandler c = " + expression + ";"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "ref struct", useBoolReturns: false); var comp = CreateCompilationWithCSharp(new[] { code, handler }); // Note: We don't give any errors when mixing dynamic and ref structs today. If that ever changes, we should get an // error here. This will crash at runtime because of this. comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Literal{1}""")] [InlineData(@"$""Literal"" + $""{1}""")] public void ConversionInParamsArguments(string expression) { var code = @" using System; using System.Linq; M(" + expression + ", " + expression + @"); void M(params CustomHandler[] handlers) { Console.WriteLine(string.Join(Environment.NewLine, handlers.Select(h => h.ToString()))); } "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, expectedOutput: @" literal:Literal value:1 alignment:0 format: literal:Literal value:1 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 100 (0x64) .maxstack 7 .locals init (CustomHandler V_0) IL_0000: ldc.i4.2 IL_0001: newarr ""CustomHandler"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: ldc.i4.7 IL_000b: ldc.i4.1 IL_000c: call ""CustomHandler..ctor(int, int)"" IL_0011: ldloca.s V_0 IL_0013: ldstr ""Literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloca.s V_0 IL_001f: ldc.i4.1 IL_0020: box ""int"" IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002c: ldloc.0 IL_002d: stelem ""CustomHandler"" IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldloca.s V_0 IL_0036: ldc.i4.7 IL_0037: ldc.i4.1 IL_0038: call ""CustomHandler..ctor(int, int)"" IL_003d: ldloca.s V_0 IL_003f: ldstr ""Literal"" IL_0044: call ""void CustomHandler.AppendLiteral(string)"" IL_0049: ldloca.s V_0 IL_004b: ldc.i4.1 IL_004c: box ""int"" IL_0051: ldc.i4.0 IL_0052: ldnull IL_0053: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0058: ldloc.0 IL_0059: stelem ""CustomHandler"" IL_005e: call ""void Program.<<Main>$>g__M|0_0(CustomHandler[])"" IL_0063: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_01(string mod) { var code = @" using System.Runtime.CompilerServices; M($""""); " + mod + @" void M([InterpolatedStringHandlerArgument("""")] CustomHandler c) { } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (6,10): error CS8944: 'M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // void M([InterpolatedStringHandlerArgument("")] CustomHandler c) { } Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M(CustomHandler)").WithLocation(6, 10 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; M(1, $""""); " + mod + @" void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_01(string mod) { var code = @" using System.Runtime.CompilerServices; var a = " + mod + @" ([InterpolatedStringHandlerArgument("""")] CustomHandler c) => { }; a($""""); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,12): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument("""")").WithLocation(4, 12 + mod.Length), // (4,12): error CS8944: 'lambda expression' is not an instance method, the receiver cannot be an interpolated string handler argument. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("lambda expression").WithLocation(4, 12 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; var a = " + mod + @" (int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); a(1, $""""); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) => throw null; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @""); verifier.VerifyDiagnostics( // (5,19): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = (int i, [InterpolatedStringHandlerArgument("i")] CustomHandler c) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument(""i"")").WithLocation(5, 19 + mod.Length) ); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 4 IL_0000: ldsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""System.Action<int, CustomHandler>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: newobj ""CustomHandler..ctor(int, int)"" IL_0027: callvirt ""void System.Action<int, CustomHandler>.Invoke(int, CustomHandler)"" IL_002c: ret } "); } [Fact] public void ArgumentsOnDelegateTypes_01() { var code = @" using System.Runtime.CompilerServices; M m = null; m($""""); delegate void M([InterpolatedStringHandlerArgument("""")] CustomHandler c); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(6, 3), // (8,18): error CS8944: 'M.Invoke(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // delegate void M([InterpolatedStringHandlerArgument("")] CustomHandler c); Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M.Invoke(CustomHandler)").WithLocation(8, 18) ); } [Fact] public void ArgumentsOnDelegateTypes_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Delegate Sub M(<InterpolatedStringHandlerArgument("""")> c As CustomHandler) <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @" M m = null; m($""""); "; var comp = CreateCompilation(code, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(4, 3) ); } [Fact] public void ArgumentsOnDelegateTypes_03() { var code = @" using System; using System.Runtime.CompilerServices; M m = (i, c) => Console.WriteLine(c.ToString()); m(1, $""""); delegate void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 5 .locals init (int V_0) IL_0000: ldsfld ""M Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""M..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""M Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: stloc.0 IL_0021: ldloc.0 IL_0022: ldc.i4.0 IL_0023: ldc.i4.0 IL_0024: ldloc.0 IL_0025: newobj ""CustomHandler..ctor(int, int, int)"" IL_002a: callvirt ""void M.Invoke(int, CustomHandler)"" IL_002f: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_01() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private int _i = 0; public CustomHandler(int literalLength, int formattedCount, int i = 1) => _i = i; public override string ToString() => _i.ToString(); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: ldc.i4.1 IL_0003: newobj ""CustomHandler..ctor(int, int, int)"" IL_0008: call ""void C.M(CustomHandler)"" IL_000d: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_02() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""Literal""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, out bool isValid, int i = 1) { _s = i.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (CustomHandler V_0, bool V_1) IL_0000: ldc.i4.7 IL_0001: ldc.i4.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.1 IL_0005: newobj ""CustomHandler..ctor(int, int, out bool, int)"" IL_000a: stloc.0 IL_000b: ldloc.1 IL_000c: brfalse.s IL_001a IL_000e: ldloca.s V_0 IL_0010: ldstr ""Literal"" IL_0015: call ""void CustomHandler.AppendLiteral(string)"" IL_001a: ldloc.0 IL_001b: call ""void C.M(CustomHandler)"" IL_0020: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_03() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, int i2 = 2) { _s = i1.ToString() + i2.ToString(); } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 5 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldc.i4.2 IL_0007: newobj ""CustomHandler..ctor(int, int, int, int)"" IL_000c: call ""void C.M(int, CustomHandler)"" IL_0011: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_04() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""Literal""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, out bool isValid, int i2 = 2) { _s = i1.ToString() + i2.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.7 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: ldc.i4.2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool, int)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_001e IL_0012: ldloca.s V_1 IL_0014: ldstr ""Literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: call ""void C.M(int, CustomHandler)"" IL_0024: ret } "); } [Fact] public void HandlerExtensionMethod_01() { var code = @" $""Test"".M(); public static class StringExt { public static void M(this CustomHandler handler) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (2,1): error CS1929: 'string' does not contain a definition for 'M' and the best extension method overload 'StringExt.M(CustomHandler)' requires a receiver of type 'CustomHandler' // $"Test".M(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$""Test""").WithArguments("string", "M", "StringExt.M(CustomHandler)", "CustomHandler").WithLocation(2, 1) ); } [Fact] public void HandlerExtensionMethod_02() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument("""")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // s.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(5, 5), // (14,38): error CS8944: 'S1Ext.M(S1, CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M(this S1 s, [InterpolatedStringHandlerArgument("")] CustomHandler c) => throw null; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("S1Ext.M(S1, CustomHandler)").WithLocation(14, 38) ); } [Fact] public void HandlerExtensionMethod_03() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1"); verifier.VerifyDiagnostics(); } [Fact] public void HandlerExtensionMethod_04() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(ref this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(s.Field); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S1 s) : this(literalLength, formattedCount) => s.Field = 2; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 25 (0x19) .maxstack 4 .locals init (S1 V_0, //s S1& V_1) IL_0000: ldloca.s V_0 IL_0002: call ""S1..ctor()"" IL_0007: ldloca.s V_0 IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: ldloc.1 IL_000e: newobj ""CustomHandler..ctor(int, int, ref S1)"" IL_0013: call ""void S1Ext.M(ref S1, CustomHandler)"" IL_0018: ret } "); } [Fact] public void HandlerExtensionMethod_05() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(in this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 25 (0x19) .maxstack 4 .locals init (S1 V_0, //s S1& V_1) IL_0000: ldloca.s V_0 IL_0002: call ""S1..ctor()"" IL_0007: ldloca.s V_0 IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: ldloc.1 IL_000e: newobj ""CustomHandler..ctor(int, int, in S1)"" IL_0013: call ""void S1Ext.M(in S1, CustomHandler)"" IL_0018: ret } "); } [Fact] public void HandlerExtensionMethod_06() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(in this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,1): error CS1620: Argument 3 must be passed with the 'ref' keyword // s.M($""); Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("3", "ref").WithLocation(5, 1) ); } [Fact] public void HandlerExtensionMethod_07() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(ref this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,1): error CS1615: Argument 3 may not be passed with the 'ref' keyword // s.M($""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("3", "ref").WithLocation(5, 1) ); } [Fact] public void NoStandaloneConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,19): error CS7036: There is no argument given that corresponds to the required formal parameter 's' of 'CustomHandler.CustomHandler(int, int, string)' // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("s", "CustomHandler.CustomHandler(int, int, string)").WithLocation(4, 19), // (4,19): error CS1615: Argument 3 may not be passed with the 'out' keyword // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(4, 19) ); } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/Generated/OperationKind.Generated.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // < auto-generated /> #nullable enable using System; using System.ComponentModel; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { /// <summary> /// All of the kinds of operations, including statements and expressions. /// </summary> public enum OperationKind { /// <summary>Indicates an <see cref="IOperation"/> for a construct that is not implemented yet.</summary> None = 0x0, /// <summary>Indicates an <see cref="IInvalidOperation"/>.</summary> Invalid = 0x1, /// <summary>Indicates an <see cref="IBlockOperation"/>.</summary> Block = 0x2, /// <summary>Indicates an <see cref="IVariableDeclarationGroupOperation"/>.</summary> VariableDeclarationGroup = 0x3, /// <summary>Indicates an <see cref="ISwitchOperation"/>.</summary> Switch = 0x4, /// <summary>Indicates an <see cref="ILoopOperation"/>. This is further differentiated by <see cref="ILoopOperation.LoopKind"/>.</summary> Loop = 0x5, /// <summary>Indicates an <see cref="ILabeledOperation"/>.</summary> Labeled = 0x6, /// <summary>Indicates an <see cref="IBranchOperation"/>.</summary> Branch = 0x7, /// <summary>Indicates an <see cref="IEmptyOperation"/>.</summary> Empty = 0x8, /// <summary>Indicates an <see cref="IReturnOperation"/>.</summary> Return = 0x9, /// <summary>Indicates an <see cref="IReturnOperation"/>. This has yield break semantics.</summary> YieldBreak = 0xa, /// <summary>Indicates an <see cref="ILockOperation"/>.</summary> Lock = 0xb, /// <summary>Indicates an <see cref="ITryOperation"/>.</summary> Try = 0xc, /// <summary>Indicates an <see cref="IUsingOperation"/>.</summary> Using = 0xd, /// <summary>Indicates an <see cref="IReturnOperation"/>. This has yield return semantics.</summary> YieldReturn = 0xe, /// <summary>Indicates an <see cref="IExpressionStatementOperation"/>.</summary> ExpressionStatement = 0xf, /// <summary>Indicates an <see cref="ILocalFunctionOperation"/>.</summary> LocalFunction = 0x10, /// <summary>Indicates an <see cref="IStopOperation"/>.</summary> Stop = 0x11, /// <summary>Indicates an <see cref="IEndOperation"/>.</summary> End = 0x12, /// <summary>Indicates an <see cref="IRaiseEventOperation"/>.</summary> RaiseEvent = 0x13, /// <summary>Indicates an <see cref="ILiteralOperation"/>.</summary> Literal = 0x14, /// <summary>Indicates an <see cref="IConversionOperation"/>.</summary> Conversion = 0x15, /// <summary>Indicates an <see cref="IInvocationOperation"/>.</summary> Invocation = 0x16, /// <summary>Indicates an <see cref="IArrayElementReferenceOperation"/>.</summary> ArrayElementReference = 0x17, /// <summary>Indicates an <see cref="ILocalReferenceOperation"/>.</summary> LocalReference = 0x18, /// <summary>Indicates an <see cref="IParameterReferenceOperation"/>.</summary> ParameterReference = 0x19, /// <summary>Indicates an <see cref="IFieldReferenceOperation"/>.</summary> FieldReference = 0x1a, /// <summary>Indicates an <see cref="IMethodReferenceOperation"/>.</summary> MethodReference = 0x1b, /// <summary>Indicates an <see cref="IPropertyReferenceOperation"/>.</summary> PropertyReference = 0x1c, // Unused: 1d /// <summary>Indicates an <see cref="IEventReferenceOperation"/>.</summary> EventReference = 0x1e, /// <summary>Indicates an <see cref="IUnaryOperation"/>.</summary> Unary = 0x1f, /// <summary>Indicates an <see cref="IUnaryOperation"/>. Use <see cref="Unary"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] UnaryOperator = 0x1f, /// <summary>Indicates an <see cref="IBinaryOperation"/>.</summary> Binary = 0x20, /// <summary>Indicates an <see cref="IBinaryOperation"/>. Use <see cref="Binary"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] BinaryOperator = 0x20, /// <summary>Indicates an <see cref="IConditionalOperation"/>.</summary> Conditional = 0x21, /// <summary>Indicates an <see cref="ICoalesceOperation"/>.</summary> Coalesce = 0x22, /// <summary>Indicates an <see cref="IAnonymousFunctionOperation"/>.</summary> AnonymousFunction = 0x23, /// <summary>Indicates an <see cref="IObjectCreationOperation"/>.</summary> ObjectCreation = 0x24, /// <summary>Indicates an <see cref="ITypeParameterObjectCreationOperation"/>.</summary> TypeParameterObjectCreation = 0x25, /// <summary>Indicates an <see cref="IArrayCreationOperation"/>.</summary> ArrayCreation = 0x26, /// <summary>Indicates an <see cref="IInstanceReferenceOperation"/>.</summary> InstanceReference = 0x27, /// <summary>Indicates an <see cref="IIsTypeOperation"/>.</summary> IsType = 0x28, /// <summary>Indicates an <see cref="IAwaitOperation"/>.</summary> Await = 0x29, /// <summary>Indicates an <see cref="ISimpleAssignmentOperation"/>.</summary> SimpleAssignment = 0x2a, /// <summary>Indicates an <see cref="ICompoundAssignmentOperation"/>.</summary> CompoundAssignment = 0x2b, /// <summary>Indicates an <see cref="IParenthesizedOperation"/>.</summary> Parenthesized = 0x2c, /// <summary>Indicates an <see cref="IEventAssignmentOperation"/>.</summary> EventAssignment = 0x2d, /// <summary>Indicates an <see cref="IConditionalAccessOperation"/>.</summary> ConditionalAccess = 0x2e, /// <summary>Indicates an <see cref="IConditionalAccessInstanceOperation"/>.</summary> ConditionalAccessInstance = 0x2f, /// <summary>Indicates an <see cref="IInterpolatedStringOperation"/>.</summary> InterpolatedString = 0x30, /// <summary>Indicates an <see cref="IAnonymousObjectCreationOperation"/>.</summary> AnonymousObjectCreation = 0x31, /// <summary>Indicates an <see cref="IObjectOrCollectionInitializerOperation"/>.</summary> ObjectOrCollectionInitializer = 0x32, /// <summary>Indicates an <see cref="IMemberInitializerOperation"/>.</summary> MemberInitializer = 0x33, /// <summary>Indicates an <see cref="ICollectionElementInitializerOperation"/>.</summary> [Obsolete("ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation), error: true)] CollectionElementInitializer = 0x34, /// <summary>Indicates an <see cref="INameOfOperation"/>.</summary> NameOf = 0x35, /// <summary>Indicates an <see cref="ITupleOperation"/>.</summary> Tuple = 0x36, /// <summary>Indicates an <see cref="IDynamicObjectCreationOperation"/>.</summary> DynamicObjectCreation = 0x37, /// <summary>Indicates an <see cref="IDynamicMemberReferenceOperation"/>.</summary> DynamicMemberReference = 0x38, /// <summary>Indicates an <see cref="IDynamicInvocationOperation"/>.</summary> DynamicInvocation = 0x39, /// <summary>Indicates an <see cref="IDynamicIndexerAccessOperation"/>.</summary> DynamicIndexerAccess = 0x3a, /// <summary>Indicates an <see cref="ITranslatedQueryOperation"/>.</summary> TranslatedQuery = 0x3b, /// <summary>Indicates an <see cref="IDelegateCreationOperation"/>.</summary> DelegateCreation = 0x3c, /// <summary>Indicates an <see cref="IDefaultValueOperation"/>.</summary> DefaultValue = 0x3d, /// <summary>Indicates an <see cref="ITypeOfOperation"/>.</summary> TypeOf = 0x3e, /// <summary>Indicates an <see cref="ISizeOfOperation"/>.</summary> SizeOf = 0x3f, /// <summary>Indicates an <see cref="IAddressOfOperation"/>.</summary> AddressOf = 0x40, /// <summary>Indicates an <see cref="IIsPatternOperation"/>.</summary> IsPattern = 0x41, /// <summary>Indicates an <see cref="IIncrementOrDecrementOperation"/>. This is used as an increment operator</summary> Increment = 0x42, /// <summary>Indicates an <see cref="IThrowOperation"/>.</summary> Throw = 0x43, /// <summary>Indicates an <see cref="IIncrementOrDecrementOperation"/>. This is used as a decrement operator</summary> Decrement = 0x44, /// <summary>Indicates an <see cref="IDeconstructionAssignmentOperation"/>.</summary> DeconstructionAssignment = 0x45, /// <summary>Indicates an <see cref="IDeclarationExpressionOperation"/>.</summary> DeclarationExpression = 0x46, /// <summary>Indicates an <see cref="IOmittedArgumentOperation"/>.</summary> OmittedArgument = 0x47, /// <summary>Indicates an <see cref="IFieldInitializerOperation"/>.</summary> FieldInitializer = 0x48, /// <summary>Indicates an <see cref="IVariableInitializerOperation"/>.</summary> VariableInitializer = 0x49, /// <summary>Indicates an <see cref="IPropertyInitializerOperation"/>.</summary> PropertyInitializer = 0x4a, /// <summary>Indicates an <see cref="IParameterInitializerOperation"/>.</summary> ParameterInitializer = 0x4b, /// <summary>Indicates an <see cref="IArrayInitializerOperation"/>.</summary> ArrayInitializer = 0x4c, /// <summary>Indicates an <see cref="IVariableDeclaratorOperation"/>.</summary> VariableDeclarator = 0x4d, /// <summary>Indicates an <see cref="IVariableDeclarationOperation"/>.</summary> VariableDeclaration = 0x4e, /// <summary>Indicates an <see cref="IArgumentOperation"/>.</summary> Argument = 0x4f, /// <summary>Indicates an <see cref="ICatchClauseOperation"/>.</summary> CatchClause = 0x50, /// <summary>Indicates an <see cref="ISwitchCaseOperation"/>.</summary> SwitchCase = 0x51, /// <summary>Indicates an <see cref="ICaseClauseOperation"/>. This is further differentiated by <see cref="ICaseClauseOperation.CaseKind"/>.</summary> CaseClause = 0x52, /// <summary>Indicates an <see cref="IInterpolatedStringTextOperation"/>.</summary> InterpolatedStringText = 0x53, /// <summary>Indicates an <see cref="IInterpolationOperation"/>.</summary> Interpolation = 0x54, /// <summary>Indicates an <see cref="IConstantPatternOperation"/>.</summary> ConstantPattern = 0x55, /// <summary>Indicates an <see cref="IDeclarationPatternOperation"/>.</summary> DeclarationPattern = 0x56, /// <summary>Indicates an <see cref="ITupleBinaryOperation"/>.</summary> TupleBinary = 0x57, /// <summary>Indicates an <see cref="ITupleBinaryOperation"/>. Use <see cref="TupleBinary"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] TupleBinaryOperator = 0x57, /// <summary>Indicates an <see cref="IMethodBodyOperation"/>.</summary> MethodBody = 0x58, /// <summary>Indicates an <see cref="IMethodBodyOperation"/>. Use <see cref="MethodBody"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] MethodBodyOperation = 0x58, /// <summary>Indicates an <see cref="IConstructorBodyOperation"/>.</summary> ConstructorBody = 0x59, /// <summary>Indicates an <see cref="IConstructorBodyOperation"/>. Use <see cref="ConstructorBody"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] ConstructorBodyOperation = 0x59, /// <summary>Indicates an <see cref="IDiscardOperation"/>.</summary> Discard = 0x5a, /// <summary>Indicates an <see cref="IFlowCaptureOperation"/>.</summary> FlowCapture = 0x5b, /// <summary>Indicates an <see cref="IFlowCaptureReferenceOperation"/>.</summary> FlowCaptureReference = 0x5c, /// <summary>Indicates an <see cref="IIsNullOperation"/>.</summary> IsNull = 0x5d, /// <summary>Indicates an <see cref="ICaughtExceptionOperation"/>.</summary> CaughtException = 0x5e, /// <summary>Indicates an <see cref="IStaticLocalInitializationSemaphoreOperation"/>.</summary> StaticLocalInitializationSemaphore = 0x5f, /// <summary>Indicates an <see cref="IFlowAnonymousFunctionOperation"/>.</summary> FlowAnonymousFunction = 0x60, /// <summary>Indicates an <see cref="ICoalesceAssignmentOperation"/>.</summary> CoalesceAssignment = 0x61, // Unused: 62 /// <summary>Indicates an <see cref="IRangeOperation"/>.</summary> Range = 0x63, // Unused: 64 /// <summary>Indicates an <see cref="IReDimOperation"/>.</summary> ReDim = 0x65, /// <summary>Indicates an <see cref="IReDimClauseOperation"/>.</summary> ReDimClause = 0x66, /// <summary>Indicates an <see cref="IRecursivePatternOperation"/>.</summary> RecursivePattern = 0x67, /// <summary>Indicates an <see cref="IDiscardPatternOperation"/>.</summary> DiscardPattern = 0x68, /// <summary>Indicates an <see cref="ISwitchExpressionOperation"/>.</summary> SwitchExpression = 0x69, /// <summary>Indicates an <see cref="ISwitchExpressionArmOperation"/>.</summary> SwitchExpressionArm = 0x6a, /// <summary>Indicates an <see cref="IPropertySubpatternOperation"/>.</summary> PropertySubpattern = 0x6b, /// <summary>Indicates an <see cref="IUsingDeclarationOperation"/>.</summary> UsingDeclaration = 0x6c, /// <summary>Indicates an <see cref="INegatedPatternOperation"/>.</summary> NegatedPattern = 0x6d, /// <summary>Indicates an <see cref="IBinaryPatternOperation"/>.</summary> BinaryPattern = 0x6e, /// <summary>Indicates an <see cref="ITypePatternOperation"/>.</summary> TypePattern = 0x6f, /// <summary>Indicates an <see cref="IRelationalPatternOperation"/>.</summary> RelationalPattern = 0x70, /// <summary>Indicates an <see cref="IWithOperation"/>.</summary> With = 0x71, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // < auto-generated /> #nullable enable using System; using System.ComponentModel; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { /// <summary> /// All of the kinds of operations, including statements and expressions. /// </summary> public enum OperationKind { /// <summary>Indicates an <see cref="IOperation"/> for a construct that is not implemented yet.</summary> None = 0x0, /// <summary>Indicates an <see cref="IInvalidOperation"/>.</summary> Invalid = 0x1, /// <summary>Indicates an <see cref="IBlockOperation"/>.</summary> Block = 0x2, /// <summary>Indicates an <see cref="IVariableDeclarationGroupOperation"/>.</summary> VariableDeclarationGroup = 0x3, /// <summary>Indicates an <see cref="ISwitchOperation"/>.</summary> Switch = 0x4, /// <summary>Indicates an <see cref="ILoopOperation"/>. This is further differentiated by <see cref="ILoopOperation.LoopKind"/>.</summary> Loop = 0x5, /// <summary>Indicates an <see cref="ILabeledOperation"/>.</summary> Labeled = 0x6, /// <summary>Indicates an <see cref="IBranchOperation"/>.</summary> Branch = 0x7, /// <summary>Indicates an <see cref="IEmptyOperation"/>.</summary> Empty = 0x8, /// <summary>Indicates an <see cref="IReturnOperation"/>.</summary> Return = 0x9, /// <summary>Indicates an <see cref="IReturnOperation"/>. This has yield break semantics.</summary> YieldBreak = 0xa, /// <summary>Indicates an <see cref="ILockOperation"/>.</summary> Lock = 0xb, /// <summary>Indicates an <see cref="ITryOperation"/>.</summary> Try = 0xc, /// <summary>Indicates an <see cref="IUsingOperation"/>.</summary> Using = 0xd, /// <summary>Indicates an <see cref="IReturnOperation"/>. This has yield return semantics.</summary> YieldReturn = 0xe, /// <summary>Indicates an <see cref="IExpressionStatementOperation"/>.</summary> ExpressionStatement = 0xf, /// <summary>Indicates an <see cref="ILocalFunctionOperation"/>.</summary> LocalFunction = 0x10, /// <summary>Indicates an <see cref="IStopOperation"/>.</summary> Stop = 0x11, /// <summary>Indicates an <see cref="IEndOperation"/>.</summary> End = 0x12, /// <summary>Indicates an <see cref="IRaiseEventOperation"/>.</summary> RaiseEvent = 0x13, /// <summary>Indicates an <see cref="ILiteralOperation"/>.</summary> Literal = 0x14, /// <summary>Indicates an <see cref="IConversionOperation"/>.</summary> Conversion = 0x15, /// <summary>Indicates an <see cref="IInvocationOperation"/>.</summary> Invocation = 0x16, /// <summary>Indicates an <see cref="IArrayElementReferenceOperation"/>.</summary> ArrayElementReference = 0x17, /// <summary>Indicates an <see cref="ILocalReferenceOperation"/>.</summary> LocalReference = 0x18, /// <summary>Indicates an <see cref="IParameterReferenceOperation"/>.</summary> ParameterReference = 0x19, /// <summary>Indicates an <see cref="IFieldReferenceOperation"/>.</summary> FieldReference = 0x1a, /// <summary>Indicates an <see cref="IMethodReferenceOperation"/>.</summary> MethodReference = 0x1b, /// <summary>Indicates an <see cref="IPropertyReferenceOperation"/>.</summary> PropertyReference = 0x1c, // Unused: 1d /// <summary>Indicates an <see cref="IEventReferenceOperation"/>.</summary> EventReference = 0x1e, /// <summary>Indicates an <see cref="IUnaryOperation"/>.</summary> Unary = 0x1f, /// <summary>Indicates an <see cref="IUnaryOperation"/>. Use <see cref="Unary"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] UnaryOperator = 0x1f, /// <summary>Indicates an <see cref="IBinaryOperation"/>.</summary> Binary = 0x20, /// <summary>Indicates an <see cref="IBinaryOperation"/>. Use <see cref="Binary"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] BinaryOperator = 0x20, /// <summary>Indicates an <see cref="IConditionalOperation"/>.</summary> Conditional = 0x21, /// <summary>Indicates an <see cref="ICoalesceOperation"/>.</summary> Coalesce = 0x22, /// <summary>Indicates an <see cref="IAnonymousFunctionOperation"/>.</summary> AnonymousFunction = 0x23, /// <summary>Indicates an <see cref="IObjectCreationOperation"/>.</summary> ObjectCreation = 0x24, /// <summary>Indicates an <see cref="ITypeParameterObjectCreationOperation"/>.</summary> TypeParameterObjectCreation = 0x25, /// <summary>Indicates an <see cref="IArrayCreationOperation"/>.</summary> ArrayCreation = 0x26, /// <summary>Indicates an <see cref="IInstanceReferenceOperation"/>.</summary> InstanceReference = 0x27, /// <summary>Indicates an <see cref="IIsTypeOperation"/>.</summary> IsType = 0x28, /// <summary>Indicates an <see cref="IAwaitOperation"/>.</summary> Await = 0x29, /// <summary>Indicates an <see cref="ISimpleAssignmentOperation"/>.</summary> SimpleAssignment = 0x2a, /// <summary>Indicates an <see cref="ICompoundAssignmentOperation"/>.</summary> CompoundAssignment = 0x2b, /// <summary>Indicates an <see cref="IParenthesizedOperation"/>.</summary> Parenthesized = 0x2c, /// <summary>Indicates an <see cref="IEventAssignmentOperation"/>.</summary> EventAssignment = 0x2d, /// <summary>Indicates an <see cref="IConditionalAccessOperation"/>.</summary> ConditionalAccess = 0x2e, /// <summary>Indicates an <see cref="IConditionalAccessInstanceOperation"/>.</summary> ConditionalAccessInstance = 0x2f, /// <summary>Indicates an <see cref="IInterpolatedStringOperation"/>.</summary> InterpolatedString = 0x30, /// <summary>Indicates an <see cref="IAnonymousObjectCreationOperation"/>.</summary> AnonymousObjectCreation = 0x31, /// <summary>Indicates an <see cref="IObjectOrCollectionInitializerOperation"/>.</summary> ObjectOrCollectionInitializer = 0x32, /// <summary>Indicates an <see cref="IMemberInitializerOperation"/>.</summary> MemberInitializer = 0x33, /// <summary>Indicates an <see cref="ICollectionElementInitializerOperation"/>.</summary> [Obsolete("ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation), error: true)] CollectionElementInitializer = 0x34, /// <summary>Indicates an <see cref="INameOfOperation"/>.</summary> NameOf = 0x35, /// <summary>Indicates an <see cref="ITupleOperation"/>.</summary> Tuple = 0x36, /// <summary>Indicates an <see cref="IDynamicObjectCreationOperation"/>.</summary> DynamicObjectCreation = 0x37, /// <summary>Indicates an <see cref="IDynamicMemberReferenceOperation"/>.</summary> DynamicMemberReference = 0x38, /// <summary>Indicates an <see cref="IDynamicInvocationOperation"/>.</summary> DynamicInvocation = 0x39, /// <summary>Indicates an <see cref="IDynamicIndexerAccessOperation"/>.</summary> DynamicIndexerAccess = 0x3a, /// <summary>Indicates an <see cref="ITranslatedQueryOperation"/>.</summary> TranslatedQuery = 0x3b, /// <summary>Indicates an <see cref="IDelegateCreationOperation"/>.</summary> DelegateCreation = 0x3c, /// <summary>Indicates an <see cref="IDefaultValueOperation"/>.</summary> DefaultValue = 0x3d, /// <summary>Indicates an <see cref="ITypeOfOperation"/>.</summary> TypeOf = 0x3e, /// <summary>Indicates an <see cref="ISizeOfOperation"/>.</summary> SizeOf = 0x3f, /// <summary>Indicates an <see cref="IAddressOfOperation"/>.</summary> AddressOf = 0x40, /// <summary>Indicates an <see cref="IIsPatternOperation"/>.</summary> IsPattern = 0x41, /// <summary>Indicates an <see cref="IIncrementOrDecrementOperation"/>. This is used as an increment operator</summary> Increment = 0x42, /// <summary>Indicates an <see cref="IThrowOperation"/>.</summary> Throw = 0x43, /// <summary>Indicates an <see cref="IIncrementOrDecrementOperation"/>. This is used as a decrement operator</summary> Decrement = 0x44, /// <summary>Indicates an <see cref="IDeconstructionAssignmentOperation"/>.</summary> DeconstructionAssignment = 0x45, /// <summary>Indicates an <see cref="IDeclarationExpressionOperation"/>.</summary> DeclarationExpression = 0x46, /// <summary>Indicates an <see cref="IOmittedArgumentOperation"/>.</summary> OmittedArgument = 0x47, /// <summary>Indicates an <see cref="IFieldInitializerOperation"/>.</summary> FieldInitializer = 0x48, /// <summary>Indicates an <see cref="IVariableInitializerOperation"/>.</summary> VariableInitializer = 0x49, /// <summary>Indicates an <see cref="IPropertyInitializerOperation"/>.</summary> PropertyInitializer = 0x4a, /// <summary>Indicates an <see cref="IParameterInitializerOperation"/>.</summary> ParameterInitializer = 0x4b, /// <summary>Indicates an <see cref="IArrayInitializerOperation"/>.</summary> ArrayInitializer = 0x4c, /// <summary>Indicates an <see cref="IVariableDeclaratorOperation"/>.</summary> VariableDeclarator = 0x4d, /// <summary>Indicates an <see cref="IVariableDeclarationOperation"/>.</summary> VariableDeclaration = 0x4e, /// <summary>Indicates an <see cref="IArgumentOperation"/>.</summary> Argument = 0x4f, /// <summary>Indicates an <see cref="ICatchClauseOperation"/>.</summary> CatchClause = 0x50, /// <summary>Indicates an <see cref="ISwitchCaseOperation"/>.</summary> SwitchCase = 0x51, /// <summary>Indicates an <see cref="ICaseClauseOperation"/>. This is further differentiated by <see cref="ICaseClauseOperation.CaseKind"/>.</summary> CaseClause = 0x52, /// <summary>Indicates an <see cref="IInterpolatedStringTextOperation"/>.</summary> InterpolatedStringText = 0x53, /// <summary>Indicates an <see cref="IInterpolationOperation"/>.</summary> Interpolation = 0x54, /// <summary>Indicates an <see cref="IConstantPatternOperation"/>.</summary> ConstantPattern = 0x55, /// <summary>Indicates an <see cref="IDeclarationPatternOperation"/>.</summary> DeclarationPattern = 0x56, /// <summary>Indicates an <see cref="ITupleBinaryOperation"/>.</summary> TupleBinary = 0x57, /// <summary>Indicates an <see cref="ITupleBinaryOperation"/>. Use <see cref="TupleBinary"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] TupleBinaryOperator = 0x57, /// <summary>Indicates an <see cref="IMethodBodyOperation"/>.</summary> MethodBody = 0x58, /// <summary>Indicates an <see cref="IMethodBodyOperation"/>. Use <see cref="MethodBody"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] MethodBodyOperation = 0x58, /// <summary>Indicates an <see cref="IConstructorBodyOperation"/>.</summary> ConstructorBody = 0x59, /// <summary>Indicates an <see cref="IConstructorBodyOperation"/>. Use <see cref="ConstructorBody"/> instead.</summary> [EditorBrowsable(EditorBrowsableState.Never)] ConstructorBodyOperation = 0x59, /// <summary>Indicates an <see cref="IDiscardOperation"/>.</summary> Discard = 0x5a, /// <summary>Indicates an <see cref="IFlowCaptureOperation"/>.</summary> FlowCapture = 0x5b, /// <summary>Indicates an <see cref="IFlowCaptureReferenceOperation"/>.</summary> FlowCaptureReference = 0x5c, /// <summary>Indicates an <see cref="IIsNullOperation"/>.</summary> IsNull = 0x5d, /// <summary>Indicates an <see cref="ICaughtExceptionOperation"/>.</summary> CaughtException = 0x5e, /// <summary>Indicates an <see cref="IStaticLocalInitializationSemaphoreOperation"/>.</summary> StaticLocalInitializationSemaphore = 0x5f, /// <summary>Indicates an <see cref="IFlowAnonymousFunctionOperation"/>.</summary> FlowAnonymousFunction = 0x60, /// <summary>Indicates an <see cref="ICoalesceAssignmentOperation"/>.</summary> CoalesceAssignment = 0x61, // Unused: 62 /// <summary>Indicates an <see cref="IRangeOperation"/>.</summary> Range = 0x63, // Unused: 64 /// <summary>Indicates an <see cref="IReDimOperation"/>.</summary> ReDim = 0x65, /// <summary>Indicates an <see cref="IReDimClauseOperation"/>.</summary> ReDimClause = 0x66, /// <summary>Indicates an <see cref="IRecursivePatternOperation"/>.</summary> RecursivePattern = 0x67, /// <summary>Indicates an <see cref="IDiscardPatternOperation"/>.</summary> DiscardPattern = 0x68, /// <summary>Indicates an <see cref="ISwitchExpressionOperation"/>.</summary> SwitchExpression = 0x69, /// <summary>Indicates an <see cref="ISwitchExpressionArmOperation"/>.</summary> SwitchExpressionArm = 0x6a, /// <summary>Indicates an <see cref="IPropertySubpatternOperation"/>.</summary> PropertySubpattern = 0x6b, /// <summary>Indicates an <see cref="IUsingDeclarationOperation"/>.</summary> UsingDeclaration = 0x6c, /// <summary>Indicates an <see cref="INegatedPatternOperation"/>.</summary> NegatedPattern = 0x6d, /// <summary>Indicates an <see cref="IBinaryPatternOperation"/>.</summary> BinaryPattern = 0x6e, /// <summary>Indicates an <see cref="ITypePatternOperation"/>.</summary> TypePattern = 0x6f, /// <summary>Indicates an <see cref="IRelationalPatternOperation"/>.</summary> RelationalPattern = 0x70, /// <summary>Indicates an <see cref="IWithOperation"/>.</summary> With = 0x71, /// <summary>Indicates an <see cref="IInterpolatedStringHandlerCreationOperation"/>.</summary> InterpolatedStringHandlerCreation = 0x72, /// <summary>Indicates an <see cref="IInterpolatedStringAdditionOperation"/>.</summary> InterpolatedStringAddition = 0x73, /// <summary>Indicates an <see cref="IInterpolatedStringAppendOperation"/>. This append is of a literal component</summary> InterpolatedStringAppendLiteral = 0x74, /// <summary>Indicates an <see cref="IInterpolatedStringAppendOperation"/>. This append is of an interpolation component</summary> InterpolatedStringAppendFormatted = 0x75, /// <summary>Indicates an <see cref="IInterpolatedStringAppendOperation"/>. This append is invalid</summary> InterpolatedStringAppendInvalid = 0x76, /// <summary>Indicates an <see cref="IInterpolatedStringHandlerArgumentPlaceholderOperation"/>.</summary> InterpolatedStringHandlerArgumentPlaceholder = 0x77, } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/Generated/Operations.Generated.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // < auto-generated /> #nullable enable using System; using System.Collections.Generic; using System.Threading; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { #region Interfaces /// <summary> /// Represents an invalid operation with one or more child operations. /// <para> /// Current usage: /// (1) C# invalid expression or invalid statement. /// (2) VB invalid expression or invalid statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Invalid"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInvalidOperation : IOperation { } /// <summary> /// Represents a block containing a sequence of operations and local declarations. /// <para> /// Current usage: /// (1) C# "{ ... }" block statement. /// (2) VB implicit block statement for method bodies and other block scoped statements. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Block"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IBlockOperation : IOperation { /// <summary> /// Operations contained within the block. /// </summary> ImmutableArray<IOperation> Operations { get; } /// <summary> /// Local declarations contained within the block. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } } /// <summary> /// Represents a variable declaration statement. /// </summary> /// <para> /// Current Usage: /// (1) C# local declaration statement /// (2) C# fixed statement /// (3) C# using statement /// (4) C# using declaration /// (5) VB Dim statement /// (6) VB Using statement /// </para> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.VariableDeclarationGroup"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IVariableDeclarationGroupOperation : IOperation { /// <summary> /// Variable declaration in the statement. /// </summary> /// <remarks> /// In C#, this will always be a single declaration, with all variables in <see cref="IVariableDeclarationOperation.Declarators" />. /// </remarks> ImmutableArray<IVariableDeclarationOperation> Declarations { get; } } /// <summary> /// Represents a switch operation with a value to be switched upon and switch cases. /// <para> /// Current usage: /// (1) C# switch statement. /// (2) VB Select Case statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Switch"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISwitchOperation : IOperation { /// <summary> /// Locals declared within the switch operation with scope spanning across all <see cref="Cases" />. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Value to be switched upon. /// </summary> IOperation Value { get; } /// <summary> /// Cases of the switch. /// </summary> ImmutableArray<ISwitchCaseOperation> Cases { get; } /// <summary> /// Exit label for the switch statement. /// </summary> ILabelSymbol ExitLabel { get; } } /// <summary> /// Represents a loop operation. /// <para> /// Current usage: /// (1) C# 'while', 'for', 'foreach' and 'do' loop statements /// (2) VB 'While', 'ForTo', 'ForEach', 'Do While' and 'Do Until' loop statements /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILoopOperation : IOperation { /// <summary> /// Kind of the loop. /// </summary> LoopKind LoopKind { get; } /// <summary> /// Body of the loop. /// </summary> IOperation Body { get; } /// <summary> /// Declared locals. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Loop continue label. /// </summary> ILabelSymbol ContinueLabel { get; } /// <summary> /// Loop exit/break label. /// </summary> ILabelSymbol ExitLabel { get; } } /// <summary> /// Represents a for each loop. /// <para> /// Current usage: /// (1) C# 'foreach' loop statement /// (2) VB 'For Each' loop statement /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IForEachLoopOperation : ILoopOperation { /// <summary> /// Refers to the operation for declaring a new local variable or reference an existing variable or an expression. /// </summary> IOperation LoopControlVariable { get; } /// <summary> /// Collection value over which the loop iterates. /// </summary> IOperation Collection { get; } /// <summary> /// Optional list of comma separated next variables at loop bottom in VB. /// This list is always empty for C#. /// </summary> ImmutableArray<IOperation> NextVariables { get; } /// <summary> /// Whether this for each loop is asynchronous. /// Always false for VB. /// </summary> bool IsAsynchronous { get; } } /// <summary> /// Represents a for loop. /// <para> /// Current usage: /// (1) C# 'for' loop statement /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IForLoopOperation : ILoopOperation { /// <summary> /// List of operations to execute before entry to the loop. For C#, this comes from the first clause of the for statement. /// </summary> ImmutableArray<IOperation> Before { get; } /// <summary> /// Locals declared within the loop Condition and are in scope throughout the <see cref="Condition" />, /// <see cref="ILoopOperation.Body" /> and <see cref="AtLoopBottom" />. /// They are considered to be declared per iteration. /// </summary> ImmutableArray<ILocalSymbol> ConditionLocals { get; } /// <summary> /// Condition of the loop. For C#, this comes from the second clause of the for statement. /// </summary> IOperation? Condition { get; } /// <summary> /// List of operations to execute at the bottom of the loop. For C#, this comes from the third clause of the for statement. /// </summary> ImmutableArray<IOperation> AtLoopBottom { get; } } /// <summary> /// Represents a for to loop with loop control variable and initial, limit and step values for the control variable. /// <para> /// Current usage: /// (1) VB 'For ... To ... Step' loop statement /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IForToLoopOperation : ILoopOperation { /// <summary> /// Refers to the operation for declaring a new local variable or reference an existing variable or an expression. /// </summary> IOperation LoopControlVariable { get; } /// <summary> /// Operation for setting the initial value of the loop control variable. This comes from the expression between the 'For' and 'To' keywords. /// </summary> IOperation InitialValue { get; } /// <summary> /// Operation for the limit value of the loop control variable. This comes from the expression after the 'To' keyword. /// </summary> IOperation LimitValue { get; } /// <summary> /// Operation for the step value of the loop control variable. This comes from the expression after the 'Step' keyword, /// or inferred by the compiler if 'Step' clause is omitted. /// </summary> IOperation StepValue { get; } /// <summary> /// <code>true</code> if arithmetic operations behind this loop are 'checked'. /// </summary> bool IsChecked { get; } /// <summary> /// Optional list of comma separated next variables at loop bottom. /// </summary> ImmutableArray<IOperation> NextVariables { get; } } /// <summary> /// Represents a while or do while loop. /// <para> /// Current usage: /// (1) C# 'while' and 'do while' loop statements. /// (2) VB 'While', 'Do While' and 'Do Until' loop statements. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IWhileLoopOperation : ILoopOperation { /// <summary> /// Condition of the loop. This can only be null in error scenarios. /// </summary> IOperation? Condition { get; } /// <summary> /// True if the <see cref="Condition" /> is evaluated at start of each loop iteration. /// False if it is evaluated at the end of each loop iteration. /// </summary> bool ConditionIsTop { get; } /// <summary> /// True if the loop has 'Until' loop semantics and the loop is executed while <see cref="Condition" /> is false. /// </summary> bool ConditionIsUntil { get; } /// <summary> /// Additional conditional supplied for loop in error cases, which is ignored by the compiler. /// For example, for VB 'Do While' or 'Do Until' loop with syntax errors where both the top and bottom conditions are provided. /// The top condition is preferred and exposed as <see cref="Condition" /> and the bottom condition is ignored and exposed by this property. /// This property should be null for all non-error cases. /// </summary> IOperation? IgnoredCondition { get; } } /// <summary> /// Represents an operation with a label. /// <para> /// Current usage: /// (1) C# labeled statement. /// (2) VB label statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Labeled"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILabeledOperation : IOperation { /// <summary> /// Label that can be the target of branches. /// </summary> ILabelSymbol Label { get; } /// <summary> /// Operation that has been labeled. In VB, this is always null. /// </summary> IOperation? Operation { get; } } /// <summary> /// Represents a branch operation. /// <para> /// Current usage: /// (1) C# goto, break, or continue statement. /// (2) VB GoTo, Exit ***, or Continue *** statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Branch"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IBranchOperation : IOperation { /// <summary> /// Label that is the target of the branch. /// </summary> ILabelSymbol Target { get; } /// <summary> /// Kind of the branch. /// </summary> BranchKind BranchKind { get; } } /// <summary> /// Represents an empty or no-op operation. /// <para> /// Current usage: /// (1) C# empty statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Empty"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IEmptyOperation : IOperation { } /// <summary> /// Represents a return from the method with an optional return value. /// <para> /// Current usage: /// (1) C# return statement and yield statement. /// (2) VB Return statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Return"/></description></item> /// <item><description><see cref="OperationKind.YieldBreak"/></description></item> /// <item><description><see cref="OperationKind.YieldReturn"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IReturnOperation : IOperation { /// <summary> /// Value to be returned. /// </summary> IOperation? ReturnedValue { get; } } /// <summary> /// Represents a <see cref="Body" /> of operations that are executed while holding a lock onto the <see cref="LockedValue" />. /// <para> /// Current usage: /// (1) C# lock statement. /// (2) VB SyncLock statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Lock"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILockOperation : IOperation { /// <summary> /// Operation producing a value to be locked. /// </summary> IOperation LockedValue { get; } /// <summary> /// Body of the lock, to be executed while holding the lock. /// </summary> IOperation Body { get; } } /// <summary> /// Represents a try operation for exception handling code with a body, catch clauses and a finally handler. /// <para> /// Current usage: /// (1) C# try statement. /// (2) VB Try statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Try"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITryOperation : IOperation { /// <summary> /// Body of the try, over which the handlers are active. /// </summary> IBlockOperation Body { get; } /// <summary> /// Catch clauses of the try. /// </summary> ImmutableArray<ICatchClauseOperation> Catches { get; } /// <summary> /// Finally handler of the try. /// </summary> IBlockOperation? Finally { get; } /// <summary> /// Exit label for the try. This will always be null for C#. /// </summary> ILabelSymbol? ExitLabel { get; } } /// <summary> /// Represents a <see cref="Body" /> of operations that are executed while using disposable <see cref="Resources" />. /// <para> /// Current usage: /// (1) C# using statement. /// (2) VB Using statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Using"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IUsingOperation : IOperation { /// <summary> /// Declaration introduced or resource held by the using. /// </summary> IOperation Resources { get; } /// <summary> /// Body of the using, over which the resources of the using are maintained. /// </summary> IOperation Body { get; } /// <summary> /// Locals declared within the <see cref="Resources" /> with scope spanning across this entire <see cref="IUsingOperation" />. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Whether this using is asynchronous. /// Always false for VB. /// </summary> bool IsAsynchronous { get; } } /// <summary> /// Represents an operation that drops the resulting value and the type of the underlying wrapped <see cref="Operation" />. /// <para> /// Current usage: /// (1) C# expression statement. /// (2) VB expression statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ExpressionStatement"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IExpressionStatementOperation : IOperation { /// <summary> /// Underlying operation with a value and type. /// </summary> IOperation Operation { get; } } /// <summary> /// Represents a local function defined within a method. /// <para> /// Current usage: /// (1) C# local function statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.LocalFunction"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILocalFunctionOperation : IOperation { /// <summary> /// Local function symbol. /// </summary> IMethodSymbol Symbol { get; } /// <summary> /// Body of the local function. /// </summary> /// <remarks> /// This can be null in error scenarios, or when the method is an extern method. /// </remarks> IBlockOperation? Body { get; } /// <summary> /// An extra body for the local function, if both a block body and expression body are specified in source. /// </summary> /// <remarks> /// This is only ever non-null in error situations. /// </remarks> IBlockOperation? IgnoredBody { get; } } /// <summary> /// Represents an operation to stop or suspend execution of code. /// <para> /// Current usage: /// (1) VB Stop statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Stop"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IStopOperation : IOperation { } /// <summary> /// Represents an operation that stops the execution of code abruptly. /// <para> /// Current usage: /// (1) VB End Statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.End"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IEndOperation : IOperation { } /// <summary> /// Represents an operation for raising an event. /// <para> /// Current usage: /// (1) VB raise event statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.RaiseEvent"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRaiseEventOperation : IOperation { /// <summary> /// Reference to the event to be raised. /// </summary> IEventReferenceOperation EventReference { get; } /// <summary> /// Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order. /// </summary> /// <remarks> /// If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. /// Default values are supplied for optional arguments missing in source. /// </remarks> ImmutableArray<IArgumentOperation> Arguments { get; } } /// <summary> /// Represents a textual literal numeric, string, etc. /// <para> /// Current usage: /// (1) C# literal expression. /// (2) VB literal expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Literal"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILiteralOperation : IOperation { } /// <summary> /// Represents a type conversion. /// <para> /// Current usage: /// (1) C# conversion expression. /// (2) VB conversion expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Conversion"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConversionOperation : IOperation { /// <summary> /// Value to be converted. /// </summary> IOperation Operand { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } /// <summary> /// Gets the underlying common conversion information. /// </summary> /// <remarks> /// If you need conversion information that is language specific, use either /// <see cref="T:Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetConversion(IConversionOperation)" /> or /// <see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.GetConversion(IConversionOperation)" />. /// </remarks> CommonConversion Conversion { get; } /// <summary> /// False if the conversion will fail with a <see cref="InvalidCastException" /> at runtime if the cast fails. This is true for C#'s /// <c>as</c> operator and for VB's <c>TryCast</c> operator. /// </summary> bool IsTryCast { get; } /// <summary> /// True if the conversion can fail at runtime with an overflow exception. This corresponds to C# checked and unchecked blocks. /// </summary> bool IsChecked { get; } } /// <summary> /// Represents an invocation of a method. /// <para> /// Current usage: /// (1) C# method invocation expression. /// (2) C# collection element initializer. /// For example, in the following collection initializer: <code>new C() { 1, 2, 3 }</code>, we will have /// 3 <see cref="IInvocationOperation" /> nodes, each of which will be a call to the corresponding Add method /// with either 1, 2, 3 as the argument. /// (3) VB method invocation expression. /// (4) VB collection element initializer. /// Similar to the C# example, <code>New C() From {1, 2, 3}</code> will have 3 <see cref="IInvocationOperation" /> /// nodes with 1, 2, and 3 as their arguments, respectively. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Invocation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInvocationOperation : IOperation { /// <summary> /// Method to be invoked. /// </summary> IMethodSymbol TargetMethod { get; } /// <summary> /// 'This' or 'Me' instance to be supplied to the method, or null if the method is static. /// </summary> IOperation? Instance { get; } /// <summary> /// True if the invocation uses a virtual mechanism, and false otherwise. /// </summary> bool IsVirtual { get; } /// <summary> /// Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order. /// </summary> /// <remarks> /// If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. /// Default values are supplied for optional arguments missing in source. /// </remarks> ImmutableArray<IArgumentOperation> Arguments { get; } } /// <summary> /// Represents a reference to an array element. /// <para> /// Current usage: /// (1) C# array element reference expression. /// (2) VB array element reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ArrayElementReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IArrayElementReferenceOperation : IOperation { /// <summary> /// Array to be indexed. /// </summary> IOperation ArrayReference { get; } /// <summary> /// Indices that specify an individual element. /// </summary> ImmutableArray<IOperation> Indices { get; } } /// <summary> /// Represents a reference to a declared local variable. /// <para> /// Current usage: /// (1) C# local reference expression. /// (2) VB local reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.LocalReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILocalReferenceOperation : IOperation { /// <summary> /// Referenced local variable. /// </summary> ILocalSymbol Local { get; } /// <summary> /// True if this reference is also the declaration site of this variable. This is true in out variable declarations /// and in deconstruction operations where a new variable is being declared. /// </summary> bool IsDeclaration { get; } } /// <summary> /// Represents a reference to a parameter. /// <para> /// Current usage: /// (1) C# parameter reference expression. /// (2) VB parameter reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ParameterReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IParameterReferenceOperation : IOperation { /// <summary> /// Referenced parameter. /// </summary> IParameterSymbol Parameter { get; } } /// <summary> /// Represents a reference to a member of a class, struct, or interface. /// <para> /// Current usage: /// (1) C# member reference expression. /// (2) VB member reference expression. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMemberReferenceOperation : IOperation { /// <summary> /// Instance of the type. Null if the reference is to a static/shared member. /// </summary> IOperation? Instance { get; } /// <summary> /// Referenced member. /// </summary> ISymbol Member { get; } } /// <summary> /// Represents a reference to a field. /// <para> /// Current usage: /// (1) C# field reference expression. /// (2) VB field reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.FieldReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IFieldReferenceOperation : IMemberReferenceOperation { /// <summary> /// Referenced field. /// </summary> IFieldSymbol Field { get; } /// <summary> /// If the field reference is also where the field was declared. /// </summary> /// <remarks> /// This is only ever true in CSharp scripts, where a top-level statement creates a new variable /// in a reference, such as an out variable declaration or a deconstruction declaration. /// </remarks> bool IsDeclaration { get; } } /// <summary> /// Represents a reference to a method other than as the target of an invocation. /// <para> /// Current usage: /// (1) C# method reference expression. /// (2) VB method reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.MethodReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMethodReferenceOperation : IMemberReferenceOperation { /// <summary> /// Referenced method. /// </summary> IMethodSymbol Method { get; } /// <summary> /// Indicates whether the reference uses virtual semantics. /// </summary> bool IsVirtual { get; } } /// <summary> /// Represents a reference to a property. /// <para> /// Current usage: /// (1) C# property reference expression. /// (2) VB property reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.PropertyReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPropertyReferenceOperation : IMemberReferenceOperation { /// <summary> /// Referenced property. /// </summary> IPropertySymbol Property { get; } /// <summary> /// Arguments of the indexer property reference, excluding the instance argument. Arguments are in evaluation order. /// </summary> /// <remarks> /// If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. /// Default values are supplied for optional arguments missing in source. /// </remarks> ImmutableArray<IArgumentOperation> Arguments { get; } } /// <summary> /// Represents a reference to an event. /// <para> /// Current usage: /// (1) C# event reference expression. /// (2) VB event reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.EventReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IEventReferenceOperation : IMemberReferenceOperation { /// <summary> /// Referenced event. /// </summary> IEventSymbol Event { get; } } /// <summary> /// Represents an operation with one operand and a unary operator. /// <para> /// Current usage: /// (1) C# unary operation expression. /// (2) VB unary operation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Unary"/></description></item> /// <item><description><see cref="OperationKind.UnaryOperator"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IUnaryOperation : IOperation { /// <summary> /// Kind of unary operation. /// </summary> UnaryOperatorKind OperatorKind { get; } /// <summary> /// Operand. /// </summary> IOperation Operand { get; } /// <summary> /// <see langword="true" /> if this is a 'lifted' unary operator. When there is an /// operator that is defined to work on a value type, 'lifted' operators are /// created to work on the <see cref="System.Nullable{T}" /> versions of those /// value types. /// </summary> bool IsLifted { get; } /// <summary> /// <see langword="true" /> if overflow checking is performed for the arithmetic operation. /// </summary> bool IsChecked { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } } /// <summary> /// Represents an operation with two operands and a binary operator that produces a result with a non-null type. /// <para> /// Current usage: /// (1) C# binary operator expression. /// (2) VB binary operator expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Binary"/></description></item> /// <item><description><see cref="OperationKind.BinaryOperator"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IBinaryOperation : IOperation { /// <summary> /// Kind of binary operation. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// Left operand. /// </summary> IOperation LeftOperand { get; } /// <summary> /// Right operand. /// </summary> IOperation RightOperand { get; } /// <summary> /// <see langword="true" /> if this is a 'lifted' binary operator. When there is an /// operator that is defined to work on a value type, 'lifted' operators are /// created to work on the <see cref="System.Nullable{T}" /> versions of those /// value types. /// </summary> bool IsLifted { get; } /// <summary> /// <see langword="true" /> if this is a 'checked' binary operator. /// </summary> bool IsChecked { get; } /// <summary> /// <see langword="true" /> if the comparison is text based for string or object comparison in VB. /// </summary> bool IsCompareText { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } } /// <summary> /// Represents a conditional operation with: /// (1) <see cref="Condition" /> to be tested, /// (2) <see cref="WhenTrue" /> operation to be executed when <see cref="Condition" /> is true and /// (3) <see cref="WhenFalse" /> operation to be executed when the <see cref="Condition" /> is false. /// <para> /// Current usage: /// (1) C# ternary expression "a ? b : c" and if statement. /// (2) VB ternary expression "If(a, b, c)" and If Else statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Conditional"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConditionalOperation : IOperation { /// <summary> /// Condition to be tested. /// </summary> IOperation Condition { get; } /// <summary> /// Operation to be executed if the <see cref="Condition" /> is true. /// </summary> IOperation WhenTrue { get; } /// <summary> /// Operation to be executed if the <see cref="Condition" /> is false. /// </summary> IOperation? WhenFalse { get; } /// <summary> /// Is result a managed reference /// </summary> bool IsRef { get; } } /// <summary> /// Represents a coalesce operation with two operands: /// (1) <see cref="Value" />, which is the first operand that is unconditionally evaluated and is the result of the operation if non null. /// (2) <see cref="WhenNull" />, which is the second operand that is conditionally evaluated and is the result of the operation if <see cref="Value" /> is null. /// <para> /// Current usage: /// (1) C# null-coalescing expression "Value ?? WhenNull". /// (2) VB binary conditional expression "If(Value, WhenNull)". /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Coalesce"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICoalesceOperation : IOperation { /// <summary> /// Operation to be unconditionally evaluated. /// </summary> IOperation Value { get; } /// <summary> /// Operation to be conditionally evaluated if <see cref="Value" /> evaluates to null/Nothing. /// </summary> IOperation WhenNull { get; } /// <summary> /// Conversion associated with <see cref="Value" /> when it is not null/Nothing. /// Identity if result type of the operation is the same as type of <see cref="Value" />. /// Otherwise, if type of <see cref="Value" /> is nullable, then conversion is applied to an /// unwrapped <see cref="Value" />, otherwise to the <see cref="Value" /> itself. /// </summary> CommonConversion ValueConversion { get; } } /// <summary> /// Represents an anonymous function operation. /// <para> /// Current usage: /// (1) C# lambda expression. /// (2) VB anonymous delegate expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.AnonymousFunction"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAnonymousFunctionOperation : IOperation { /// <summary> /// Symbol of the anonymous function. /// </summary> IMethodSymbol Symbol { get; } /// <summary> /// Body of the anonymous function. /// </summary> IBlockOperation Body { get; } } /// <summary> /// Represents creation of an object instance. /// <para> /// Current usage: /// (1) C# new expression. /// (2) VB New expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ObjectCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IObjectCreationOperation : IOperation { /// <summary> /// Constructor to be invoked on the created instance. /// </summary> IMethodSymbol? Constructor { get; } /// <summary> /// Object or collection initializer, if any. /// </summary> IObjectOrCollectionInitializerOperation? Initializer { get; } /// <summary> /// Arguments of the object creation, excluding the instance argument. Arguments are in evaluation order. /// </summary> /// <remarks> /// If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. /// Default values are supplied for optional arguments missing in source. /// </remarks> ImmutableArray<IArgumentOperation> Arguments { get; } } /// <summary> /// Represents a creation of a type parameter object, i.e. new T(), where T is a type parameter with new constraint. /// <para> /// Current usage: /// (1) C# type parameter object creation expression. /// (2) VB type parameter object creation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TypeParameterObjectCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITypeParameterObjectCreationOperation : IOperation { /// <summary> /// Object or collection initializer, if any. /// </summary> IObjectOrCollectionInitializerOperation? Initializer { get; } } /// <summary> /// Represents the creation of an array instance. /// <para> /// Current usage: /// (1) C# array creation expression. /// (2) VB array creation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ArrayCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IArrayCreationOperation : IOperation { /// <summary> /// Sizes of the dimensions of the created array instance. /// </summary> ImmutableArray<IOperation> DimensionSizes { get; } /// <summary> /// Values of elements of the created array instance. /// </summary> IArrayInitializerOperation? Initializer { get; } } /// <summary> /// Represents an implicit/explicit reference to an instance. /// <para> /// Current usage: /// (1) C# this or base expression. /// (2) VB Me, MyClass, or MyBase expression. /// (3) C# object or collection or 'with' expression initializers. /// (4) VB With statements, object or collection initializers. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InstanceReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInstanceReferenceOperation : IOperation { /// <summary> /// The kind of reference that is being made. /// </summary> InstanceReferenceKind ReferenceKind { get; } } /// <summary> /// Represents an operation that tests if a value is of a specific type. /// <para> /// Current usage: /// (1) C# "is" operator expression. /// (2) VB "TypeOf" and "TypeOf IsNot" expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.IsType"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IIsTypeOperation : IOperation { /// <summary> /// Value to test. /// </summary> IOperation ValueOperand { get; } /// <summary> /// Type for which to test. /// </summary> ITypeSymbol TypeOperand { get; } /// <summary> /// Flag indicating if this is an "is not" type expression. /// True for VB "TypeOf ... IsNot ..." expression. /// False, otherwise. /// </summary> bool IsNegated { get; } } /// <summary> /// Represents an await operation. /// <para> /// Current usage: /// (1) C# await expression. /// (2) VB await expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Await"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAwaitOperation : IOperation { /// <summary> /// Awaited operation. /// </summary> IOperation Operation { get; } } /// <summary> /// Represents a base interface for assignments. /// <para> /// Current usage: /// (1) C# simple, compound and deconstruction assignment expressions. /// (2) VB simple and compound assignment expressions. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAssignmentOperation : IOperation { /// <summary> /// Target of the assignment. /// </summary> IOperation Target { get; } /// <summary> /// Value to be assigned to the target of the assignment. /// </summary> IOperation Value { get; } } /// <summary> /// Represents a simple assignment operation. /// <para> /// Current usage: /// (1) C# simple assignment expression. /// (2) VB simple assignment expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SimpleAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISimpleAssignmentOperation : IAssignmentOperation { /// <summary> /// Is this a ref assignment /// </summary> bool IsRef { get; } } /// <summary> /// Represents a compound assignment that mutates the target with the result of a binary operation. /// <para> /// Current usage: /// (1) C# compound assignment expression. /// (2) VB compound assignment expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.CompoundAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICompoundAssignmentOperation : IAssignmentOperation { /// <summary> /// Conversion applied to <see cref="IAssignmentOperation.Target" /> before the operation occurs. /// </summary> CommonConversion InConversion { get; } /// <summary> /// Conversion applied to the result of the binary operation, before it is assigned back to /// <see cref="IAssignmentOperation.Target" />. /// </summary> CommonConversion OutConversion { get; } /// <summary> /// Kind of binary operation. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// <see langword="true" /> if this assignment contains a 'lifted' binary operation. /// </summary> bool IsLifted { get; } /// <summary> /// <see langword="true" /> if overflow checking is performed for the arithmetic operation. /// </summary> bool IsChecked { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } } /// <summary> /// Represents a parenthesized operation. /// <para> /// Current usage: /// (1) VB parenthesized expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Parenthesized"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IParenthesizedOperation : IOperation { /// <summary> /// Operand enclosed in parentheses. /// </summary> IOperation Operand { get; } } /// <summary> /// Represents a binding of an event. /// <para> /// Current usage: /// (1) C# event assignment expression. /// (2) VB Add/Remove handler statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.EventAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IEventAssignmentOperation : IOperation { /// <summary> /// Reference to the event being bound. /// </summary> IOperation EventReference { get; } /// <summary> /// Handler supplied for the event. /// </summary> IOperation HandlerValue { get; } /// <summary> /// True for adding a binding, false for removing one. /// </summary> bool Adds { get; } } /// <summary> /// Represents a conditionally accessed operation. Note that <see cref="IConditionalAccessInstanceOperation" /> is used to refer to the value /// of <see cref="Operation" /> within <see cref="WhenNotNull" />. /// <para> /// Current usage: /// (1) C# conditional access expression (? or ?. operator). /// (2) VB conditional access expression (? or ?. operator). /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ConditionalAccess"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConditionalAccessOperation : IOperation { /// <summary> /// Operation that will be evaluated and accessed if non null. /// </summary> IOperation Operation { get; } /// <summary> /// Operation to be evaluated if <see cref="Operation" /> is non null. /// </summary> IOperation WhenNotNull { get; } } /// <summary> /// Represents the value of a conditionally-accessed operation within <see cref="IConditionalAccessOperation.WhenNotNull" />. /// For a conditional access operation of the form <c>someExpr?.Member</c>, this operation is used as the InstanceReceiver for the right operation <c>Member</c>. /// See https://github.com/dotnet/roslyn/issues/21279#issuecomment-323153041 for more details. /// <para> /// Current usage: /// (1) C# conditional access instance expression. /// (2) VB conditional access instance expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ConditionalAccessInstance"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConditionalAccessInstanceOperation : IOperation { } /// <summary> /// Represents an interpolated string. /// <para> /// Current usage: /// (1) C# interpolated string expression. /// (2) VB interpolated string expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InterpolatedString"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringOperation : IOperation { /// <summary> /// Constituent parts of interpolated string, each of which is an <see cref="IInterpolatedStringContentOperation" />. /// </summary> ImmutableArray<IInterpolatedStringContentOperation> Parts { get; } } /// <summary> /// Represents a creation of anonymous object. /// <para> /// Current usage: /// (1) C# "new { ... }" expression /// (2) VB "New With { ... }" expression /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.AnonymousObjectCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAnonymousObjectCreationOperation : IOperation { /// <summary> /// Property initializers. /// Each initializer is an <see cref="ISimpleAssignmentOperation" />, with an <see cref="IPropertyReferenceOperation" /> /// as the target whose Instance is an <see cref="IInstanceReferenceOperation" /> with <see cref="InstanceReferenceKind.ImplicitReceiver" /> kind. /// </summary> ImmutableArray<IOperation> Initializers { get; } } /// <summary> /// Represents an initialization for an object or collection creation. /// <para> /// Current usage: /// (1) C# object or collection initializer expression. /// (2) VB object or collection initializer expression. /// For example, object initializer "{ X = x }" within object creation "new Class() { X = x }" and /// collection initializer "{ x, y, 3 }" within collection creation "new MyList() { x, y, 3 }". /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ObjectOrCollectionInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IObjectOrCollectionInitializerOperation : IOperation { /// <summary> /// Object member or collection initializers. /// </summary> ImmutableArray<IOperation> Initializers { get; } } /// <summary> /// Represents an initialization of member within an object initializer with a nested object or collection initializer. /// <para> /// Current usage: /// (1) C# nested member initializer expression. /// For example, given an object creation with initializer "new Class() { X = x, Y = { x, y, 3 }, Z = { X = z } }", /// member initializers for Y and Z, i.e. "Y = { x, y, 3 }", and "Z = { X = z }" are nested member initializers represented by this operation. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.MemberInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMemberInitializerOperation : IOperation { /// <summary> /// Initialized member reference <see cref="IMemberReferenceOperation" /> or an invalid operation for error cases. /// </summary> IOperation InitializedMember { get; } /// <summary> /// Member initializer. /// </summary> IObjectOrCollectionInitializerOperation Initializer { get; } } /// <summary> /// Obsolete interface that used to represent a collection element initializer. It has been replaced by /// <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />, as appropriate. /// <para> /// Current usage: /// None. This API has been obsoleted in favor of <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.CollectionElementInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> [Obsolete("ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation), error: true)] public interface ICollectionElementInitializerOperation : IOperation { IMethodSymbol AddMethod { get; } ImmutableArray<IOperation> Arguments { get; } bool IsDynamic { get; } } /// <summary> /// Represents an operation that gets a string value for the <see cref="Argument" /> name. /// <para> /// Current usage: /// (1) C# nameof expression. /// (2) VB NameOf expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.NameOf"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface INameOfOperation : IOperation { /// <summary> /// Argument to the name of operation. /// </summary> IOperation Argument { get; } } /// <summary> /// Represents a tuple with one or more elements. /// <para> /// Current usage: /// (1) C# tuple expression. /// (2) VB tuple expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Tuple"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITupleOperation : IOperation { /// <summary> /// Tuple elements. /// </summary> ImmutableArray<IOperation> Elements { get; } /// <summary> /// Natural type of the tuple, or null if tuple doesn't have a natural type. /// Natural type can be different from <see cref="IOperation.Type" /> depending on the /// conversion context, in which the tuple is used. /// </summary> ITypeSymbol? NaturalType { get; } } /// <summary> /// Represents an object creation with a dynamically bound constructor. /// <para> /// Current usage: /// (1) C# "new" expression with dynamic argument(s). /// (2) VB late bound "New" expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DynamicObjectCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDynamicObjectCreationOperation : IOperation { /// <summary> /// Object or collection initializer, if any. /// </summary> IObjectOrCollectionInitializerOperation? Initializer { get; } /// <summary> /// Dynamically bound arguments, excluding the instance argument. /// </summary> ImmutableArray<IOperation> Arguments { get; } } /// <summary> /// Represents a reference to a member of a class, struct, or module that is dynamically bound. /// <para> /// Current usage: /// (1) C# dynamic member reference expression. /// (2) VB late bound member reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DynamicMemberReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDynamicMemberReferenceOperation : IOperation { /// <summary> /// Instance receiver, if it exists. /// </summary> IOperation? Instance { get; } /// <summary> /// Referenced member. /// </summary> string MemberName { get; } /// <summary> /// Type arguments. /// </summary> ImmutableArray<ITypeSymbol> TypeArguments { get; } /// <summary> /// The containing type of the referenced member, if different from type of the <see cref="Instance" />. /// </summary> ITypeSymbol? ContainingType { get; } } /// <summary> /// Represents a invocation that is dynamically bound. /// <para> /// Current usage: /// (1) C# dynamic invocation expression. /// (2) C# dynamic collection element initializer. /// For example, in the following collection initializer: <code>new C() { do1, do2, do3 }</code> where /// the doX objects are of type dynamic, we'll have 3 <see cref="IDynamicInvocationOperation" /> with do1, do2, and /// do3 as their arguments. /// (3) VB late bound invocation expression. /// (4) VB dynamic collection element initializer. /// Similar to the C# example, <code>New C() From {do1, do2, do3}</code> will generate 3 <see cref="IDynamicInvocationOperation" /> /// nodes with do1, do2, and do3 as their arguments, respectively. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DynamicInvocation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDynamicInvocationOperation : IOperation { /// <summary> /// Dynamically or late bound operation. /// </summary> IOperation Operation { get; } /// <summary> /// Dynamically bound arguments, excluding the instance argument. /// </summary> ImmutableArray<IOperation> Arguments { get; } } /// <summary> /// Represents an indexer access that is dynamically bound. /// <para> /// Current usage: /// (1) C# dynamic indexer access expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DynamicIndexerAccess"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDynamicIndexerAccessOperation : IOperation { /// <summary> /// Dynamically indexed operation. /// </summary> IOperation Operation { get; } /// <summary> /// Dynamically bound arguments, excluding the instance argument. /// </summary> ImmutableArray<IOperation> Arguments { get; } } /// <summary> /// Represents an unrolled/lowered query operation. /// For example, for a C# query expression "from x in set where x.Name != null select x.Name", the Operation tree has the following shape: /// ITranslatedQueryExpression /// IInvocationExpression ('Select' invocation for "select x.Name") /// IInvocationExpression ('Where' invocation for "where x.Name != null") /// IInvocationExpression ('From' invocation for "from x in set") /// <para> /// Current usage: /// (1) C# query expression. /// (2) VB query expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TranslatedQuery"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITranslatedQueryOperation : IOperation { /// <summary> /// Underlying unrolled operation. /// </summary> IOperation Operation { get; } } /// <summary> /// Represents a delegate creation. This is created whenever a new delegate is created. /// <para> /// Current usage: /// (1) C# delegate creation expression. /// (2) VB delegate creation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DelegateCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDelegateCreationOperation : IOperation { /// <summary> /// The lambda or method binding that this delegate is created from. /// </summary> IOperation Target { get; } } /// <summary> /// Represents a default value operation. /// <para> /// Current usage: /// (1) C# default value expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DefaultValue"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDefaultValueOperation : IOperation { } /// <summary> /// Represents an operation that gets <see cref="System.Type" /> for the given <see cref="TypeOperand" />. /// <para> /// Current usage: /// (1) C# typeof expression. /// (2) VB GetType expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TypeOf"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITypeOfOperation : IOperation { /// <summary> /// Type operand. /// </summary> ITypeSymbol TypeOperand { get; } } /// <summary> /// Represents an operation to compute the size of a given type. /// <para> /// Current usage: /// (1) C# sizeof expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SizeOf"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISizeOfOperation : IOperation { /// <summary> /// Type operand. /// </summary> ITypeSymbol TypeOperand { get; } } /// <summary> /// Represents an operation that creates a pointer value by taking the address of a reference. /// <para> /// Current usage: /// (1) C# address of expression /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.AddressOf"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAddressOfOperation : IOperation { /// <summary> /// Addressed reference. /// </summary> IOperation Reference { get; } } /// <summary> /// Represents an operation that tests if a value matches a specific pattern. /// <para> /// Current usage: /// (1) C# is pattern expression. For example, "x is int i". /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.IsPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IIsPatternOperation : IOperation { /// <summary> /// Underlying operation to test. /// </summary> IOperation Value { get; } /// <summary> /// Pattern. /// </summary> IPatternOperation Pattern { get; } } /// <summary> /// Represents an <see cref="OperationKind.Increment" /> or <see cref="OperationKind.Decrement" /> operation. /// Note that this operation is different from an <see cref="IUnaryOperation" /> as it mutates the <see cref="Target" />, /// while unary operator expression does not mutate it's operand. /// <para> /// Current usage: /// (1) C# increment expression or decrement expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Increment"/></description></item> /// <item><description><see cref="OperationKind.Decrement"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IIncrementOrDecrementOperation : IOperation { /// <summary> /// <see langword="true" /> if this is a postfix expression. <see langword="false" /> if this is a prefix expression. /// </summary> bool IsPostfix { get; } /// <summary> /// <see langword="true" /> if this is a 'lifted' increment operator. When there /// is an operator that is defined to work on a value type, 'lifted' operators are /// created to work on the <see cref="System.Nullable{T}" /> versions of those /// value types. /// </summary> bool IsLifted { get; } /// <summary> /// <see langword="true" /> if overflow checking is performed for the arithmetic operation. /// </summary> bool IsChecked { get; } /// <summary> /// Target of the assignment. /// </summary> IOperation Target { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } } /// <summary> /// Represents an operation to throw an exception. /// <para> /// Current usage: /// (1) C# throw expression. /// (2) C# throw statement. /// (2) VB Throw statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Throw"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IThrowOperation : IOperation { /// <summary> /// Instance of an exception being thrown. /// </summary> IOperation? Exception { get; } } /// <summary> /// Represents a assignment with a deconstruction. /// <para> /// Current usage: /// (1) C# deconstruction assignment expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DeconstructionAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDeconstructionAssignmentOperation : IAssignmentOperation { } /// <summary> /// Represents a declaration expression operation. Unlike a regular variable declaration <see cref="IVariableDeclaratorOperation" /> and <see cref="IVariableDeclarationOperation" />, this operation represents an "expression" declaring a variable. /// <para> /// Current usage: /// (1) C# declaration expression. For example, /// (a) "var (x, y)" is a deconstruction declaration expression with variables x and y. /// (b) "(var x, var y)" is a tuple expression with two declaration expressions. /// (c) "M(out var x);" is an invocation expression with an out "var x" declaration expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DeclarationExpression"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDeclarationExpressionOperation : IOperation { /// <summary> /// Underlying expression. /// </summary> IOperation Expression { get; } } /// <summary> /// Represents an argument value that has been omitted in an invocation. /// <para> /// Current usage: /// (1) VB omitted argument in an invocation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.OmittedArgument"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IOmittedArgumentOperation : IOperation { } /// <summary> /// Represents an initializer for a field, property, parameter or a local variable declaration. /// <para> /// Current usage: /// (1) C# field, property, parameter or local variable initializer. /// (2) VB field(s), property, parameter or local variable initializer. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISymbolInitializerOperation : IOperation { /// <summary> /// Local declared in and scoped to the <see cref="Value" />. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Underlying initializer value. /// </summary> IOperation Value { get; } } /// <summary> /// Represents an initialization of a field. /// <para> /// Current usage: /// (1) C# field initializer with equals value clause. /// (2) VB field(s) initializer with equals value clause or AsNew clause. Multiple fields can be initialized with AsNew clause in VB. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.FieldInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IFieldInitializerOperation : ISymbolInitializerOperation { /// <summary> /// Initialized fields. There can be multiple fields for Visual Basic fields declared with AsNew clause. /// </summary> ImmutableArray<IFieldSymbol> InitializedFields { get; } } /// <summary> /// Represents an initialization of a local variable. /// <para> /// Current usage: /// (1) C# local variable initializer with equals value clause. /// (2) VB local variable initializer with equals value clause or AsNew clause. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.VariableInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IVariableInitializerOperation : ISymbolInitializerOperation { } /// <summary> /// Represents an initialization of a property. /// <para> /// Current usage: /// (1) C# property initializer with equals value clause. /// (2) VB property initializer with equals value clause or AsNew clause. Multiple properties can be initialized with 'WithEvents' declaration with AsNew clause in VB. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.PropertyInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPropertyInitializerOperation : ISymbolInitializerOperation { /// <summary> /// Initialized properties. There can be multiple properties for Visual Basic 'WithEvents' declaration with AsNew clause. /// </summary> ImmutableArray<IPropertySymbol> InitializedProperties { get; } } /// <summary> /// Represents an initialization of a parameter at the point of declaration. /// <para> /// Current usage: /// (1) C# parameter initializer with equals value clause. /// (2) VB parameter initializer with equals value clause. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ParameterInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IParameterInitializerOperation : ISymbolInitializerOperation { /// <summary> /// Initialized parameter. /// </summary> IParameterSymbol Parameter { get; } } /// <summary> /// Represents the initialization of an array instance. /// <para> /// Current usage: /// (1) C# array initializer. /// (2) VB array initializer. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ArrayInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IArrayInitializerOperation : IOperation { /// <summary> /// Values to initialize array elements. /// </summary> ImmutableArray<IOperation> ElementValues { get; } } /// <summary> /// Represents a single variable declarator and initializer. /// </summary> /// <para> /// Current Usage: /// (1) C# variable declarator /// (2) C# catch variable declaration /// (3) VB single variable declaration /// (4) VB catch variable declaration /// </para> /// <remarks> /// In VB, the initializer for this node is only ever used for explicit array bounds initializers. This node corresponds to /// the VariableDeclaratorSyntax in C# and the ModifiedIdentifierSyntax in VB. /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.VariableDeclarator"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IVariableDeclaratorOperation : IOperation { /// <summary> /// Symbol declared by this variable declaration /// </summary> ILocalSymbol Symbol { get; } /// <summary> /// Optional initializer of the variable. /// </summary> /// <remarks> /// If this variable is in an <see cref="IVariableDeclarationOperation" />, the initializer may be located /// in the parent operation. Call <see cref="OperationExtensions.GetVariableInitializer(IVariableDeclaratorOperation)" /> /// to check in all locations. It is only possible to have initializers in both locations in VB invalid code scenarios. /// </remarks> IVariableInitializerOperation? Initializer { get; } /// <summary> /// Additional arguments supplied to the declarator in error cases, ignored by the compiler. This only used for the C# case of /// DeclaredArgumentSyntax nodes on a VariableDeclaratorSyntax. /// </summary> ImmutableArray<IOperation> IgnoredArguments { get; } } /// <summary> /// Represents a declarator that declares multiple individual variables. /// </summary> /// <para> /// Current Usage: /// (1) C# VariableDeclaration /// (2) C# fixed declarations /// (3) VB Dim statement declaration groups /// (4) VB Using statement variable declarations /// </para> /// <remarks> /// The initializer of this node is applied to all individual declarations in <see cref="Declarators" />. There cannot /// be initializers in both locations except in invalid code scenarios. /// In C#, this node will never have an initializer. /// This corresponds to the VariableDeclarationSyntax in C#, and the VariableDeclaratorSyntax in Visual Basic. /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.VariableDeclaration"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IVariableDeclarationOperation : IOperation { /// <summary> /// Individual variable declarations declared by this multiple declaration. /// </summary> /// <remarks> /// All <see cref="IVariableDeclarationGroupOperation" /> will have at least 1 <see cref="IVariableDeclarationOperation" />, /// even if the declaration group only declares 1 variable. /// </remarks> ImmutableArray<IVariableDeclaratorOperation> Declarators { get; } /// <summary> /// Optional initializer of the variable. /// </summary> /// <remarks> /// In C#, this will always be null. /// </remarks> IVariableInitializerOperation? Initializer { get; } /// <summary> /// Array dimensions supplied to an array declaration in error cases, ignored by the compiler. This is only used for the C# case of /// RankSpecifierSyntax nodes on an ArrayTypeSyntax. /// </summary> ImmutableArray<IOperation> IgnoredDimensions { get; } } /// <summary> /// Represents an argument to a method invocation. /// <para> /// Current usage: /// (1) C# argument to an invocation expression, object creation expression, etc. /// (2) VB argument to an invocation expression, object creation expression, etc. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Argument"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IArgumentOperation : IOperation { /// <summary> /// Kind of argument. /// </summary> ArgumentKind ArgumentKind { get; } /// <summary> /// Parameter the argument matches. This can be null for __arglist parameters. /// </summary> IParameterSymbol? Parameter { get; } /// <summary> /// Value supplied for the argument. /// </summary> IOperation Value { get; } /// <summary> /// Information of the conversion applied to the argument value passing it into the target method. Applicable only to VB Reference arguments. /// </summary> CommonConversion InConversion { get; } /// <summary> /// Information of the conversion applied to the argument value after the invocation. Applicable only to VB Reference arguments. /// </summary> CommonConversion OutConversion { get; } } /// <summary> /// Represents a catch clause. /// <para> /// Current usage: /// (1) C# catch clause. /// (2) VB Catch clause. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.CatchClause"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICatchClauseOperation : IOperation { /// <summary> /// Optional source for exception. This could be any of the following operation: /// 1. Declaration for the local catch variable bound to the caught exception (C# and VB) OR /// 2. Null, indicating no declaration or expression (C# and VB) /// 3. Reference to an existing local or parameter (VB) OR /// 4. Other expression for error scenarios (VB) /// </summary> IOperation? ExceptionDeclarationOrExpression { get; } /// <summary> /// Type of the exception handled by the catch clause. /// </summary> ITypeSymbol ExceptionType { get; } /// <summary> /// Locals declared by the <see cref="ExceptionDeclarationOrExpression" /> and/or <see cref="Filter" /> clause. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Filter operation to be executed to determine whether to handle the exception. /// </summary> IOperation? Filter { get; } /// <summary> /// Body of the exception handler. /// </summary> IBlockOperation Handler { get; } } /// <summary> /// Represents a switch case section with one or more case clauses to match and one or more operations to execute within the section. /// <para> /// Current usage: /// (1) C# switch section for one or more case clause and set of statements to execute. /// (2) VB case block with a case statement for one or more case clause and set of statements to execute. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SwitchCase"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISwitchCaseOperation : IOperation { /// <summary> /// Clauses of the case. /// </summary> ImmutableArray<ICaseClauseOperation> Clauses { get; } /// <summary> /// One or more operations to execute within the switch section. /// </summary> ImmutableArray<IOperation> Body { get; } /// <summary> /// Locals declared within the switch case section scoped to the section. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } } /// <summary> /// Represents a case clause. /// <para> /// Current usage: /// (1) C# case clause. /// (2) VB Case clause. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICaseClauseOperation : IOperation { /// <summary> /// Kind of the clause. /// </summary> CaseKind CaseKind { get; } /// <summary> /// Label associated with the case clause, if any. /// </summary> ILabelSymbol? Label { get; } } /// <summary> /// Represents a default case clause. /// <para> /// Current usage: /// (1) C# default clause. /// (2) VB Case Else clause. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDefaultCaseClauseOperation : ICaseClauseOperation { } /// <summary> /// Represents a case clause with a pattern and an optional guard operation. /// <para> /// Current usage: /// (1) C# pattern case clause. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPatternCaseClauseOperation : ICaseClauseOperation { /// <summary> /// Label associated with the case clause. /// </summary> new ILabelSymbol Label { get; } /// <summary> /// Pattern associated with case clause. /// </summary> IPatternOperation Pattern { get; } /// <summary> /// Guard associated with the pattern case clause. /// </summary> IOperation? Guard { get; } } /// <summary> /// Represents a case clause with range of values for comparison. /// <para> /// Current usage: /// (1) VB range case clause of the form "Case x To y". /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRangeCaseClauseOperation : ICaseClauseOperation { /// <summary> /// Minimum value of the case range. /// </summary> IOperation MinimumValue { get; } /// <summary> /// Maximum value of the case range. /// </summary> IOperation MaximumValue { get; } } /// <summary> /// Represents a case clause with custom relational operator for comparison. /// <para> /// Current usage: /// (1) VB relational case clause of the form "Case Is op x". /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRelationalCaseClauseOperation : ICaseClauseOperation { /// <summary> /// Case value. /// </summary> IOperation Value { get; } /// <summary> /// Relational operator used to compare the switch value with the case value. /// </summary> BinaryOperatorKind Relation { get; } } /// <summary> /// Represents a case clause with a single value for comparison. /// <para> /// Current usage: /// (1) C# case clause of the form "case x" /// (2) VB case clause of the form "Case x". /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISingleValueCaseClauseOperation : ICaseClauseOperation { /// <summary> /// Case value. /// </summary> IOperation Value { get; } } /// <summary> /// Represents a constituent part of an interpolated string. /// <para> /// Current usage: /// (1) C# interpolated string content. /// (2) VB interpolated string content. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringContentOperation : IOperation { } /// <summary> /// Represents a constituent string literal part of an interpolated string operation. /// <para> /// Current usage: /// (1) C# interpolated string text. /// (2) VB interpolated string text. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InterpolatedStringText"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringTextOperation : IInterpolatedStringContentOperation { /// <summary> /// Text content. /// </summary> IOperation Text { get; } } /// <summary> /// Represents a constituent interpolation part of an interpolated string operation. /// <para> /// Current usage: /// (1) C# interpolation part. /// (2) VB interpolation part. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Interpolation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolationOperation : IInterpolatedStringContentOperation { /// <summary> /// Expression of the interpolation. /// </summary> IOperation Expression { get; } /// <summary> /// Optional alignment of the interpolation. /// </summary> IOperation? Alignment { get; } /// <summary> /// Optional format string of the interpolation. /// </summary> IOperation? FormatString { get; } } /// <summary> /// Represents a pattern matching operation. /// <para> /// Current usage: /// (1) C# pattern. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPatternOperation : IOperation { /// <summary> /// The input type to the pattern-matching operation. /// </summary> ITypeSymbol InputType { get; } /// <summary> /// The narrowed type of the pattern-matching operation. /// </summary> ITypeSymbol NarrowedType { get; } } /// <summary> /// Represents a pattern with a constant value. /// <para> /// Current usage: /// (1) C# constant pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ConstantPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConstantPatternOperation : IPatternOperation { /// <summary> /// Constant value of the pattern operation. /// </summary> IOperation Value { get; } } /// <summary> /// Represents a pattern that declares a symbol. /// <para> /// Current usage: /// (1) C# declaration pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DeclarationPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDeclarationPatternOperation : IPatternOperation { /// <summary> /// The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#). /// </summary> ITypeSymbol? MatchedType { get; } /// <summary> /// True if the pattern is of a form that accepts null. /// For example, in C# the pattern `var x` will match a null input, /// while the pattern `string x` will not. /// </summary> bool MatchesNull { get; } /// <summary> /// Symbol declared by the pattern, if any. /// </summary> ISymbol? DeclaredSymbol { get; } } /// <summary> /// Represents a comparison of two operands that returns a bool type. /// <para> /// Current usage: /// (1) C# tuple binary operator expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TupleBinary"/></description></item> /// <item><description><see cref="OperationKind.TupleBinaryOperator"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITupleBinaryOperation : IOperation { /// <summary> /// Kind of binary operation. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// Left operand. /// </summary> IOperation LeftOperand { get; } /// <summary> /// Right operand. /// </summary> IOperation RightOperand { get; } } /// <summary> /// Represents a method body operation. /// <para> /// Current usage: /// (1) C# method body /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMethodBodyBaseOperation : IOperation { /// <summary> /// Method body corresponding to BaseMethodDeclarationSyntax.Body or AccessorDeclarationSyntax.Body /// </summary> IBlockOperation? BlockBody { get; } /// <summary> /// Method body corresponding to BaseMethodDeclarationSyntax.ExpressionBody or AccessorDeclarationSyntax.ExpressionBody /// </summary> IBlockOperation? ExpressionBody { get; } } /// <summary> /// Represents a method body operation. /// <para> /// Current usage: /// (1) C# method body for non-constructor /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.MethodBody"/></description></item> /// <item><description><see cref="OperationKind.MethodBodyOperation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMethodBodyOperation : IMethodBodyBaseOperation { } /// <summary> /// Represents a constructor method body operation. /// <para> /// Current usage: /// (1) C# method body for constructor declaration /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ConstructorBody"/></description></item> /// <item><description><see cref="OperationKind.ConstructorBodyOperation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConstructorBodyOperation : IMethodBodyBaseOperation { /// <summary> /// Local declarations contained within the <see cref="Initializer" />. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Constructor initializer, if any. /// </summary> IOperation? Initializer { get; } } /// <summary> /// Represents a discard operation. /// <para> /// Current usage: C# discard expressions /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Discard"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDiscardOperation : IOperation { /// <summary> /// The symbol of the discard operation. /// </summary> IDiscardSymbol DiscardSymbol { get; } } /// <summary> /// Represents a coalesce assignment operation with a target and a conditionally-evaluated value: /// (1) <see cref="IAssignmentOperation.Target" /> is evaluated for null. If it is null, <see cref="IAssignmentOperation.Value" /> is evaluated and assigned to target. /// (2) <see cref="IAssignmentOperation.Value" /> is conditionally evaluated if <see cref="IAssignmentOperation.Target" /> is null, and the result is assigned into <see cref="IAssignmentOperation.Target" />. /// The result of the entire expression is<see cref="IAssignmentOperation.Target" />, which is only evaluated once. /// <para> /// Current usage: /// (1) C# null-coalescing assignment operation <code>Target ??= Value</code>. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.CoalesceAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICoalesceAssignmentOperation : IAssignmentOperation { } /// <summary> /// Represents a range operation. /// <para> /// Current usage: /// (1) C# range expressions /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Range"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRangeOperation : IOperation { /// <summary> /// Left operand. /// </summary> IOperation? LeftOperand { get; } /// <summary> /// Right operand. /// </summary> IOperation? RightOperand { get; } /// <summary> /// <code>true</code> if this is a 'lifted' range operation. When there is an /// operator that is defined to work on a value type, 'lifted' operators are /// created to work on the <see cref="System.Nullable{T}" /> versions of those /// value types. /// </summary> bool IsLifted { get; } /// <summary> /// Factory method used to create this Range value. Can be null if appropriate /// symbol was not found. /// </summary> IMethodSymbol? Method { get; } } /// <summary> /// Represents the ReDim operation to re-allocate storage space for array variables. /// <para> /// Current usage: /// (1) VB ReDim statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ReDim"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IReDimOperation : IOperation { /// <summary> /// Individual clauses of the ReDim operation. /// </summary> ImmutableArray<IReDimClauseOperation> Clauses { get; } /// <summary> /// Modifier used to preserve the data in the existing array when you change the size of only the last dimension. /// </summary> bool Preserve { get; } } /// <summary> /// Represents an individual clause of an <see cref="IReDimOperation" /> to re-allocate storage space for a single array variable. /// <para> /// Current usage: /// (1) VB ReDim clause. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ReDimClause"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IReDimClauseOperation : IOperation { /// <summary> /// Operand whose storage space needs to be re-allocated. /// </summary> IOperation Operand { get; } /// <summary> /// Sizes of the dimensions of the created array instance. /// </summary> ImmutableArray<IOperation> DimensionSizes { get; } } /// <summary> /// Represents a C# recursive pattern. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.RecursivePattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRecursivePatternOperation : IPatternOperation { /// <summary> /// The type accepted for the recursive pattern. /// </summary> ITypeSymbol MatchedType { get; } /// <summary> /// The symbol, if any, used for the fetching values for subpatterns. This is either a <code>Deconstruct</code> /// method, the type <code>System.Runtime.CompilerServices.ITuple</code>, or null (for example, in /// error cases or when matching a tuple type). /// </summary> ISymbol? DeconstructSymbol { get; } /// <summary> /// This contains the patterns contained within a deconstruction or positional subpattern. /// </summary> ImmutableArray<IPatternOperation> DeconstructionSubpatterns { get; } /// <summary> /// This contains the (symbol, property) pairs within a property subpattern. /// </summary> ImmutableArray<IPropertySubpatternOperation> PropertySubpatterns { get; } /// <summary> /// Symbol declared by the pattern. /// </summary> ISymbol? DeclaredSymbol { get; } } /// <summary> /// Represents a discard pattern. /// <para> /// Current usage: C# discard pattern /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DiscardPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDiscardPatternOperation : IPatternOperation { } /// <summary> /// Represents a switch expression. /// <para> /// Current usage: /// (1) C# switch expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SwitchExpression"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISwitchExpressionOperation : IOperation { /// <summary> /// Value to be switched upon. /// </summary> IOperation Value { get; } /// <summary> /// Arms of the switch expression. /// </summary> ImmutableArray<ISwitchExpressionArmOperation> Arms { get; } /// <summary> /// True if the switch expressions arms cover every possible input value. /// </summary> bool IsExhaustive { get; } } /// <summary> /// Represents one arm of a switch expression. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SwitchExpressionArm"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISwitchExpressionArmOperation : IOperation { /// <summary> /// The pattern to match. /// </summary> IPatternOperation Pattern { get; } /// <summary> /// Guard (when clause expression) associated with the switch arm, if any. /// </summary> IOperation? Guard { get; } /// <summary> /// Result value of the enclosing switch expression when this arm matches. /// </summary> IOperation Value { get; } /// <summary> /// Locals declared within the switch arm (e.g. pattern locals and locals declared in the guard) scoped to the arm. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } } /// <summary> /// Represents an element of a property subpattern, which identifies a member to be matched and the /// pattern to match it against. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.PropertySubpattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPropertySubpatternOperation : IOperation { /// <summary> /// The member being matched in a property subpattern. This can be a <see cref="IMemberReferenceOperation" /> /// in non-error cases, or an <see cref="IInvalidOperation" /> in error cases. /// </summary> IOperation Member { get; } /// <summary> /// The pattern to which the member is matched in a property subpattern. /// </summary> IPatternOperation Pattern { get; } } /// <summary> /// Represents a standalone VB query Aggregate operation with more than one item in Into clause. /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IAggregateQueryOperation : IOperation { IOperation Group { get; } IOperation Aggregation { get; } } /// <summary> /// Represents a C# fixed statement. /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IFixedOperation : IOperation { /// <summary> /// Locals declared. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Variables to be fixed. /// </summary> IVariableDeclarationGroupOperation Variables { get; } /// <summary> /// Body of the fixed, over which the variables are fixed. /// </summary> IOperation Body { get; } } /// <summary> /// Represents a creation of an instance of a NoPia interface, i.e. new I(), where I is an embedded NoPia interface. /// <para> /// Current usage: /// (1) C# NoPia interface instance creation expression. /// (2) VB NoPia interface instance creation expression. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface INoPiaObjectCreationOperation : IOperation { /// <summary> /// Object or collection initializer, if any. /// </summary> IObjectOrCollectionInitializerOperation? Initializer { get; } } /// <summary> /// Represents a general placeholder when no more specific kind of placeholder is available. /// A placeholder is an expression whose meaning is inferred from context. /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IPlaceholderOperation : IOperation { PlaceholderKind PlaceholderKind { get; } } /// <summary> /// Represents a reference through a pointer. /// <para> /// Current usage: /// (1) C# pointer indirection reference expression. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IPointerIndirectionReferenceOperation : IOperation { /// <summary> /// Pointer to be dereferenced. /// </summary> IOperation Pointer { get; } } /// <summary> /// Represents a <see cref="Body" /> of operations that are executed with implicit reference to the <see cref="Value" /> for member references. /// <para> /// Current usage: /// (1) VB With statement. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IWithStatementOperation : IOperation { /// <summary> /// Body of the with. /// </summary> IOperation Body { get; } /// <summary> /// Value to whose members leading-dot-qualified references within the with body bind. /// </summary> IOperation Value { get; } } /// <summary> /// Represents using variable declaration, with scope spanning across the parent <see cref="IBlockOperation" />. /// <para> /// Current Usage: /// (1) C# using declaration /// (1) C# asynchronous using declaration /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.UsingDeclaration"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IUsingDeclarationOperation : IOperation { /// <summary> /// The variables declared by this using declaration. /// </summary> IVariableDeclarationGroupOperation DeclarationGroup { get; } /// <summary> /// True if this is an asynchronous using declaration. /// </summary> bool IsAsynchronous { get; } } /// <summary> /// Represents a negated pattern. /// <para> /// Current usage: /// (1) C# negated pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.NegatedPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface INegatedPatternOperation : IPatternOperation { /// <summary> /// The negated pattern. /// </summary> IPatternOperation Pattern { get; } } /// <summary> /// Represents a binary ("and" or "or") pattern. /// <para> /// Current usage: /// (1) C# "and" and "or" patterns. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.BinaryPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IBinaryPatternOperation : IPatternOperation { /// <summary> /// Kind of binary pattern; either <see cref="BinaryOperatorKind.And" /> or <see cref="BinaryOperatorKind.Or" />. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// The pattern on the left. /// </summary> IPatternOperation LeftPattern { get; } /// <summary> /// The pattern on the right. /// </summary> IPatternOperation RightPattern { get; } } /// <summary> /// Represents a pattern comparing the input with a given type. /// <para> /// Current usage: /// (1) C# type pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TypePattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITypePatternOperation : IPatternOperation { /// <summary> /// The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#). /// </summary> ITypeSymbol MatchedType { get; } } /// <summary> /// Represents a pattern comparing the input with a constant value using a relational operator. /// <para> /// Current usage: /// (1) C# relational pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.RelationalPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRelationalPatternOperation : IPatternOperation { /// <summary> /// The kind of the relational operator. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// Constant value of the pattern operation. /// </summary> IOperation Value { get; } } /// <summary> /// Represents cloning of an object instance. /// <para> /// Current usage: /// (1) C# with expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.With"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IWithOperation : IOperation { /// <summary> /// Operand to be cloned. /// </summary> IOperation Operand { get; } /// <summary> /// Clone method to be invoked on the value. This can be null in error scenarios. /// </summary> IMethodSymbol? CloneMethod { get; } /// <summary> /// With collection initializer. /// </summary> IObjectOrCollectionInitializerOperation Initializer { get; } } #endregion #region Implementations internal sealed partial class BlockOperation : Operation, IBlockOperation { internal BlockOperation(ImmutableArray<IOperation> operations, ImmutableArray<ILocalSymbol> locals, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operations = SetParentOperation(operations, this); Locals = locals; } public ImmutableArray<IOperation> Operations { get; } public ImmutableArray<ILocalSymbol> Locals { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Operations.Length => Operations[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Operations.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Operations.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Block; public override void Accept(OperationVisitor visitor) => visitor.VisitBlock(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitBlock(this, argument); } internal sealed partial class VariableDeclarationGroupOperation : Operation, IVariableDeclarationGroupOperation { internal VariableDeclarationGroupOperation(ImmutableArray<IVariableDeclarationOperation> declarations, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Declarations = SetParentOperation(declarations, this); } public ImmutableArray<IVariableDeclarationOperation> Declarations { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Declarations.Length => Declarations[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Declarations.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Declarations.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.VariableDeclarationGroup; public override void Accept(OperationVisitor visitor) => visitor.VisitVariableDeclarationGroup(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitVariableDeclarationGroup(this, argument); } internal sealed partial class SwitchOperation : Operation, ISwitchOperation { internal SwitchOperation(ImmutableArray<ILocalSymbol> locals, IOperation value, ImmutableArray<ISwitchCaseOperation> cases, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Locals = locals; Value = SetParentOperation(value, this); Cases = SetParentOperation(cases, this); ExitLabel = exitLabel; } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation Value { get; } public ImmutableArray<ISwitchCaseOperation> Cases { get; } public ILabelSymbol ExitLabel { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when index < Cases.Length => Cases[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (!Cases.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Cases.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Switch; public override void Accept(OperationVisitor visitor) => visitor.VisitSwitch(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSwitch(this, argument); } internal abstract partial class BaseLoopOperation : Operation, ILoopOperation { protected BaseLoopOperation(IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Body = SetParentOperation(body, this); Locals = locals; ContinueLabel = continueLabel; ExitLabel = exitLabel; } public abstract LoopKind LoopKind { get; } public IOperation Body { get; } public ImmutableArray<ILocalSymbol> Locals { get; } public ILabelSymbol ContinueLabel { get; } public ILabelSymbol ExitLabel { get; } } internal sealed partial class ForEachLoopOperation : BaseLoopOperation, IForEachLoopOperation { internal ForEachLoopOperation(IOperation loopControlVariable, IOperation collection, ImmutableArray<IOperation> nextVariables, ForEachLoopOperationInfo? info, bool isAsynchronous, IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) { LoopControlVariable = SetParentOperation(loopControlVariable, this); Collection = SetParentOperation(collection, this); NextVariables = SetParentOperation(nextVariables, this); Info = info; IsAsynchronous = isAsynchronous; } public IOperation LoopControlVariable { get; } public IOperation Collection { get; } public ImmutableArray<IOperation> NextVariables { get; } public ForEachLoopOperationInfo? Info { get; } public bool IsAsynchronous { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Collection != null => Collection, 1 when LoopControlVariable != null => LoopControlVariable, 2 when Body != null => Body, 3 when index < NextVariables.Length => NextVariables[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Collection != null) return (true, 0, 0); else goto case 0; case 0: if (LoopControlVariable != null) return (true, 1, 0); else goto case 1; case 1: if (Body != null) return (true, 2, 0); else goto case 2; case 2: if (!NextVariables.IsEmpty) return (true, 3, 0); else goto case 3; case 3 when previousIndex + 1 < NextVariables.Length: return (true, 3, previousIndex + 1); case 3: case 4: return (false, 4, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Loop; public override void Accept(OperationVisitor visitor) => visitor.VisitForEachLoop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitForEachLoop(this, argument); } internal sealed partial class ForLoopOperation : BaseLoopOperation, IForLoopOperation { internal ForLoopOperation(ImmutableArray<IOperation> before, ImmutableArray<ILocalSymbol> conditionLocals, IOperation? condition, ImmutableArray<IOperation> atLoopBottom, IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) { Before = SetParentOperation(before, this); ConditionLocals = conditionLocals; Condition = SetParentOperation(condition, this); AtLoopBottom = SetParentOperation(atLoopBottom, this); } public ImmutableArray<IOperation> Before { get; } public ImmutableArray<ILocalSymbol> ConditionLocals { get; } public IOperation? Condition { get; } public ImmutableArray<IOperation> AtLoopBottom { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Before.Length => Before[index], 1 when Condition != null => Condition, 2 when Body != null => Body, 3 when index < AtLoopBottom.Length => AtLoopBottom[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Before.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Before.Length: return (true, 0, previousIndex + 1); case 0: if (Condition != null) return (true, 1, 0); else goto case 1; case 1: if (Body != null) return (true, 2, 0); else goto case 2; case 2: if (!AtLoopBottom.IsEmpty) return (true, 3, 0); else goto case 3; case 3 when previousIndex + 1 < AtLoopBottom.Length: return (true, 3, previousIndex + 1); case 3: case 4: return (false, 4, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Loop; public override void Accept(OperationVisitor visitor) => visitor.VisitForLoop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitForLoop(this, argument); } internal sealed partial class ForToLoopOperation : BaseLoopOperation, IForToLoopOperation { internal ForToLoopOperation(IOperation loopControlVariable, IOperation initialValue, IOperation limitValue, IOperation stepValue, bool isChecked, ImmutableArray<IOperation> nextVariables, (ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo) info, IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) { LoopControlVariable = SetParentOperation(loopControlVariable, this); InitialValue = SetParentOperation(initialValue, this); LimitValue = SetParentOperation(limitValue, this); StepValue = SetParentOperation(stepValue, this); IsChecked = isChecked; NextVariables = SetParentOperation(nextVariables, this); Info = info; } public IOperation LoopControlVariable { get; } public IOperation InitialValue { get; } public IOperation LimitValue { get; } public IOperation StepValue { get; } public bool IsChecked { get; } public ImmutableArray<IOperation> NextVariables { get; } public (ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo) Info { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LoopControlVariable != null => LoopControlVariable, 1 when InitialValue != null => InitialValue, 2 when LimitValue != null => LimitValue, 3 when StepValue != null => StepValue, 4 when Body != null => Body, 5 when index < NextVariables.Length => NextVariables[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LoopControlVariable != null) return (true, 0, 0); else goto case 0; case 0: if (InitialValue != null) return (true, 1, 0); else goto case 1; case 1: if (LimitValue != null) return (true, 2, 0); else goto case 2; case 2: if (StepValue != null) return (true, 3, 0); else goto case 3; case 3: if (Body != null) return (true, 4, 0); else goto case 4; case 4: if (!NextVariables.IsEmpty) return (true, 5, 0); else goto case 5; case 5 when previousIndex + 1 < NextVariables.Length: return (true, 5, previousIndex + 1); case 5: case 6: return (false, 6, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Loop; public override void Accept(OperationVisitor visitor) => visitor.VisitForToLoop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitForToLoop(this, argument); } internal sealed partial class WhileLoopOperation : BaseLoopOperation, IWhileLoopOperation { internal WhileLoopOperation(IOperation? condition, bool conditionIsTop, bool conditionIsUntil, IOperation? ignoredCondition, IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) { Condition = SetParentOperation(condition, this); ConditionIsTop = conditionIsTop; ConditionIsUntil = conditionIsUntil; IgnoredCondition = SetParentOperation(ignoredCondition, this); } public IOperation? Condition { get; } public bool ConditionIsTop { get; } public bool ConditionIsUntil { get; } public IOperation? IgnoredCondition { get; } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Loop; public override void Accept(OperationVisitor visitor) => visitor.VisitWhileLoop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitWhileLoop(this, argument); } internal sealed partial class LabeledOperation : Operation, ILabeledOperation { internal LabeledOperation(ILabelSymbol label, IOperation? operation, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Label = label; Operation = SetParentOperation(operation, this); } public ILabelSymbol Label { get; } public IOperation? Operation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Labeled; public override void Accept(OperationVisitor visitor) => visitor.VisitLabeled(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLabeled(this, argument); } internal sealed partial class BranchOperation : Operation, IBranchOperation { internal BranchOperation(ILabelSymbol target, BranchKind branchKind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Target = target; BranchKind = branchKind; } public ILabelSymbol Target { get; } public BranchKind BranchKind { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Branch; public override void Accept(OperationVisitor visitor) => visitor.VisitBranch(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitBranch(this, argument); } internal sealed partial class EmptyOperation : Operation, IEmptyOperation { internal EmptyOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Empty; public override void Accept(OperationVisitor visitor) => visitor.VisitEmpty(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitEmpty(this, argument); } internal sealed partial class ReturnOperation : Operation, IReturnOperation { internal ReturnOperation(IOperation? returnedValue, OperationKind kind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ReturnedValue = SetParentOperation(returnedValue, this); Kind = kind; } public IOperation? ReturnedValue { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when ReturnedValue != null => ReturnedValue, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (ReturnedValue != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind { get; } public override void Accept(OperationVisitor visitor) => visitor.VisitReturn(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitReturn(this, argument); } internal sealed partial class LockOperation : Operation, ILockOperation { internal LockOperation(IOperation lockedValue, IOperation body, ILocalSymbol? lockTakenSymbol, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { LockedValue = SetParentOperation(lockedValue, this); Body = SetParentOperation(body, this); LockTakenSymbol = lockTakenSymbol; } public IOperation LockedValue { get; } public IOperation Body { get; } public ILocalSymbol? LockTakenSymbol { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LockedValue != null => LockedValue, 1 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LockedValue != null) return (true, 0, 0); else goto case 0; case 0: if (Body != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Lock; public override void Accept(OperationVisitor visitor) => visitor.VisitLock(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLock(this, argument); } internal sealed partial class TryOperation : Operation, ITryOperation { internal TryOperation(IBlockOperation body, ImmutableArray<ICatchClauseOperation> catches, IBlockOperation? @finally, ILabelSymbol? exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Body = SetParentOperation(body, this); Catches = SetParentOperation(catches, this); Finally = SetParentOperation(@finally, this); ExitLabel = exitLabel; } public IBlockOperation Body { get; } public ImmutableArray<ICatchClauseOperation> Catches { get; } public IBlockOperation? Finally { get; } public ILabelSymbol? ExitLabel { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Body != null => Body, 1 when index < Catches.Length => Catches[index], 2 when Finally != null => Finally, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Body != null) return (true, 0, 0); else goto case 0; case 0: if (!Catches.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Catches.Length: return (true, 1, previousIndex + 1); case 1: if (Finally != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Try; public override void Accept(OperationVisitor visitor) => visitor.VisitTry(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTry(this, argument); } internal sealed partial class UsingOperation : Operation, IUsingOperation { internal UsingOperation(IOperation resources, IOperation body, ImmutableArray<ILocalSymbol> locals, bool isAsynchronous, DisposeOperationInfo disposeInfo, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Resources = SetParentOperation(resources, this); Body = SetParentOperation(body, this); Locals = locals; IsAsynchronous = isAsynchronous; DisposeInfo = disposeInfo; } public IOperation Resources { get; } public IOperation Body { get; } public ImmutableArray<ILocalSymbol> Locals { get; } public bool IsAsynchronous { get; } public DisposeOperationInfo DisposeInfo { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Resources != null => Resources, 1 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Resources != null) return (true, 0, 0); else goto case 0; case 0: if (Body != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Using; public override void Accept(OperationVisitor visitor) => visitor.VisitUsing(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitUsing(this, argument); } internal sealed partial class ExpressionStatementOperation : Operation, IExpressionStatementOperation { internal ExpressionStatementOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operation = SetParentOperation(operation, this); } public IOperation Operation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ExpressionStatement; public override void Accept(OperationVisitor visitor) => visitor.VisitExpressionStatement(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitExpressionStatement(this, argument); } internal sealed partial class LocalFunctionOperation : Operation, ILocalFunctionOperation { internal LocalFunctionOperation(IMethodSymbol symbol, IBlockOperation? body, IBlockOperation? ignoredBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Symbol = symbol; Body = SetParentOperation(body, this); IgnoredBody = SetParentOperation(ignoredBody, this); } public IMethodSymbol Symbol { get; } public IBlockOperation? Body { get; } public IBlockOperation? IgnoredBody { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Body != null => Body, 1 when IgnoredBody != null => IgnoredBody, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Body != null) return (true, 0, 0); else goto case 0; case 0: if (IgnoredBody != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.LocalFunction; public override void Accept(OperationVisitor visitor) => visitor.VisitLocalFunction(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLocalFunction(this, argument); } internal sealed partial class StopOperation : Operation, IStopOperation { internal StopOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Stop; public override void Accept(OperationVisitor visitor) => visitor.VisitStop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitStop(this, argument); } internal sealed partial class EndOperation : Operation, IEndOperation { internal EndOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.End; public override void Accept(OperationVisitor visitor) => visitor.VisitEnd(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitEnd(this, argument); } internal sealed partial class RaiseEventOperation : Operation, IRaiseEventOperation { internal RaiseEventOperation(IEventReferenceOperation eventReference, ImmutableArray<IArgumentOperation> arguments, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { EventReference = SetParentOperation(eventReference, this); Arguments = SetParentOperation(arguments, this); } public IEventReferenceOperation EventReference { get; } public ImmutableArray<IArgumentOperation> Arguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when EventReference != null => EventReference, 1 when index < Arguments.Length => Arguments[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (EventReference != null) return (true, 0, 0); else goto case 0; case 0: if (!Arguments.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Arguments.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.RaiseEvent; public override void Accept(OperationVisitor visitor) => visitor.VisitRaiseEvent(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRaiseEvent(this, argument); } internal sealed partial class LiteralOperation : Operation, ILiteralOperation { internal LiteralOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperationConstantValue = constantValue; Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Literal; public override void Accept(OperationVisitor visitor) => visitor.VisitLiteral(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLiteral(this, argument); } internal sealed partial class ConversionOperation : Operation, IConversionOperation { internal ConversionOperation(IOperation operand, IConvertibleConversion conversion, bool isTryCast, bool isChecked, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); ConversionConvertible = conversion; IsTryCast = isTryCast; IsChecked = isChecked; OperationConstantValue = constantValue; Type = type; } public IOperation Operand { get; } internal IConvertibleConversion ConversionConvertible { get; } public CommonConversion Conversion => ConversionConvertible.ToCommonConversion(); public bool IsTryCast { get; } public bool IsChecked { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Conversion; public override void Accept(OperationVisitor visitor) => visitor.VisitConversion(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConversion(this, argument); } internal sealed partial class InvocationOperation : Operation, IInvocationOperation { internal InvocationOperation(IMethodSymbol targetMethod, IOperation? instance, bool isVirtual, ImmutableArray<IArgumentOperation> arguments, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { TargetMethod = targetMethod; Instance = SetParentOperation(instance, this); IsVirtual = isVirtual; Arguments = SetParentOperation(arguments, this); Type = type; } public IMethodSymbol TargetMethod { get; } public IOperation? Instance { get; } public bool IsVirtual { get; } public ImmutableArray<IArgumentOperation> Arguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, 1 when index < Arguments.Length => Arguments[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: if (!Arguments.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Arguments.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Invocation; public override void Accept(OperationVisitor visitor) => visitor.VisitInvocation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInvocation(this, argument); } internal sealed partial class ArrayElementReferenceOperation : Operation, IArrayElementReferenceOperation { internal ArrayElementReferenceOperation(IOperation arrayReference, ImmutableArray<IOperation> indices, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ArrayReference = SetParentOperation(arrayReference, this); Indices = SetParentOperation(indices, this); Type = type; } public IOperation ArrayReference { get; } public ImmutableArray<IOperation> Indices { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when ArrayReference != null => ArrayReference, 1 when index < Indices.Length => Indices[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (ArrayReference != null) return (true, 0, 0); else goto case 0; case 0: if (!Indices.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Indices.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ArrayElementReference; public override void Accept(OperationVisitor visitor) => visitor.VisitArrayElementReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitArrayElementReference(this, argument); } internal sealed partial class LocalReferenceOperation : Operation, ILocalReferenceOperation { internal LocalReferenceOperation(ILocalSymbol local, bool isDeclaration, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Local = local; IsDeclaration = isDeclaration; OperationConstantValue = constantValue; Type = type; } public ILocalSymbol Local { get; } public bool IsDeclaration { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.LocalReference; public override void Accept(OperationVisitor visitor) => visitor.VisitLocalReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLocalReference(this, argument); } internal sealed partial class ParameterReferenceOperation : Operation, IParameterReferenceOperation { internal ParameterReferenceOperation(IParameterSymbol parameter, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Parameter = parameter; Type = type; } public IParameterSymbol Parameter { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ParameterReference; public override void Accept(OperationVisitor visitor) => visitor.VisitParameterReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitParameterReference(this, argument); } internal abstract partial class BaseMemberReferenceOperation : Operation, IMemberReferenceOperation { protected BaseMemberReferenceOperation(IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Instance = SetParentOperation(instance, this); } public IOperation? Instance { get; } } internal sealed partial class FieldReferenceOperation : BaseMemberReferenceOperation, IFieldReferenceOperation { internal FieldReferenceOperation(IFieldSymbol field, bool isDeclaration, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(instance, semanticModel, syntax, isImplicit) { Field = field; IsDeclaration = isDeclaration; OperationConstantValue = constantValue; Type = type; } public IFieldSymbol Field { get; } public bool IsDeclaration { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.FieldReference; public override void Accept(OperationVisitor visitor) => visitor.VisitFieldReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFieldReference(this, argument); } internal sealed partial class MethodReferenceOperation : BaseMemberReferenceOperation, IMethodReferenceOperation { internal MethodReferenceOperation(IMethodSymbol method, bool isVirtual, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(instance, semanticModel, syntax, isImplicit) { Method = method; IsVirtual = isVirtual; Type = type; } public IMethodSymbol Method { get; } public bool IsVirtual { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.MethodReference; public override void Accept(OperationVisitor visitor) => visitor.VisitMethodReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitMethodReference(this, argument); } internal sealed partial class PropertyReferenceOperation : BaseMemberReferenceOperation, IPropertyReferenceOperation { internal PropertyReferenceOperation(IPropertySymbol property, ImmutableArray<IArgumentOperation> arguments, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(instance, semanticModel, syntax, isImplicit) { Property = property; Arguments = SetParentOperation(arguments, this); Type = type; } public IPropertySymbol Property { get; } public ImmutableArray<IArgumentOperation> Arguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, 1 when index < Arguments.Length => Arguments[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: if (!Arguments.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Arguments.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.PropertyReference; public override void Accept(OperationVisitor visitor) => visitor.VisitPropertyReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPropertyReference(this, argument); } internal sealed partial class EventReferenceOperation : BaseMemberReferenceOperation, IEventReferenceOperation { internal EventReferenceOperation(IEventSymbol @event, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(instance, semanticModel, syntax, isImplicit) { Event = @event; Type = type; } public IEventSymbol Event { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.EventReference; public override void Accept(OperationVisitor visitor) => visitor.VisitEventReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitEventReference(this, argument); } internal sealed partial class UnaryOperation : Operation, IUnaryOperation { internal UnaryOperation(UnaryOperatorKind operatorKind, IOperation operand, bool isLifted, bool isChecked, IMethodSymbol? operatorMethod, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; Operand = SetParentOperation(operand, this); IsLifted = isLifted; IsChecked = isChecked; OperatorMethod = operatorMethod; OperationConstantValue = constantValue; Type = type; } public UnaryOperatorKind OperatorKind { get; } public IOperation Operand { get; } public bool IsLifted { get; } public bool IsChecked { get; } public IMethodSymbol? OperatorMethod { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Unary; public override void Accept(OperationVisitor visitor) => visitor.VisitUnaryOperator(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitUnaryOperator(this, argument); } internal sealed partial class BinaryOperation : Operation, IBinaryOperation { internal BinaryOperation(BinaryOperatorKind operatorKind, IOperation leftOperand, IOperation rightOperand, bool isLifted, bool isChecked, bool isCompareText, IMethodSymbol? operatorMethod, IMethodSymbol? unaryOperatorMethod, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; LeftOperand = SetParentOperation(leftOperand, this); RightOperand = SetParentOperation(rightOperand, this); IsLifted = isLifted; IsChecked = isChecked; IsCompareText = isCompareText; OperatorMethod = operatorMethod; UnaryOperatorMethod = unaryOperatorMethod; OperationConstantValue = constantValue; Type = type; } public BinaryOperatorKind OperatorKind { get; } public IOperation LeftOperand { get; } public IOperation RightOperand { get; } public bool IsLifted { get; } public bool IsChecked { get; } public bool IsCompareText { get; } public IMethodSymbol? OperatorMethod { get; } public IMethodSymbol? UnaryOperatorMethod { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LeftOperand != null => LeftOperand, 1 when RightOperand != null => RightOperand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LeftOperand != null) return (true, 0, 0); else goto case 0; case 0: if (RightOperand != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Binary; public override void Accept(OperationVisitor visitor) => visitor.VisitBinaryOperator(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitBinaryOperator(this, argument); } internal sealed partial class ConditionalOperation : Operation, IConditionalOperation { internal ConditionalOperation(IOperation condition, IOperation whenTrue, IOperation? whenFalse, bool isRef, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Condition = SetParentOperation(condition, this); WhenTrue = SetParentOperation(whenTrue, this); WhenFalse = SetParentOperation(whenFalse, this); IsRef = isRef; OperationConstantValue = constantValue; Type = type; } public IOperation Condition { get; } public IOperation WhenTrue { get; } public IOperation? WhenFalse { get; } public bool IsRef { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Condition != null => Condition, 1 when WhenTrue != null => WhenTrue, 2 when WhenFalse != null => WhenFalse, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Condition != null) return (true, 0, 0); else goto case 0; case 0: if (WhenTrue != null) return (true, 1, 0); else goto case 1; case 1: if (WhenFalse != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Conditional; public override void Accept(OperationVisitor visitor) => visitor.VisitConditional(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConditional(this, argument); } internal sealed partial class CoalesceOperation : Operation, ICoalesceOperation { internal CoalesceOperation(IOperation value, IOperation whenNull, IConvertibleConversion valueConversion, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); WhenNull = SetParentOperation(whenNull, this); ValueConversionConvertible = valueConversion; OperationConstantValue = constantValue; Type = type; } public IOperation Value { get; } public IOperation WhenNull { get; } internal IConvertibleConversion ValueConversionConvertible { get; } public CommonConversion ValueConversion => ValueConversionConvertible.ToCommonConversion(); protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when WhenNull != null => WhenNull, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (WhenNull != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Coalesce; public override void Accept(OperationVisitor visitor) => visitor.VisitCoalesce(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCoalesce(this, argument); } internal sealed partial class AnonymousFunctionOperation : Operation, IAnonymousFunctionOperation { internal AnonymousFunctionOperation(IMethodSymbol symbol, IBlockOperation body, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Symbol = symbol; Body = SetParentOperation(body, this); } public IMethodSymbol Symbol { get; } public IBlockOperation Body { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Body != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.AnonymousFunction; public override void Accept(OperationVisitor visitor) => visitor.VisitAnonymousFunction(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAnonymousFunction(this, argument); } internal sealed partial class ObjectCreationOperation : Operation, IObjectCreationOperation { internal ObjectCreationOperation(IMethodSymbol? constructor, IObjectOrCollectionInitializerOperation? initializer, ImmutableArray<IArgumentOperation> arguments, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Constructor = constructor; Initializer = SetParentOperation(initializer, this); Arguments = SetParentOperation(arguments, this); OperationConstantValue = constantValue; Type = type; } public IMethodSymbol? Constructor { get; } public IObjectOrCollectionInitializerOperation? Initializer { get; } public ImmutableArray<IArgumentOperation> Arguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Arguments.Length => Arguments[index], 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Arguments.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Arguments.Length: return (true, 0, previousIndex + 1); case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.ObjectCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitObjectCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitObjectCreation(this, argument); } internal sealed partial class TypeParameterObjectCreationOperation : Operation, ITypeParameterObjectCreationOperation { internal TypeParameterObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Initializer = SetParentOperation(initializer, this); Type = type; } public IObjectOrCollectionInitializerOperation? Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Initializer != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TypeParameterObjectCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitTypeParameterObjectCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTypeParameterObjectCreation(this, argument); } internal sealed partial class ArrayCreationOperation : Operation, IArrayCreationOperation { internal ArrayCreationOperation(ImmutableArray<IOperation> dimensionSizes, IArrayInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { DimensionSizes = SetParentOperation(dimensionSizes, this); Initializer = SetParentOperation(initializer, this); Type = type; } public ImmutableArray<IOperation> DimensionSizes { get; } public IArrayInitializerOperation? Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < DimensionSizes.Length => DimensionSizes[index], 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!DimensionSizes.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < DimensionSizes.Length: return (true, 0, previousIndex + 1); case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ArrayCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitArrayCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitArrayCreation(this, argument); } internal sealed partial class InstanceReferenceOperation : Operation, IInstanceReferenceOperation { internal InstanceReferenceOperation(InstanceReferenceKind referenceKind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ReferenceKind = referenceKind; Type = type; } public InstanceReferenceKind ReferenceKind { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.InstanceReference; public override void Accept(OperationVisitor visitor) => visitor.VisitInstanceReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInstanceReference(this, argument); } internal sealed partial class IsTypeOperation : Operation, IIsTypeOperation { internal IsTypeOperation(IOperation valueOperand, ITypeSymbol typeOperand, bool isNegated, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ValueOperand = SetParentOperation(valueOperand, this); TypeOperand = typeOperand; IsNegated = isNegated; Type = type; } public IOperation ValueOperand { get; } public ITypeSymbol TypeOperand { get; } public bool IsNegated { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when ValueOperand != null => ValueOperand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (ValueOperand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.IsType; public override void Accept(OperationVisitor visitor) => visitor.VisitIsType(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitIsType(this, argument); } internal sealed partial class AwaitOperation : Operation, IAwaitOperation { internal AwaitOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operation = SetParentOperation(operation, this); Type = type; } public IOperation Operation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Await; public override void Accept(OperationVisitor visitor) => visitor.VisitAwait(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAwait(this, argument); } internal abstract partial class BaseAssignmentOperation : Operation, IAssignmentOperation { protected BaseAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Target = SetParentOperation(target, this); Value = SetParentOperation(value, this); } public IOperation Target { get; } public IOperation Value { get; } } internal sealed partial class SimpleAssignmentOperation : BaseAssignmentOperation, ISimpleAssignmentOperation { internal SimpleAssignmentOperation(bool isRef, IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(target, value, semanticModel, syntax, isImplicit) { IsRef = isRef; OperationConstantValue = constantValue; Type = type; } public bool IsRef { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, 1 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: if (Value != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.SimpleAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitSimpleAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSimpleAssignment(this, argument); } internal sealed partial class CompoundAssignmentOperation : BaseAssignmentOperation, ICompoundAssignmentOperation { internal CompoundAssignmentOperation(IConvertibleConversion inConversion, IConvertibleConversion outConversion, BinaryOperatorKind operatorKind, bool isLifted, bool isChecked, IMethodSymbol? operatorMethod, IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(target, value, semanticModel, syntax, isImplicit) { InConversionConvertible = inConversion; OutConversionConvertible = outConversion; OperatorKind = operatorKind; IsLifted = isLifted; IsChecked = isChecked; OperatorMethod = operatorMethod; Type = type; } internal IConvertibleConversion InConversionConvertible { get; } public CommonConversion InConversion => InConversionConvertible.ToCommonConversion(); internal IConvertibleConversion OutConversionConvertible { get; } public CommonConversion OutConversion => OutConversionConvertible.ToCommonConversion(); public BinaryOperatorKind OperatorKind { get; } public bool IsLifted { get; } public bool IsChecked { get; } public IMethodSymbol? OperatorMethod { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, 1 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: if (Value != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CompoundAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitCompoundAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCompoundAssignment(this, argument); } internal sealed partial class ParenthesizedOperation : Operation, IParenthesizedOperation { internal ParenthesizedOperation(IOperation operand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); OperationConstantValue = constantValue; Type = type; } public IOperation Operand { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Parenthesized; public override void Accept(OperationVisitor visitor) => visitor.VisitParenthesized(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitParenthesized(this, argument); } internal sealed partial class EventAssignmentOperation : Operation, IEventAssignmentOperation { internal EventAssignmentOperation(IOperation eventReference, IOperation handlerValue, bool adds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { EventReference = SetParentOperation(eventReference, this); HandlerValue = SetParentOperation(handlerValue, this); Adds = adds; Type = type; } public IOperation EventReference { get; } public IOperation HandlerValue { get; } public bool Adds { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when EventReference != null => EventReference, 1 when HandlerValue != null => HandlerValue, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (EventReference != null) return (true, 0, 0); else goto case 0; case 0: if (HandlerValue != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.EventAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitEventAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitEventAssignment(this, argument); } internal sealed partial class ConditionalAccessOperation : Operation, IConditionalAccessOperation { internal ConditionalAccessOperation(IOperation operation, IOperation whenNotNull, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operation = SetParentOperation(operation, this); WhenNotNull = SetParentOperation(whenNotNull, this); Type = type; } public IOperation Operation { get; } public IOperation WhenNotNull { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, 1 when WhenNotNull != null => WhenNotNull, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: if (WhenNotNull != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ConditionalAccess; public override void Accept(OperationVisitor visitor) => visitor.VisitConditionalAccess(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConditionalAccess(this, argument); } internal sealed partial class ConditionalAccessInstanceOperation : Operation, IConditionalAccessInstanceOperation { internal ConditionalAccessInstanceOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ConditionalAccessInstance; public override void Accept(OperationVisitor visitor) => visitor.VisitConditionalAccessInstance(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConditionalAccessInstance(this, argument); } internal sealed partial class InterpolatedStringOperation : Operation, IInterpolatedStringOperation { internal InterpolatedStringOperation(ImmutableArray<IInterpolatedStringContentOperation> parts, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Parts = SetParentOperation(parts, this); OperationConstantValue = constantValue; Type = type; } public ImmutableArray<IInterpolatedStringContentOperation> Parts { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Parts.Length => Parts[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Parts.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Parts.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.InterpolatedString; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolatedString(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolatedString(this, argument); } internal sealed partial class AnonymousObjectCreationOperation : Operation, IAnonymousObjectCreationOperation { internal AnonymousObjectCreationOperation(ImmutableArray<IOperation> initializers, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Initializers = SetParentOperation(initializers, this); Type = type; } public ImmutableArray<IOperation> Initializers { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Initializers.Length => Initializers[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Initializers.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Initializers.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.AnonymousObjectCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitAnonymousObjectCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAnonymousObjectCreation(this, argument); } internal sealed partial class ObjectOrCollectionInitializerOperation : Operation, IObjectOrCollectionInitializerOperation { internal ObjectOrCollectionInitializerOperation(ImmutableArray<IOperation> initializers, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Initializers = SetParentOperation(initializers, this); Type = type; } public ImmutableArray<IOperation> Initializers { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Initializers.Length => Initializers[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Initializers.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Initializers.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ObjectOrCollectionInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitObjectOrCollectionInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitObjectOrCollectionInitializer(this, argument); } internal sealed partial class MemberInitializerOperation : Operation, IMemberInitializerOperation { internal MemberInitializerOperation(IOperation initializedMember, IObjectOrCollectionInitializerOperation initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { InitializedMember = SetParentOperation(initializedMember, this); Initializer = SetParentOperation(initializer, this); Type = type; } public IOperation InitializedMember { get; } public IObjectOrCollectionInitializerOperation Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when InitializedMember != null => InitializedMember, 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (InitializedMember != null) return (true, 0, 0); else goto case 0; case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.MemberInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitMemberInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitMemberInitializer(this, argument); } internal sealed partial class NameOfOperation : Operation, INameOfOperation { internal NameOfOperation(IOperation argument, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Argument = SetParentOperation(argument, this); OperationConstantValue = constantValue; Type = type; } public IOperation Argument { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Argument != null => Argument, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Argument != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.NameOf; public override void Accept(OperationVisitor visitor) => visitor.VisitNameOf(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitNameOf(this, argument); } internal sealed partial class TupleOperation : Operation, ITupleOperation { internal TupleOperation(ImmutableArray<IOperation> elements, ITypeSymbol? naturalType, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Elements = SetParentOperation(elements, this); NaturalType = naturalType; Type = type; } public ImmutableArray<IOperation> Elements { get; } public ITypeSymbol? NaturalType { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Elements.Length => Elements[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Elements.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Elements.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Tuple; public override void Accept(OperationVisitor visitor) => visitor.VisitTuple(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTuple(this, argument); } internal sealed partial class DynamicMemberReferenceOperation : Operation, IDynamicMemberReferenceOperation { internal DynamicMemberReferenceOperation(IOperation? instance, string memberName, ImmutableArray<ITypeSymbol> typeArguments, ITypeSymbol? containingType, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Instance = SetParentOperation(instance, this); MemberName = memberName; TypeArguments = typeArguments; ContainingType = containingType; Type = type; } public IOperation? Instance { get; } public string MemberName { get; } public ImmutableArray<ITypeSymbol> TypeArguments { get; } public ITypeSymbol? ContainingType { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DynamicMemberReference; public override void Accept(OperationVisitor visitor) => visitor.VisitDynamicMemberReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDynamicMemberReference(this, argument); } internal sealed partial class TranslatedQueryOperation : Operation, ITranslatedQueryOperation { internal TranslatedQueryOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operation = SetParentOperation(operation, this); Type = type; } public IOperation Operation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TranslatedQuery; public override void Accept(OperationVisitor visitor) => visitor.VisitTranslatedQuery(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTranslatedQuery(this, argument); } internal sealed partial class DelegateCreationOperation : Operation, IDelegateCreationOperation { internal DelegateCreationOperation(IOperation target, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Target = SetParentOperation(target, this); Type = type; } public IOperation Target { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DelegateCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitDelegateCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDelegateCreation(this, argument); } internal sealed partial class DefaultValueOperation : Operation, IDefaultValueOperation { internal DefaultValueOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperationConstantValue = constantValue; Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.DefaultValue; public override void Accept(OperationVisitor visitor) => visitor.VisitDefaultValue(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDefaultValue(this, argument); } internal sealed partial class TypeOfOperation : Operation, ITypeOfOperation { internal TypeOfOperation(ITypeSymbol typeOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { TypeOperand = typeOperand; Type = type; } public ITypeSymbol TypeOperand { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TypeOf; public override void Accept(OperationVisitor visitor) => visitor.VisitTypeOf(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTypeOf(this, argument); } internal sealed partial class SizeOfOperation : Operation, ISizeOfOperation { internal SizeOfOperation(ITypeSymbol typeOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { TypeOperand = typeOperand; OperationConstantValue = constantValue; Type = type; } public ITypeSymbol TypeOperand { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.SizeOf; public override void Accept(OperationVisitor visitor) => visitor.VisitSizeOf(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSizeOf(this, argument); } internal sealed partial class AddressOfOperation : Operation, IAddressOfOperation { internal AddressOfOperation(IOperation reference, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Reference = SetParentOperation(reference, this); Type = type; } public IOperation Reference { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Reference != null => Reference, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Reference != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.AddressOf; public override void Accept(OperationVisitor visitor) => visitor.VisitAddressOf(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAddressOf(this, argument); } internal sealed partial class IsPatternOperation : Operation, IIsPatternOperation { internal IsPatternOperation(IOperation value, IPatternOperation pattern, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); Pattern = SetParentOperation(pattern, this); Type = type; } public IOperation Value { get; } public IPatternOperation Pattern { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when Pattern != null => Pattern, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (Pattern != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.IsPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitIsPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitIsPattern(this, argument); } internal sealed partial class IncrementOrDecrementOperation : Operation, IIncrementOrDecrementOperation { internal IncrementOrDecrementOperation(bool isPostfix, bool isLifted, bool isChecked, IOperation target, IMethodSymbol? operatorMethod, OperationKind kind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { IsPostfix = isPostfix; IsLifted = isLifted; IsChecked = isChecked; Target = SetParentOperation(target, this); OperatorMethod = operatorMethod; Type = type; Kind = kind; } public bool IsPostfix { get; } public bool IsLifted { get; } public bool IsChecked { get; } public IOperation Target { get; } public IMethodSymbol? OperatorMethod { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind { get; } public override void Accept(OperationVisitor visitor) => visitor.VisitIncrementOrDecrement(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitIncrementOrDecrement(this, argument); } internal sealed partial class ThrowOperation : Operation, IThrowOperation { internal ThrowOperation(IOperation? exception, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Exception = SetParentOperation(exception, this); Type = type; } public IOperation? Exception { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Exception != null => Exception, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Exception != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Throw; public override void Accept(OperationVisitor visitor) => visitor.VisitThrow(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitThrow(this, argument); } internal sealed partial class DeconstructionAssignmentOperation : BaseAssignmentOperation, IDeconstructionAssignmentOperation { internal DeconstructionAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(target, value, semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, 1 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: if (Value != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DeconstructionAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitDeconstructionAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDeconstructionAssignment(this, argument); } internal sealed partial class DeclarationExpressionOperation : Operation, IDeclarationExpressionOperation { internal DeclarationExpressionOperation(IOperation expression, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Expression = SetParentOperation(expression, this); Type = type; } public IOperation Expression { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Expression != null => Expression, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Expression != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DeclarationExpression; public override void Accept(OperationVisitor visitor) => visitor.VisitDeclarationExpression(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDeclarationExpression(this, argument); } internal sealed partial class OmittedArgumentOperation : Operation, IOmittedArgumentOperation { internal OmittedArgumentOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.OmittedArgument; public override void Accept(OperationVisitor visitor) => visitor.VisitOmittedArgument(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitOmittedArgument(this, argument); } internal abstract partial class BaseSymbolInitializerOperation : Operation, ISymbolInitializerOperation { protected BaseSymbolInitializerOperation(ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Locals = locals; Value = SetParentOperation(value, this); } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation Value { get; } } internal sealed partial class FieldInitializerOperation : BaseSymbolInitializerOperation, IFieldInitializerOperation { internal FieldInitializerOperation(ImmutableArray<IFieldSymbol> initializedFields, ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(locals, value, semanticModel, syntax, isImplicit) { InitializedFields = initializedFields; } public ImmutableArray<IFieldSymbol> InitializedFields { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.FieldInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitFieldInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFieldInitializer(this, argument); } internal sealed partial class VariableInitializerOperation : BaseSymbolInitializerOperation, IVariableInitializerOperation { internal VariableInitializerOperation(ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(locals, value, semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.VariableInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitVariableInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitVariableInitializer(this, argument); } internal sealed partial class PropertyInitializerOperation : BaseSymbolInitializerOperation, IPropertyInitializerOperation { internal PropertyInitializerOperation(ImmutableArray<IPropertySymbol> initializedProperties, ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(locals, value, semanticModel, syntax, isImplicit) { InitializedProperties = initializedProperties; } public ImmutableArray<IPropertySymbol> InitializedProperties { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.PropertyInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitPropertyInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPropertyInitializer(this, argument); } internal sealed partial class ParameterInitializerOperation : BaseSymbolInitializerOperation, IParameterInitializerOperation { internal ParameterInitializerOperation(IParameterSymbol parameter, ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(locals, value, semanticModel, syntax, isImplicit) { Parameter = parameter; } public IParameterSymbol Parameter { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ParameterInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitParameterInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitParameterInitializer(this, argument); } internal sealed partial class ArrayInitializerOperation : Operation, IArrayInitializerOperation { internal ArrayInitializerOperation(ImmutableArray<IOperation> elementValues, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ElementValues = SetParentOperation(elementValues, this); } public ImmutableArray<IOperation> ElementValues { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < ElementValues.Length => ElementValues[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!ElementValues.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < ElementValues.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ArrayInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitArrayInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitArrayInitializer(this, argument); } internal sealed partial class VariableDeclaratorOperation : Operation, IVariableDeclaratorOperation { internal VariableDeclaratorOperation(ILocalSymbol symbol, IVariableInitializerOperation? initializer, ImmutableArray<IOperation> ignoredArguments, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Symbol = symbol; Initializer = SetParentOperation(initializer, this); IgnoredArguments = SetParentOperation(ignoredArguments, this); } public ILocalSymbol Symbol { get; } public IVariableInitializerOperation? Initializer { get; } public ImmutableArray<IOperation> IgnoredArguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < IgnoredArguments.Length => IgnoredArguments[index], 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!IgnoredArguments.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < IgnoredArguments.Length: return (true, 0, previousIndex + 1); case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.VariableDeclarator; public override void Accept(OperationVisitor visitor) => visitor.VisitVariableDeclarator(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitVariableDeclarator(this, argument); } internal sealed partial class VariableDeclarationOperation : Operation, IVariableDeclarationOperation { internal VariableDeclarationOperation(ImmutableArray<IVariableDeclaratorOperation> declarators, IVariableInitializerOperation? initializer, ImmutableArray<IOperation> ignoredDimensions, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Declarators = SetParentOperation(declarators, this); Initializer = SetParentOperation(initializer, this); IgnoredDimensions = SetParentOperation(ignoredDimensions, this); } public ImmutableArray<IVariableDeclaratorOperation> Declarators { get; } public IVariableInitializerOperation? Initializer { get; } public ImmutableArray<IOperation> IgnoredDimensions { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < IgnoredDimensions.Length => IgnoredDimensions[index], 1 when index < Declarators.Length => Declarators[index], 2 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!IgnoredDimensions.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < IgnoredDimensions.Length: return (true, 0, previousIndex + 1); case 0: if (!Declarators.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Declarators.Length: return (true, 1, previousIndex + 1); case 1: if (Initializer != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.VariableDeclaration; public override void Accept(OperationVisitor visitor) => visitor.VisitVariableDeclaration(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitVariableDeclaration(this, argument); } internal sealed partial class ArgumentOperation : Operation, IArgumentOperation { internal ArgumentOperation(ArgumentKind argumentKind, IParameterSymbol? parameter, IOperation value, IConvertibleConversion inConversion, IConvertibleConversion outConversion, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ArgumentKind = argumentKind; Parameter = parameter; Value = SetParentOperation(value, this); InConversionConvertible = inConversion; OutConversionConvertible = outConversion; } public ArgumentKind ArgumentKind { get; } public IParameterSymbol? Parameter { get; } public IOperation Value { get; } internal IConvertibleConversion InConversionConvertible { get; } public CommonConversion InConversion => InConversionConvertible.ToCommonConversion(); internal IConvertibleConversion OutConversionConvertible { get; } public CommonConversion OutConversion => OutConversionConvertible.ToCommonConversion(); protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Argument; public override void Accept(OperationVisitor visitor) => visitor.VisitArgument(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitArgument(this, argument); } internal sealed partial class CatchClauseOperation : Operation, ICatchClauseOperation { internal CatchClauseOperation(IOperation? exceptionDeclarationOrExpression, ITypeSymbol exceptionType, ImmutableArray<ILocalSymbol> locals, IOperation? filter, IBlockOperation handler, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ExceptionDeclarationOrExpression = SetParentOperation(exceptionDeclarationOrExpression, this); ExceptionType = exceptionType; Locals = locals; Filter = SetParentOperation(filter, this); Handler = SetParentOperation(handler, this); } public IOperation? ExceptionDeclarationOrExpression { get; } public ITypeSymbol ExceptionType { get; } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation? Filter { get; } public IBlockOperation Handler { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when ExceptionDeclarationOrExpression != null => ExceptionDeclarationOrExpression, 1 when Filter != null => Filter, 2 when Handler != null => Handler, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (ExceptionDeclarationOrExpression != null) return (true, 0, 0); else goto case 0; case 0: if (Filter != null) return (true, 1, 0); else goto case 1; case 1: if (Handler != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CatchClause; public override void Accept(OperationVisitor visitor) => visitor.VisitCatchClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCatchClause(this, argument); } internal sealed partial class SwitchCaseOperation : Operation, ISwitchCaseOperation { internal SwitchCaseOperation(ImmutableArray<ICaseClauseOperation> clauses, ImmutableArray<IOperation> body, ImmutableArray<ILocalSymbol> locals, IOperation? condition, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Clauses = SetParentOperation(clauses, this); Body = SetParentOperation(body, this); Locals = locals; Condition = SetParentOperation(condition, this); } public ImmutableArray<ICaseClauseOperation> Clauses { get; } public ImmutableArray<IOperation> Body { get; } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation? Condition { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Clauses.Length => Clauses[index], 1 when index < Body.Length => Body[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Clauses.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Clauses.Length: return (true, 0, previousIndex + 1); case 0: if (!Body.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Body.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.SwitchCase; public override void Accept(OperationVisitor visitor) => visitor.VisitSwitchCase(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSwitchCase(this, argument); } internal abstract partial class BaseCaseClauseOperation : Operation, ICaseClauseOperation { protected BaseCaseClauseOperation(ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Label = label; } public abstract CaseKind CaseKind { get; } public ILabelSymbol? Label { get; } } internal sealed partial class DefaultCaseClauseOperation : BaseCaseClauseOperation, IDefaultCaseClauseOperation { internal DefaultCaseClauseOperation(ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitDefaultCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDefaultCaseClause(this, argument); } internal sealed partial class PatternCaseClauseOperation : BaseCaseClauseOperation, IPatternCaseClauseOperation { internal PatternCaseClauseOperation(ILabelSymbol label, IPatternOperation pattern, IOperation? guard, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { Pattern = SetParentOperation(pattern, this); Guard = SetParentOperation(guard, this); } public new ILabelSymbol Label => base.Label!; public IPatternOperation Pattern { get; } public IOperation? Guard { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Pattern != null => Pattern, 1 when Guard != null => Guard, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Pattern != null) return (true, 0, 0); else goto case 0; case 0: if (Guard != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitPatternCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPatternCaseClause(this, argument); } internal sealed partial class RangeCaseClauseOperation : BaseCaseClauseOperation, IRangeCaseClauseOperation { internal RangeCaseClauseOperation(IOperation minimumValue, IOperation maximumValue, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { MinimumValue = SetParentOperation(minimumValue, this); MaximumValue = SetParentOperation(maximumValue, this); } public IOperation MinimumValue { get; } public IOperation MaximumValue { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when MinimumValue != null => MinimumValue, 1 when MaximumValue != null => MaximumValue, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (MinimumValue != null) return (true, 0, 0); else goto case 0; case 0: if (MaximumValue != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitRangeCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRangeCaseClause(this, argument); } internal sealed partial class RelationalCaseClauseOperation : BaseCaseClauseOperation, IRelationalCaseClauseOperation { internal RelationalCaseClauseOperation(IOperation value, BinaryOperatorKind relation, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); Relation = relation; } public IOperation Value { get; } public BinaryOperatorKind Relation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitRelationalCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRelationalCaseClause(this, argument); } internal sealed partial class SingleValueCaseClauseOperation : BaseCaseClauseOperation, ISingleValueCaseClauseOperation { internal SingleValueCaseClauseOperation(IOperation value, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitSingleValueCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSingleValueCaseClause(this, argument); } internal abstract partial class BaseInterpolatedStringContentOperation : Operation, IInterpolatedStringContentOperation { protected BaseInterpolatedStringContentOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { } } internal sealed partial class InterpolatedStringTextOperation : BaseInterpolatedStringContentOperation, IInterpolatedStringTextOperation { internal InterpolatedStringTextOperation(IOperation text, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Text = SetParentOperation(text, this); } public IOperation Text { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Text != null => Text, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Text != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.InterpolatedStringText; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolatedStringText(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolatedStringText(this, argument); } internal sealed partial class InterpolationOperation : BaseInterpolatedStringContentOperation, IInterpolationOperation { internal InterpolationOperation(IOperation expression, IOperation? alignment, IOperation? formatString, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Expression = SetParentOperation(expression, this); Alignment = SetParentOperation(alignment, this); FormatString = SetParentOperation(formatString, this); } public IOperation Expression { get; } public IOperation? Alignment { get; } public IOperation? FormatString { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Expression != null => Expression, 1 when Alignment != null => Alignment, 2 when FormatString != null => FormatString, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Expression != null) return (true, 0, 0); else goto case 0; case 0: if (Alignment != null) return (true, 1, 0); else goto case 1; case 1: if (FormatString != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Interpolation; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolation(this, argument); } internal abstract partial class BasePatternOperation : Operation, IPatternOperation { protected BasePatternOperation(ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { InputType = inputType; NarrowedType = narrowedType; } public ITypeSymbol InputType { get; } public ITypeSymbol NarrowedType { get; } } internal sealed partial class ConstantPatternOperation : BasePatternOperation, IConstantPatternOperation { internal ConstantPatternOperation(IOperation value, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ConstantPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitConstantPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConstantPattern(this, argument); } internal sealed partial class DeclarationPatternOperation : BasePatternOperation, IDeclarationPatternOperation { internal DeclarationPatternOperation(ITypeSymbol? matchedType, bool matchesNull, ISymbol? declaredSymbol, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { MatchedType = matchedType; MatchesNull = matchesNull; DeclaredSymbol = declaredSymbol; } public ITypeSymbol? MatchedType { get; } public bool MatchesNull { get; } public ISymbol? DeclaredSymbol { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DeclarationPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitDeclarationPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDeclarationPattern(this, argument); } internal sealed partial class TupleBinaryOperation : Operation, ITupleBinaryOperation { internal TupleBinaryOperation(BinaryOperatorKind operatorKind, IOperation leftOperand, IOperation rightOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; LeftOperand = SetParentOperation(leftOperand, this); RightOperand = SetParentOperation(rightOperand, this); Type = type; } public BinaryOperatorKind OperatorKind { get; } public IOperation LeftOperand { get; } public IOperation RightOperand { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LeftOperand != null => LeftOperand, 1 when RightOperand != null => RightOperand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LeftOperand != null) return (true, 0, 0); else goto case 0; case 0: if (RightOperand != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TupleBinary; public override void Accept(OperationVisitor visitor) => visitor.VisitTupleBinaryOperator(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTupleBinaryOperator(this, argument); } internal abstract partial class BaseMethodBodyBaseOperation : Operation, IMethodBodyBaseOperation { protected BaseMethodBodyBaseOperation(IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { BlockBody = SetParentOperation(blockBody, this); ExpressionBody = SetParentOperation(expressionBody, this); } public IBlockOperation? BlockBody { get; } public IBlockOperation? ExpressionBody { get; } } internal sealed partial class MethodBodyOperation : BaseMethodBodyBaseOperation, IMethodBodyOperation { internal MethodBodyOperation(IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(blockBody, expressionBody, semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when BlockBody != null => BlockBody, 1 when ExpressionBody != null => ExpressionBody, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (BlockBody != null) return (true, 0, 0); else goto case 0; case 0: if (ExpressionBody != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.MethodBody; public override void Accept(OperationVisitor visitor) => visitor.VisitMethodBodyOperation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitMethodBodyOperation(this, argument); } internal sealed partial class ConstructorBodyOperation : BaseMethodBodyBaseOperation, IConstructorBodyOperation { internal ConstructorBodyOperation(ImmutableArray<ILocalSymbol> locals, IOperation? initializer, IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(blockBody, expressionBody, semanticModel, syntax, isImplicit) { Locals = locals; Initializer = SetParentOperation(initializer, this); } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation? Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Initializer != null => Initializer, 1 when BlockBody != null => BlockBody, 2 when ExpressionBody != null => ExpressionBody, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Initializer != null) return (true, 0, 0); else goto case 0; case 0: if (BlockBody != null) return (true, 1, 0); else goto case 1; case 1: if (ExpressionBody != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ConstructorBody; public override void Accept(OperationVisitor visitor) => visitor.VisitConstructorBodyOperation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConstructorBodyOperation(this, argument); } internal sealed partial class DiscardOperation : Operation, IDiscardOperation { internal DiscardOperation(IDiscardSymbol discardSymbol, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { DiscardSymbol = discardSymbol; Type = type; } public IDiscardSymbol DiscardSymbol { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Discard; public override void Accept(OperationVisitor visitor) => visitor.VisitDiscardOperation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDiscardOperation(this, argument); } internal sealed partial class FlowCaptureOperation : Operation, IFlowCaptureOperation { internal FlowCaptureOperation(CaptureId id, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Id = id; Value = SetParentOperation(value, this); } public CaptureId Id { get; } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.FlowCapture; public override void Accept(OperationVisitor visitor) => visitor.VisitFlowCapture(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFlowCapture(this, argument); } internal sealed partial class FlowCaptureReferenceOperation : Operation, IFlowCaptureReferenceOperation { internal FlowCaptureReferenceOperation(CaptureId id, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Id = id; OperationConstantValue = constantValue; Type = type; } public CaptureId Id { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.FlowCaptureReference; public override void Accept(OperationVisitor visitor) => visitor.VisitFlowCaptureReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFlowCaptureReference(this, argument); } internal sealed partial class IsNullOperation : Operation, IIsNullOperation { internal IsNullOperation(IOperation operand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); OperationConstantValue = constantValue; Type = type; } public IOperation Operand { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.IsNull; public override void Accept(OperationVisitor visitor) => visitor.VisitIsNull(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitIsNull(this, argument); } internal sealed partial class CaughtExceptionOperation : Operation, ICaughtExceptionOperation { internal CaughtExceptionOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaughtException; public override void Accept(OperationVisitor visitor) => visitor.VisitCaughtException(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCaughtException(this, argument); } internal sealed partial class StaticLocalInitializationSemaphoreOperation : Operation, IStaticLocalInitializationSemaphoreOperation { internal StaticLocalInitializationSemaphoreOperation(ILocalSymbol local, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Local = local; Type = type; } public ILocalSymbol Local { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.StaticLocalInitializationSemaphore; public override void Accept(OperationVisitor visitor) => visitor.VisitStaticLocalInitializationSemaphore(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitStaticLocalInitializationSemaphore(this, argument); } internal sealed partial class CoalesceAssignmentOperation : BaseAssignmentOperation, ICoalesceAssignmentOperation { internal CoalesceAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(target, value, semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, 1 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: if (Value != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CoalesceAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitCoalesceAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCoalesceAssignment(this, argument); } internal sealed partial class RangeOperation : Operation, IRangeOperation { internal RangeOperation(IOperation? leftOperand, IOperation? rightOperand, bool isLifted, IMethodSymbol? method, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { LeftOperand = SetParentOperation(leftOperand, this); RightOperand = SetParentOperation(rightOperand, this); IsLifted = isLifted; Method = method; Type = type; } public IOperation? LeftOperand { get; } public IOperation? RightOperand { get; } public bool IsLifted { get; } public IMethodSymbol? Method { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LeftOperand != null => LeftOperand, 1 when RightOperand != null => RightOperand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LeftOperand != null) return (true, 0, 0); else goto case 0; case 0: if (RightOperand != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Range; public override void Accept(OperationVisitor visitor) => visitor.VisitRangeOperation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRangeOperation(this, argument); } internal sealed partial class ReDimOperation : Operation, IReDimOperation { internal ReDimOperation(ImmutableArray<IReDimClauseOperation> clauses, bool preserve, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Clauses = SetParentOperation(clauses, this); Preserve = preserve; } public ImmutableArray<IReDimClauseOperation> Clauses { get; } public bool Preserve { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Clauses.Length => Clauses[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Clauses.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Clauses.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ReDim; public override void Accept(OperationVisitor visitor) => visitor.VisitReDim(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitReDim(this, argument); } internal sealed partial class ReDimClauseOperation : Operation, IReDimClauseOperation { internal ReDimClauseOperation(IOperation operand, ImmutableArray<IOperation> dimensionSizes, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); DimensionSizes = SetParentOperation(dimensionSizes, this); } public IOperation Operand { get; } public ImmutableArray<IOperation> DimensionSizes { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, 1 when index < DimensionSizes.Length => DimensionSizes[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: if (!DimensionSizes.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < DimensionSizes.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ReDimClause; public override void Accept(OperationVisitor visitor) => visitor.VisitReDimClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitReDimClause(this, argument); } internal sealed partial class RecursivePatternOperation : BasePatternOperation, IRecursivePatternOperation { internal RecursivePatternOperation(ITypeSymbol matchedType, ISymbol? deconstructSymbol, ImmutableArray<IPatternOperation> deconstructionSubpatterns, ImmutableArray<IPropertySubpatternOperation> propertySubpatterns, ISymbol? declaredSymbol, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { MatchedType = matchedType; DeconstructSymbol = deconstructSymbol; DeconstructionSubpatterns = SetParentOperation(deconstructionSubpatterns, this); PropertySubpatterns = SetParentOperation(propertySubpatterns, this); DeclaredSymbol = declaredSymbol; } public ITypeSymbol MatchedType { get; } public ISymbol? DeconstructSymbol { get; } public ImmutableArray<IPatternOperation> DeconstructionSubpatterns { get; } public ImmutableArray<IPropertySubpatternOperation> PropertySubpatterns { get; } public ISymbol? DeclaredSymbol { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < DeconstructionSubpatterns.Length => DeconstructionSubpatterns[index], 1 when index < PropertySubpatterns.Length => PropertySubpatterns[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!DeconstructionSubpatterns.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < DeconstructionSubpatterns.Length: return (true, 0, previousIndex + 1); case 0: if (!PropertySubpatterns.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < PropertySubpatterns.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.RecursivePattern; public override void Accept(OperationVisitor visitor) => visitor.VisitRecursivePattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRecursivePattern(this, argument); } internal sealed partial class DiscardPatternOperation : BasePatternOperation, IDiscardPatternOperation { internal DiscardPatternOperation(ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DiscardPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitDiscardPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDiscardPattern(this, argument); } internal sealed partial class SwitchExpressionOperation : Operation, ISwitchExpressionOperation { internal SwitchExpressionOperation(IOperation value, ImmutableArray<ISwitchExpressionArmOperation> arms, bool isExhaustive, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); Arms = SetParentOperation(arms, this); IsExhaustive = isExhaustive; Type = type; } public IOperation Value { get; } public ImmutableArray<ISwitchExpressionArmOperation> Arms { get; } public bool IsExhaustive { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when index < Arms.Length => Arms[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (!Arms.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Arms.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.SwitchExpression; public override void Accept(OperationVisitor visitor) => visitor.VisitSwitchExpression(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSwitchExpression(this, argument); } internal sealed partial class SwitchExpressionArmOperation : Operation, ISwitchExpressionArmOperation { internal SwitchExpressionArmOperation(IPatternOperation pattern, IOperation? guard, IOperation value, ImmutableArray<ILocalSymbol> locals, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Pattern = SetParentOperation(pattern, this); Guard = SetParentOperation(guard, this); Value = SetParentOperation(value, this); Locals = locals; } public IPatternOperation Pattern { get; } public IOperation? Guard { get; } public IOperation Value { get; } public ImmutableArray<ILocalSymbol> Locals { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Pattern != null => Pattern, 1 when Guard != null => Guard, 2 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Pattern != null) return (true, 0, 0); else goto case 0; case 0: if (Guard != null) return (true, 1, 0); else goto case 1; case 1: if (Value != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.SwitchExpressionArm; public override void Accept(OperationVisitor visitor) => visitor.VisitSwitchExpressionArm(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSwitchExpressionArm(this, argument); } internal sealed partial class PropertySubpatternOperation : Operation, IPropertySubpatternOperation { internal PropertySubpatternOperation(IOperation member, IPatternOperation pattern, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Member = SetParentOperation(member, this); Pattern = SetParentOperation(pattern, this); } public IOperation Member { get; } public IPatternOperation Pattern { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Member != null => Member, 1 when Pattern != null => Pattern, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Member != null) return (true, 0, 0); else goto case 0; case 0: if (Pattern != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.PropertySubpattern; public override void Accept(OperationVisitor visitor) => visitor.VisitPropertySubpattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPropertySubpattern(this, argument); } internal sealed partial class AggregateQueryOperation : Operation, IAggregateQueryOperation { internal AggregateQueryOperation(IOperation group, IOperation aggregation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Group = SetParentOperation(group, this); Aggregation = SetParentOperation(aggregation, this); Type = type; } public IOperation Group { get; } public IOperation Aggregation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Group != null => Group, 1 when Aggregation != null => Aggregation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Group != null) return (true, 0, 0); else goto case 0; case 0: if (Aggregation != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitAggregateQuery(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAggregateQuery(this, argument); } internal sealed partial class FixedOperation : Operation, IFixedOperation { internal FixedOperation(ImmutableArray<ILocalSymbol> locals, IVariableDeclarationGroupOperation variables, IOperation body, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Locals = locals; Variables = SetParentOperation(variables, this); Body = SetParentOperation(body, this); } public ImmutableArray<ILocalSymbol> Locals { get; } public IVariableDeclarationGroupOperation Variables { get; } public IOperation Body { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Variables != null => Variables, 1 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Variables != null) return (true, 0, 0); else goto case 0; case 0: if (Body != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitFixed(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFixed(this, argument); } internal sealed partial class NoPiaObjectCreationOperation : Operation, INoPiaObjectCreationOperation { internal NoPiaObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Initializer = SetParentOperation(initializer, this); Type = type; } public IObjectOrCollectionInitializerOperation? Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Initializer != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitNoPiaObjectCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitNoPiaObjectCreation(this, argument); } internal sealed partial class PlaceholderOperation : Operation, IPlaceholderOperation { internal PlaceholderOperation(PlaceholderKind placeholderKind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { PlaceholderKind = placeholderKind; Type = type; } public PlaceholderKind PlaceholderKind { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitPlaceholder(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPlaceholder(this, argument); } internal sealed partial class WithStatementOperation : Operation, IWithStatementOperation { internal WithStatementOperation(IOperation body, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Body = SetParentOperation(body, this); Value = SetParentOperation(value, this); } public IOperation Body { get; } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (Body != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitWithStatement(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitWithStatement(this, argument); } internal sealed partial class UsingDeclarationOperation : Operation, IUsingDeclarationOperation { internal UsingDeclarationOperation(IVariableDeclarationGroupOperation declarationGroup, bool isAsynchronous, DisposeOperationInfo disposeInfo, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { DeclarationGroup = SetParentOperation(declarationGroup, this); IsAsynchronous = isAsynchronous; DisposeInfo = disposeInfo; } public IVariableDeclarationGroupOperation DeclarationGroup { get; } public bool IsAsynchronous { get; } public DisposeOperationInfo DisposeInfo { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when DeclarationGroup != null => DeclarationGroup, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (DeclarationGroup != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.UsingDeclaration; public override void Accept(OperationVisitor visitor) => visitor.VisitUsingDeclaration(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitUsingDeclaration(this, argument); } internal sealed partial class NegatedPatternOperation : BasePatternOperation, INegatedPatternOperation { internal NegatedPatternOperation(IPatternOperation pattern, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { Pattern = SetParentOperation(pattern, this); } public IPatternOperation Pattern { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Pattern != null => Pattern, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Pattern != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.NegatedPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitNegatedPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitNegatedPattern(this, argument); } internal sealed partial class BinaryPatternOperation : BasePatternOperation, IBinaryPatternOperation { internal BinaryPatternOperation(BinaryOperatorKind operatorKind, IPatternOperation leftPattern, IPatternOperation rightPattern, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; LeftPattern = SetParentOperation(leftPattern, this); RightPattern = SetParentOperation(rightPattern, this); } public BinaryOperatorKind OperatorKind { get; } public IPatternOperation LeftPattern { get; } public IPatternOperation RightPattern { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LeftPattern != null => LeftPattern, 1 when RightPattern != null => RightPattern, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LeftPattern != null) return (true, 0, 0); else goto case 0; case 0: if (RightPattern != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.BinaryPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitBinaryPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitBinaryPattern(this, argument); } internal sealed partial class TypePatternOperation : BasePatternOperation, ITypePatternOperation { internal TypePatternOperation(ITypeSymbol matchedType, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { MatchedType = matchedType; } public ITypeSymbol MatchedType { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TypePattern; public override void Accept(OperationVisitor visitor) => visitor.VisitTypePattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTypePattern(this, argument); } internal sealed partial class RelationalPatternOperation : BasePatternOperation, IRelationalPatternOperation { internal RelationalPatternOperation(BinaryOperatorKind operatorKind, IOperation value, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; Value = SetParentOperation(value, this); } public BinaryOperatorKind OperatorKind { get; } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.RelationalPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitRelationalPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRelationalPattern(this, argument); } internal sealed partial class WithOperation : Operation, IWithOperation { internal WithOperation(IOperation operand, IMethodSymbol? cloneMethod, IObjectOrCollectionInitializerOperation initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); CloneMethod = cloneMethod; Initializer = SetParentOperation(initializer, this); Type = type; } public IOperation Operand { get; } public IMethodSymbol? CloneMethod { get; } public IObjectOrCollectionInitializerOperation Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.With; public override void Accept(OperationVisitor visitor) => visitor.VisitWith(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitWith(this, argument); } #endregion #region Cloner internal sealed partial class OperationCloner : OperationVisitor<object?, IOperation> { private static readonly OperationCloner s_instance = new OperationCloner(); /// <summary>Deep clone given IOperation</summary> public static T CloneOperation<T>(T operation) where T : IOperation => s_instance.Visit(operation); public OperationCloner() { } [return: NotNullIfNotNull("node")] private T? Visit<T>(T? node) where T : IOperation? => (T?)Visit(node, argument: null); public override IOperation DefaultVisit(IOperation operation, object? argument) => throw ExceptionUtilities.Unreachable; private ImmutableArray<T> VisitArray<T>(ImmutableArray<T> nodes) where T : IOperation => nodes.SelectAsArray((n, @this) => @this.Visit(n), this)!; private ImmutableArray<(ISymbol, T)> VisitArray<T>(ImmutableArray<(ISymbol, T)> nodes) where T : IOperation => nodes.SelectAsArray((n, @this) => (n.Item1, @this.Visit(n.Item2)), this)!; public override IOperation VisitBlock(IBlockOperation operation, object? argument) { var internalOperation = (BlockOperation)operation; return new BlockOperation(VisitArray(internalOperation.Operations), internalOperation.Locals, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, object? argument) { var internalOperation = (VariableDeclarationGroupOperation)operation; return new VariableDeclarationGroupOperation(VisitArray(internalOperation.Declarations), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitSwitch(ISwitchOperation operation, object? argument) { var internalOperation = (SwitchOperation)operation; return new SwitchOperation(internalOperation.Locals, Visit(internalOperation.Value), VisitArray(internalOperation.Cases), internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitForEachLoop(IForEachLoopOperation operation, object? argument) { var internalOperation = (ForEachLoopOperation)operation; return new ForEachLoopOperation(Visit(internalOperation.LoopControlVariable), Visit(internalOperation.Collection), VisitArray(internalOperation.NextVariables), internalOperation.Info, internalOperation.IsAsynchronous, Visit(internalOperation.Body), internalOperation.Locals, internalOperation.ContinueLabel, internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitForLoop(IForLoopOperation operation, object? argument) { var internalOperation = (ForLoopOperation)operation; return new ForLoopOperation(VisitArray(internalOperation.Before), internalOperation.ConditionLocals, Visit(internalOperation.Condition), VisitArray(internalOperation.AtLoopBottom), Visit(internalOperation.Body), internalOperation.Locals, internalOperation.ContinueLabel, internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitForToLoop(IForToLoopOperation operation, object? argument) { var internalOperation = (ForToLoopOperation)operation; return new ForToLoopOperation(Visit(internalOperation.LoopControlVariable), Visit(internalOperation.InitialValue), Visit(internalOperation.LimitValue), Visit(internalOperation.StepValue), internalOperation.IsChecked, VisitArray(internalOperation.NextVariables), internalOperation.Info, Visit(internalOperation.Body), internalOperation.Locals, internalOperation.ContinueLabel, internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitWhileLoop(IWhileLoopOperation operation, object? argument) { var internalOperation = (WhileLoopOperation)operation; return new WhileLoopOperation(Visit(internalOperation.Condition), internalOperation.ConditionIsTop, internalOperation.ConditionIsUntil, Visit(internalOperation.IgnoredCondition), Visit(internalOperation.Body), internalOperation.Locals, internalOperation.ContinueLabel, internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitLabeled(ILabeledOperation operation, object? argument) { var internalOperation = (LabeledOperation)operation; return new LabeledOperation(internalOperation.Label, Visit(internalOperation.Operation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitBranch(IBranchOperation operation, object? argument) { var internalOperation = (BranchOperation)operation; return new BranchOperation(internalOperation.Target, internalOperation.BranchKind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitEmpty(IEmptyOperation operation, object? argument) { var internalOperation = (EmptyOperation)operation; return new EmptyOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitReturn(IReturnOperation operation, object? argument) { var internalOperation = (ReturnOperation)operation; return new ReturnOperation(Visit(internalOperation.ReturnedValue), internalOperation.Kind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitLock(ILockOperation operation, object? argument) { var internalOperation = (LockOperation)operation; return new LockOperation(Visit(internalOperation.LockedValue), Visit(internalOperation.Body), internalOperation.LockTakenSymbol, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitTry(ITryOperation operation, object? argument) { var internalOperation = (TryOperation)operation; return new TryOperation(Visit(internalOperation.Body), VisitArray(internalOperation.Catches), Visit(internalOperation.Finally), internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitUsing(IUsingOperation operation, object? argument) { var internalOperation = (UsingOperation)operation; return new UsingOperation(Visit(internalOperation.Resources), Visit(internalOperation.Body), internalOperation.Locals, internalOperation.IsAsynchronous, internalOperation.DisposeInfo, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitExpressionStatement(IExpressionStatementOperation operation, object? argument) { var internalOperation = (ExpressionStatementOperation)operation; return new ExpressionStatementOperation(Visit(internalOperation.Operation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitLocalFunction(ILocalFunctionOperation operation, object? argument) { var internalOperation = (LocalFunctionOperation)operation; return new LocalFunctionOperation(internalOperation.Symbol, Visit(internalOperation.Body), Visit(internalOperation.IgnoredBody), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitStop(IStopOperation operation, object? argument) { var internalOperation = (StopOperation)operation; return new StopOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitEnd(IEndOperation operation, object? argument) { var internalOperation = (EndOperation)operation; return new EndOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRaiseEvent(IRaiseEventOperation operation, object? argument) { var internalOperation = (RaiseEventOperation)operation; return new RaiseEventOperation(Visit(internalOperation.EventReference), VisitArray(internalOperation.Arguments), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitLiteral(ILiteralOperation operation, object? argument) { var internalOperation = (LiteralOperation)operation; return new LiteralOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitConversion(IConversionOperation operation, object? argument) { var internalOperation = (ConversionOperation)operation; return new ConversionOperation(Visit(internalOperation.Operand), internalOperation.ConversionConvertible, internalOperation.IsTryCast, internalOperation.IsChecked, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitInvocation(IInvocationOperation operation, object? argument) { var internalOperation = (InvocationOperation)operation; return new InvocationOperation(internalOperation.TargetMethod, Visit(internalOperation.Instance), internalOperation.IsVirtual, VisitArray(internalOperation.Arguments), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitArrayElementReference(IArrayElementReferenceOperation operation, object? argument) { var internalOperation = (ArrayElementReferenceOperation)operation; return new ArrayElementReferenceOperation(Visit(internalOperation.ArrayReference), VisitArray(internalOperation.Indices), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitLocalReference(ILocalReferenceOperation operation, object? argument) { var internalOperation = (LocalReferenceOperation)operation; return new LocalReferenceOperation(internalOperation.Local, internalOperation.IsDeclaration, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitParameterReference(IParameterReferenceOperation operation, object? argument) { var internalOperation = (ParameterReferenceOperation)operation; return new ParameterReferenceOperation(internalOperation.Parameter, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitFieldReference(IFieldReferenceOperation operation, object? argument) { var internalOperation = (FieldReferenceOperation)operation; return new FieldReferenceOperation(internalOperation.Field, internalOperation.IsDeclaration, Visit(internalOperation.Instance), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitMethodReference(IMethodReferenceOperation operation, object? argument) { var internalOperation = (MethodReferenceOperation)operation; return new MethodReferenceOperation(internalOperation.Method, internalOperation.IsVirtual, Visit(internalOperation.Instance), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitPropertyReference(IPropertyReferenceOperation operation, object? argument) { var internalOperation = (PropertyReferenceOperation)operation; return new PropertyReferenceOperation(internalOperation.Property, VisitArray(internalOperation.Arguments), Visit(internalOperation.Instance), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitEventReference(IEventReferenceOperation operation, object? argument) { var internalOperation = (EventReferenceOperation)operation; return new EventReferenceOperation(internalOperation.Event, Visit(internalOperation.Instance), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitUnaryOperator(IUnaryOperation operation, object? argument) { var internalOperation = (UnaryOperation)operation; return new UnaryOperation(internalOperation.OperatorKind, Visit(internalOperation.Operand), internalOperation.IsLifted, internalOperation.IsChecked, internalOperation.OperatorMethod, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitBinaryOperator(IBinaryOperation operation, object? argument) { var internalOperation = (BinaryOperation)operation; return new BinaryOperation(internalOperation.OperatorKind, Visit(internalOperation.LeftOperand), Visit(internalOperation.RightOperand), internalOperation.IsLifted, internalOperation.IsChecked, internalOperation.IsCompareText, internalOperation.OperatorMethod, internalOperation.UnaryOperatorMethod, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitConditional(IConditionalOperation operation, object? argument) { var internalOperation = (ConditionalOperation)operation; return new ConditionalOperation(Visit(internalOperation.Condition), Visit(internalOperation.WhenTrue), Visit(internalOperation.WhenFalse), internalOperation.IsRef, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitCoalesce(ICoalesceOperation operation, object? argument) { var internalOperation = (CoalesceOperation)operation; return new CoalesceOperation(Visit(internalOperation.Value), Visit(internalOperation.WhenNull), internalOperation.ValueConversionConvertible, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitAnonymousFunction(IAnonymousFunctionOperation operation, object? argument) { var internalOperation = (AnonymousFunctionOperation)operation; return new AnonymousFunctionOperation(internalOperation.Symbol, Visit(internalOperation.Body), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitObjectCreation(IObjectCreationOperation operation, object? argument) { var internalOperation = (ObjectCreationOperation)operation; return new ObjectCreationOperation(internalOperation.Constructor, Visit(internalOperation.Initializer), VisitArray(internalOperation.Arguments), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, object? argument) { var internalOperation = (TypeParameterObjectCreationOperation)operation; return new TypeParameterObjectCreationOperation(Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitArrayCreation(IArrayCreationOperation operation, object? argument) { var internalOperation = (ArrayCreationOperation)operation; return new ArrayCreationOperation(VisitArray(internalOperation.DimensionSizes), Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitInstanceReference(IInstanceReferenceOperation operation, object? argument) { var internalOperation = (InstanceReferenceOperation)operation; return new InstanceReferenceOperation(internalOperation.ReferenceKind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitIsType(IIsTypeOperation operation, object? argument) { var internalOperation = (IsTypeOperation)operation; return new IsTypeOperation(Visit(internalOperation.ValueOperand), internalOperation.TypeOperand, internalOperation.IsNegated, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitAwait(IAwaitOperation operation, object? argument) { var internalOperation = (AwaitOperation)operation; return new AwaitOperation(Visit(internalOperation.Operation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitSimpleAssignment(ISimpleAssignmentOperation operation, object? argument) { var internalOperation = (SimpleAssignmentOperation)operation; return new SimpleAssignmentOperation(internalOperation.IsRef, Visit(internalOperation.Target), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitCompoundAssignment(ICompoundAssignmentOperation operation, object? argument) { var internalOperation = (CompoundAssignmentOperation)operation; return new CompoundAssignmentOperation(internalOperation.InConversionConvertible, internalOperation.OutConversionConvertible, internalOperation.OperatorKind, internalOperation.IsLifted, internalOperation.IsChecked, internalOperation.OperatorMethod, Visit(internalOperation.Target), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitParenthesized(IParenthesizedOperation operation, object? argument) { var internalOperation = (ParenthesizedOperation)operation; return new ParenthesizedOperation(Visit(internalOperation.Operand), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitEventAssignment(IEventAssignmentOperation operation, object? argument) { var internalOperation = (EventAssignmentOperation)operation; return new EventAssignmentOperation(Visit(internalOperation.EventReference), Visit(internalOperation.HandlerValue), internalOperation.Adds, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitConditionalAccess(IConditionalAccessOperation operation, object? argument) { var internalOperation = (ConditionalAccessOperation)operation; return new ConditionalAccessOperation(Visit(internalOperation.Operation), Visit(internalOperation.WhenNotNull), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, object? argument) { var internalOperation = (ConditionalAccessInstanceOperation)operation; return new ConditionalAccessInstanceOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitInterpolatedString(IInterpolatedStringOperation operation, object? argument) { var internalOperation = (InterpolatedStringOperation)operation; return new InterpolatedStringOperation(VisitArray(internalOperation.Parts), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, object? argument) { var internalOperation = (AnonymousObjectCreationOperation)operation; return new AnonymousObjectCreationOperation(VisitArray(internalOperation.Initializers), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, object? argument) { var internalOperation = (ObjectOrCollectionInitializerOperation)operation; return new ObjectOrCollectionInitializerOperation(VisitArray(internalOperation.Initializers), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitMemberInitializer(IMemberInitializerOperation operation, object? argument) { var internalOperation = (MemberInitializerOperation)operation; return new MemberInitializerOperation(Visit(internalOperation.InitializedMember), Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitNameOf(INameOfOperation operation, object? argument) { var internalOperation = (NameOfOperation)operation; return new NameOfOperation(Visit(internalOperation.Argument), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitTuple(ITupleOperation operation, object? argument) { var internalOperation = (TupleOperation)operation; return new TupleOperation(VisitArray(internalOperation.Elements), internalOperation.NaturalType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, object? argument) { var internalOperation = (DynamicMemberReferenceOperation)operation; return new DynamicMemberReferenceOperation(Visit(internalOperation.Instance), internalOperation.MemberName, internalOperation.TypeArguments, internalOperation.ContainingType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitTranslatedQuery(ITranslatedQueryOperation operation, object? argument) { var internalOperation = (TranslatedQueryOperation)operation; return new TranslatedQueryOperation(Visit(internalOperation.Operation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDelegateCreation(IDelegateCreationOperation operation, object? argument) { var internalOperation = (DelegateCreationOperation)operation; return new DelegateCreationOperation(Visit(internalOperation.Target), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDefaultValue(IDefaultValueOperation operation, object? argument) { var internalOperation = (DefaultValueOperation)operation; return new DefaultValueOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitTypeOf(ITypeOfOperation operation, object? argument) { var internalOperation = (TypeOfOperation)operation; return new TypeOfOperation(internalOperation.TypeOperand, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitSizeOf(ISizeOfOperation operation, object? argument) { var internalOperation = (SizeOfOperation)operation; return new SizeOfOperation(internalOperation.TypeOperand, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitAddressOf(IAddressOfOperation operation, object? argument) { var internalOperation = (AddressOfOperation)operation; return new AddressOfOperation(Visit(internalOperation.Reference), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitIsPattern(IIsPatternOperation operation, object? argument) { var internalOperation = (IsPatternOperation)operation; return new IsPatternOperation(Visit(internalOperation.Value), Visit(internalOperation.Pattern), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, object? argument) { var internalOperation = (IncrementOrDecrementOperation)operation; return new IncrementOrDecrementOperation(internalOperation.IsPostfix, internalOperation.IsLifted, internalOperation.IsChecked, Visit(internalOperation.Target), internalOperation.OperatorMethod, internalOperation.Kind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitThrow(IThrowOperation operation, object? argument) { var internalOperation = (ThrowOperation)operation; return new ThrowOperation(Visit(internalOperation.Exception), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, object? argument) { var internalOperation = (DeconstructionAssignmentOperation)operation; return new DeconstructionAssignmentOperation(Visit(internalOperation.Target), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDeclarationExpression(IDeclarationExpressionOperation operation, object? argument) { var internalOperation = (DeclarationExpressionOperation)operation; return new DeclarationExpressionOperation(Visit(internalOperation.Expression), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitOmittedArgument(IOmittedArgumentOperation operation, object? argument) { var internalOperation = (OmittedArgumentOperation)operation; return new OmittedArgumentOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitFieldInitializer(IFieldInitializerOperation operation, object? argument) { var internalOperation = (FieldInitializerOperation)operation; return new FieldInitializerOperation(internalOperation.InitializedFields, internalOperation.Locals, Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitVariableInitializer(IVariableInitializerOperation operation, object? argument) { var internalOperation = (VariableInitializerOperation)operation; return new VariableInitializerOperation(internalOperation.Locals, Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitPropertyInitializer(IPropertyInitializerOperation operation, object? argument) { var internalOperation = (PropertyInitializerOperation)operation; return new PropertyInitializerOperation(internalOperation.InitializedProperties, internalOperation.Locals, Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitParameterInitializer(IParameterInitializerOperation operation, object? argument) { var internalOperation = (ParameterInitializerOperation)operation; return new ParameterInitializerOperation(internalOperation.Parameter, internalOperation.Locals, Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitArrayInitializer(IArrayInitializerOperation operation, object? argument) { var internalOperation = (ArrayInitializerOperation)operation; return new ArrayInitializerOperation(VisitArray(internalOperation.ElementValues), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitVariableDeclarator(IVariableDeclaratorOperation operation, object? argument) { var internalOperation = (VariableDeclaratorOperation)operation; return new VariableDeclaratorOperation(internalOperation.Symbol, Visit(internalOperation.Initializer), VisitArray(internalOperation.IgnoredArguments), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitVariableDeclaration(IVariableDeclarationOperation operation, object? argument) { var internalOperation = (VariableDeclarationOperation)operation; return new VariableDeclarationOperation(VisitArray(internalOperation.Declarators), Visit(internalOperation.Initializer), VisitArray(internalOperation.IgnoredDimensions), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitArgument(IArgumentOperation operation, object? argument) { var internalOperation = (ArgumentOperation)operation; return new ArgumentOperation(internalOperation.ArgumentKind, internalOperation.Parameter, Visit(internalOperation.Value), internalOperation.InConversionConvertible, internalOperation.OutConversionConvertible, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitCatchClause(ICatchClauseOperation operation, object? argument) { var internalOperation = (CatchClauseOperation)operation; return new CatchClauseOperation(Visit(internalOperation.ExceptionDeclarationOrExpression), internalOperation.ExceptionType, internalOperation.Locals, Visit(internalOperation.Filter), Visit(internalOperation.Handler), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitSwitchCase(ISwitchCaseOperation operation, object? argument) { var internalOperation = (SwitchCaseOperation)operation; return new SwitchCaseOperation(VisitArray(internalOperation.Clauses), VisitArray(internalOperation.Body), internalOperation.Locals, Visit(internalOperation.Condition), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, object? argument) { var internalOperation = (DefaultCaseClauseOperation)operation; return new DefaultCaseClauseOperation(internalOperation.Label, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitPatternCaseClause(IPatternCaseClauseOperation operation, object? argument) { var internalOperation = (PatternCaseClauseOperation)operation; return new PatternCaseClauseOperation(internalOperation.Label, Visit(internalOperation.Pattern), Visit(internalOperation.Guard), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRangeCaseClause(IRangeCaseClauseOperation operation, object? argument) { var internalOperation = (RangeCaseClauseOperation)operation; return new RangeCaseClauseOperation(Visit(internalOperation.MinimumValue), Visit(internalOperation.MaximumValue), internalOperation.Label, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, object? argument) { var internalOperation = (RelationalCaseClauseOperation)operation; return new RelationalCaseClauseOperation(Visit(internalOperation.Value), internalOperation.Relation, internalOperation.Label, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, object? argument) { var internalOperation = (SingleValueCaseClauseOperation)operation; return new SingleValueCaseClauseOperation(Visit(internalOperation.Value), internalOperation.Label, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, object? argument) { var internalOperation = (InterpolatedStringTextOperation)operation; return new InterpolatedStringTextOperation(Visit(internalOperation.Text), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitInterpolation(IInterpolationOperation operation, object? argument) { var internalOperation = (InterpolationOperation)operation; return new InterpolationOperation(Visit(internalOperation.Expression), Visit(internalOperation.Alignment), Visit(internalOperation.FormatString), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitConstantPattern(IConstantPatternOperation operation, object? argument) { var internalOperation = (ConstantPatternOperation)operation; return new ConstantPatternOperation(Visit(internalOperation.Value), internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitDeclarationPattern(IDeclarationPatternOperation operation, object? argument) { var internalOperation = (DeclarationPatternOperation)operation; return new DeclarationPatternOperation(internalOperation.MatchedType, internalOperation.MatchesNull, internalOperation.DeclaredSymbol, internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitTupleBinaryOperator(ITupleBinaryOperation operation, object? argument) { var internalOperation = (TupleBinaryOperation)operation; return new TupleBinaryOperation(internalOperation.OperatorKind, Visit(internalOperation.LeftOperand), Visit(internalOperation.RightOperand), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitMethodBodyOperation(IMethodBodyOperation operation, object? argument) { var internalOperation = (MethodBodyOperation)operation; return new MethodBodyOperation(Visit(internalOperation.BlockBody), Visit(internalOperation.ExpressionBody), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitConstructorBodyOperation(IConstructorBodyOperation operation, object? argument) { var internalOperation = (ConstructorBodyOperation)operation; return new ConstructorBodyOperation(internalOperation.Locals, Visit(internalOperation.Initializer), Visit(internalOperation.BlockBody), Visit(internalOperation.ExpressionBody), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitDiscardOperation(IDiscardOperation operation, object? argument) { var internalOperation = (DiscardOperation)operation; return new DiscardOperation(internalOperation.DiscardSymbol, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, object? argument) { var internalOperation = (FlowCaptureReferenceOperation)operation; return new FlowCaptureReferenceOperation(internalOperation.Id, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, object? argument) { var internalOperation = (CoalesceAssignmentOperation)operation; return new CoalesceAssignmentOperation(Visit(internalOperation.Target), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitRangeOperation(IRangeOperation operation, object? argument) { var internalOperation = (RangeOperation)operation; return new RangeOperation(Visit(internalOperation.LeftOperand), Visit(internalOperation.RightOperand), internalOperation.IsLifted, internalOperation.Method, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitReDim(IReDimOperation operation, object? argument) { var internalOperation = (ReDimOperation)operation; return new ReDimOperation(VisitArray(internalOperation.Clauses), internalOperation.Preserve, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitReDimClause(IReDimClauseOperation operation, object? argument) { var internalOperation = (ReDimClauseOperation)operation; return new ReDimClauseOperation(Visit(internalOperation.Operand), VisitArray(internalOperation.DimensionSizes), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRecursivePattern(IRecursivePatternOperation operation, object? argument) { var internalOperation = (RecursivePatternOperation)operation; return new RecursivePatternOperation(internalOperation.MatchedType, internalOperation.DeconstructSymbol, VisitArray(internalOperation.DeconstructionSubpatterns), VisitArray(internalOperation.PropertySubpatterns), internalOperation.DeclaredSymbol, internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitDiscardPattern(IDiscardPatternOperation operation, object? argument) { var internalOperation = (DiscardPatternOperation)operation; return new DiscardPatternOperation(internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitSwitchExpression(ISwitchExpressionOperation operation, object? argument) { var internalOperation = (SwitchExpressionOperation)operation; return new SwitchExpressionOperation(Visit(internalOperation.Value), VisitArray(internalOperation.Arms), internalOperation.IsExhaustive, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation, object? argument) { var internalOperation = (SwitchExpressionArmOperation)operation; return new SwitchExpressionArmOperation(Visit(internalOperation.Pattern), Visit(internalOperation.Guard), Visit(internalOperation.Value), internalOperation.Locals, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitPropertySubpattern(IPropertySubpatternOperation operation, object? argument) { var internalOperation = (PropertySubpatternOperation)operation; return new PropertySubpatternOperation(Visit(internalOperation.Member), Visit(internalOperation.Pattern), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } internal override IOperation VisitAggregateQuery(IAggregateQueryOperation operation, object? argument) { var internalOperation = (AggregateQueryOperation)operation; return new AggregateQueryOperation(Visit(internalOperation.Group), Visit(internalOperation.Aggregation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } internal override IOperation VisitFixed(IFixedOperation operation, object? argument) { var internalOperation = (FixedOperation)operation; return new FixedOperation(internalOperation.Locals, Visit(internalOperation.Variables), Visit(internalOperation.Body), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } internal override IOperation VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, object? argument) { var internalOperation = (NoPiaObjectCreationOperation)operation; return new NoPiaObjectCreationOperation(Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } internal override IOperation VisitPlaceholder(IPlaceholderOperation operation, object? argument) { var internalOperation = (PlaceholderOperation)operation; return new PlaceholderOperation(internalOperation.PlaceholderKind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } internal override IOperation VisitWithStatement(IWithStatementOperation operation, object? argument) { var internalOperation = (WithStatementOperation)operation; return new WithStatementOperation(Visit(internalOperation.Body), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitUsingDeclaration(IUsingDeclarationOperation operation, object? argument) { var internalOperation = (UsingDeclarationOperation)operation; return new UsingDeclarationOperation(Visit(internalOperation.DeclarationGroup), internalOperation.IsAsynchronous, internalOperation.DisposeInfo, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitNegatedPattern(INegatedPatternOperation operation, object? argument) { var internalOperation = (NegatedPatternOperation)operation; return new NegatedPatternOperation(Visit(internalOperation.Pattern), internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitBinaryPattern(IBinaryPatternOperation operation, object? argument) { var internalOperation = (BinaryPatternOperation)operation; return new BinaryPatternOperation(internalOperation.OperatorKind, Visit(internalOperation.LeftPattern), Visit(internalOperation.RightPattern), internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitTypePattern(ITypePatternOperation operation, object? argument) { var internalOperation = (TypePatternOperation)operation; return new TypePatternOperation(internalOperation.MatchedType, internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRelationalPattern(IRelationalPatternOperation operation, object? argument) { var internalOperation = (RelationalPatternOperation)operation; return new RelationalPatternOperation(internalOperation.OperatorKind, Visit(internalOperation.Value), internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitWith(IWithOperation operation, object? argument) { var internalOperation = (WithOperation)operation; return new WithOperation(Visit(internalOperation.Operand), internalOperation.CloneMethod, Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } } #endregion #region Visitors public abstract partial class OperationVisitor { public virtual void Visit(IOperation? operation) => operation?.Accept(this); public virtual void DefaultVisit(IOperation operation) { /* no-op */ } internal virtual void VisitNoneOperation(IOperation operation) { /* no-op */ } public virtual void VisitInvalid(IInvalidOperation operation) => DefaultVisit(operation); public virtual void VisitBlock(IBlockOperation operation) => DefaultVisit(operation); public virtual void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) => DefaultVisit(operation); public virtual void VisitSwitch(ISwitchOperation operation) => DefaultVisit(operation); public virtual void VisitForEachLoop(IForEachLoopOperation operation) => DefaultVisit(operation); public virtual void VisitForLoop(IForLoopOperation operation) => DefaultVisit(operation); public virtual void VisitForToLoop(IForToLoopOperation operation) => DefaultVisit(operation); public virtual void VisitWhileLoop(IWhileLoopOperation operation) => DefaultVisit(operation); public virtual void VisitLabeled(ILabeledOperation operation) => DefaultVisit(operation); public virtual void VisitBranch(IBranchOperation operation) => DefaultVisit(operation); public virtual void VisitEmpty(IEmptyOperation operation) => DefaultVisit(operation); public virtual void VisitReturn(IReturnOperation operation) => DefaultVisit(operation); public virtual void VisitLock(ILockOperation operation) => DefaultVisit(operation); public virtual void VisitTry(ITryOperation operation) => DefaultVisit(operation); public virtual void VisitUsing(IUsingOperation operation) => DefaultVisit(operation); public virtual void VisitExpressionStatement(IExpressionStatementOperation operation) => DefaultVisit(operation); public virtual void VisitLocalFunction(ILocalFunctionOperation operation) => DefaultVisit(operation); public virtual void VisitStop(IStopOperation operation) => DefaultVisit(operation); public virtual void VisitEnd(IEndOperation operation) => DefaultVisit(operation); public virtual void VisitRaiseEvent(IRaiseEventOperation operation) => DefaultVisit(operation); public virtual void VisitLiteral(ILiteralOperation operation) => DefaultVisit(operation); public virtual void VisitConversion(IConversionOperation operation) => DefaultVisit(operation); public virtual void VisitInvocation(IInvocationOperation operation) => DefaultVisit(operation); public virtual void VisitArrayElementReference(IArrayElementReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitLocalReference(ILocalReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitParameterReference(IParameterReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitFieldReference(IFieldReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitMethodReference(IMethodReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitPropertyReference(IPropertyReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitEventReference(IEventReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitUnaryOperator(IUnaryOperation operation) => DefaultVisit(operation); public virtual void VisitBinaryOperator(IBinaryOperation operation) => DefaultVisit(operation); public virtual void VisitConditional(IConditionalOperation operation) => DefaultVisit(operation); public virtual void VisitCoalesce(ICoalesceOperation operation) => DefaultVisit(operation); public virtual void VisitAnonymousFunction(IAnonymousFunctionOperation operation) => DefaultVisit(operation); public virtual void VisitObjectCreation(IObjectCreationOperation operation) => DefaultVisit(operation); public virtual void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) => DefaultVisit(operation); public virtual void VisitArrayCreation(IArrayCreationOperation operation) => DefaultVisit(operation); public virtual void VisitInstanceReference(IInstanceReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitIsType(IIsTypeOperation operation) => DefaultVisit(operation); public virtual void VisitAwait(IAwaitOperation operation) => DefaultVisit(operation); public virtual void VisitSimpleAssignment(ISimpleAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitCompoundAssignment(ICompoundAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitParenthesized(IParenthesizedOperation operation) => DefaultVisit(operation); public virtual void VisitEventAssignment(IEventAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitConditionalAccess(IConditionalAccessOperation operation) => DefaultVisit(operation); public virtual void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolatedString(IInterpolatedStringOperation operation) => DefaultVisit(operation); public virtual void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) => DefaultVisit(operation); public virtual void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitMemberInitializer(IMemberInitializerOperation operation) => DefaultVisit(operation); [Obsolete("ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation), error: true)] public virtual void VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitNameOf(INameOfOperation operation) => DefaultVisit(operation); public virtual void VisitTuple(ITupleOperation operation) => DefaultVisit(operation); public virtual void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) => DefaultVisit(operation); public virtual void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitDynamicInvocation(IDynamicInvocationOperation operation) => DefaultVisit(operation); public virtual void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) => DefaultVisit(operation); public virtual void VisitTranslatedQuery(ITranslatedQueryOperation operation) => DefaultVisit(operation); public virtual void VisitDelegateCreation(IDelegateCreationOperation operation) => DefaultVisit(operation); public virtual void VisitDefaultValue(IDefaultValueOperation operation) => DefaultVisit(operation); public virtual void VisitTypeOf(ITypeOfOperation operation) => DefaultVisit(operation); public virtual void VisitSizeOf(ISizeOfOperation operation) => DefaultVisit(operation); public virtual void VisitAddressOf(IAddressOfOperation operation) => DefaultVisit(operation); public virtual void VisitIsPattern(IIsPatternOperation operation) => DefaultVisit(operation); public virtual void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) => DefaultVisit(operation); public virtual void VisitThrow(IThrowOperation operation) => DefaultVisit(operation); public virtual void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitDeclarationExpression(IDeclarationExpressionOperation operation) => DefaultVisit(operation); public virtual void VisitOmittedArgument(IOmittedArgumentOperation operation) => DefaultVisit(operation); public virtual void VisitFieldInitializer(IFieldInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitVariableInitializer(IVariableInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitPropertyInitializer(IPropertyInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitParameterInitializer(IParameterInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitArrayInitializer(IArrayInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitVariableDeclarator(IVariableDeclaratorOperation operation) => DefaultVisit(operation); public virtual void VisitVariableDeclaration(IVariableDeclarationOperation operation) => DefaultVisit(operation); public virtual void VisitArgument(IArgumentOperation operation) => DefaultVisit(operation); public virtual void VisitCatchClause(ICatchClauseOperation operation) => DefaultVisit(operation); public virtual void VisitSwitchCase(ISwitchCaseOperation operation) => DefaultVisit(operation); public virtual void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitPatternCaseClause(IPatternCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitRangeCaseClause(IRangeCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolation(IInterpolationOperation operation) => DefaultVisit(operation); public virtual void VisitConstantPattern(IConstantPatternOperation operation) => DefaultVisit(operation); public virtual void VisitDeclarationPattern(IDeclarationPatternOperation operation) => DefaultVisit(operation); public virtual void VisitTupleBinaryOperator(ITupleBinaryOperation operation) => DefaultVisit(operation); public virtual void VisitMethodBodyOperation(IMethodBodyOperation operation) => DefaultVisit(operation); public virtual void VisitConstructorBodyOperation(IConstructorBodyOperation operation) => DefaultVisit(operation); public virtual void VisitDiscardOperation(IDiscardOperation operation) => DefaultVisit(operation); public virtual void VisitFlowCapture(IFlowCaptureOperation operation) => DefaultVisit(operation); public virtual void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitIsNull(IIsNullOperation operation) => DefaultVisit(operation); public virtual void VisitCaughtException(ICaughtExceptionOperation operation) => DefaultVisit(operation); public virtual void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) => DefaultVisit(operation); public virtual void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) => DefaultVisit(operation); public virtual void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitRangeOperation(IRangeOperation operation) => DefaultVisit(operation); public virtual void VisitReDim(IReDimOperation operation) => DefaultVisit(operation); public virtual void VisitReDimClause(IReDimClauseOperation operation) => DefaultVisit(operation); public virtual void VisitRecursivePattern(IRecursivePatternOperation operation) => DefaultVisit(operation); public virtual void VisitDiscardPattern(IDiscardPatternOperation operation) => DefaultVisit(operation); public virtual void VisitSwitchExpression(ISwitchExpressionOperation operation) => DefaultVisit(operation); public virtual void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) => DefaultVisit(operation); public virtual void VisitPropertySubpattern(IPropertySubpatternOperation operation) => DefaultVisit(operation); internal virtual void VisitAggregateQuery(IAggregateQueryOperation operation) => DefaultVisit(operation); internal virtual void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) => DefaultVisit(operation); internal virtual void VisitPlaceholder(IPlaceholderOperation operation) => DefaultVisit(operation); internal virtual void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) => DefaultVisit(operation); internal virtual void VisitWithStatement(IWithStatementOperation operation) => DefaultVisit(operation); public virtual void VisitUsingDeclaration(IUsingDeclarationOperation operation) => DefaultVisit(operation); public virtual void VisitNegatedPattern(INegatedPatternOperation operation) => DefaultVisit(operation); public virtual void VisitBinaryPattern(IBinaryPatternOperation operation) => DefaultVisit(operation); public virtual void VisitTypePattern(ITypePatternOperation operation) => DefaultVisit(operation); public virtual void VisitRelationalPattern(IRelationalPatternOperation operation) => DefaultVisit(operation); public virtual void VisitWith(IWithOperation operation) => DefaultVisit(operation); } public abstract partial class OperationVisitor<TArgument, TResult> { public virtual TResult? Visit(IOperation? operation, TArgument argument) => operation is null ? default(TResult) : operation.Accept(this, argument); public virtual TResult? DefaultVisit(IOperation operation, TArgument argument) => default(TResult); internal virtual TResult? VisitNoneOperation(IOperation operation, TArgument argument) => default(TResult); public virtual TResult? VisitInvalid(IInvalidOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitBlock(IBlockOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSwitch(ISwitchOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitForEachLoop(IForEachLoopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitForLoop(IForLoopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitForToLoop(IForToLoopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitWhileLoop(IWhileLoopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLabeled(ILabeledOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitBranch(IBranchOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitEmpty(IEmptyOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitReturn(IReturnOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLock(ILockOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTry(ITryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitUsing(IUsingOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitExpressionStatement(IExpressionStatementOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLocalFunction(ILocalFunctionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitStop(IStopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitEnd(IEndOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRaiseEvent(IRaiseEventOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLiteral(ILiteralOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConversion(IConversionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInvocation(IInvocationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitArrayElementReference(IArrayElementReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLocalReference(ILocalReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitParameterReference(IParameterReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFieldReference(IFieldReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitMethodReference(IMethodReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitPropertyReference(IPropertyReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitEventReference(IEventReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitUnaryOperator(IUnaryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitBinaryOperator(IBinaryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConditional(IConditionalOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCoalesce(ICoalesceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitAnonymousFunction(IAnonymousFunctionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitObjectCreation(IObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitArrayCreation(IArrayCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInstanceReference(IInstanceReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitIsType(IIsTypeOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitAwait(IAwaitOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSimpleAssignment(ISimpleAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCompoundAssignment(ICompoundAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitParenthesized(IParenthesizedOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitEventAssignment(IEventAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConditionalAccess(IConditionalAccessOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolatedString(IInterpolatedStringOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitMemberInitializer(IMemberInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); [Obsolete("ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation), error: true)] public virtual TResult? VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitNameOf(INameOfOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTuple(ITupleOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDynamicInvocation(IDynamicInvocationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTranslatedQuery(ITranslatedQueryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDelegateCreation(IDelegateCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDefaultValue(IDefaultValueOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTypeOf(ITypeOfOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSizeOf(ISizeOfOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitAddressOf(IAddressOfOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitIsPattern(IIsPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitThrow(IThrowOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDeclarationExpression(IDeclarationExpressionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitOmittedArgument(IOmittedArgumentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFieldInitializer(IFieldInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitVariableInitializer(IVariableInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitPropertyInitializer(IPropertyInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitParameterInitializer(IParameterInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitArrayInitializer(IArrayInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitVariableDeclarator(IVariableDeclaratorOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitVariableDeclaration(IVariableDeclarationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitArgument(IArgumentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCatchClause(ICatchClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSwitchCase(ISwitchCaseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitPatternCaseClause(IPatternCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRangeCaseClause(IRangeCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolation(IInterpolationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConstantPattern(IConstantPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDeclarationPattern(IDeclarationPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTupleBinaryOperator(ITupleBinaryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitMethodBodyOperation(IMethodBodyOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConstructorBodyOperation(IConstructorBodyOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDiscardOperation(IDiscardOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFlowCapture(IFlowCaptureOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitIsNull(IIsNullOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCaughtException(ICaughtExceptionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRangeOperation(IRangeOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitReDim(IReDimOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitReDimClause(IReDimClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRecursivePattern(IRecursivePatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDiscardPattern(IDiscardPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSwitchExpression(ISwitchExpressionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitPropertySubpattern(IPropertySubpatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitAggregateQuery(IAggregateQueryOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitPlaceholder(IPlaceholderOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitWithStatement(IWithStatementOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitUsingDeclaration(IUsingDeclarationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitNegatedPattern(INegatedPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitBinaryPattern(IBinaryPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTypePattern(ITypePatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRelationalPattern(IRelationalPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitWith(IWithOperation operation, TArgument argument) => DefaultVisit(operation, argument); } #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. // < auto-generated /> #nullable enable using System; using System.Collections.Generic; using System.Threading; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { #region Interfaces /// <summary> /// Represents an invalid operation with one or more child operations. /// <para> /// Current usage: /// (1) C# invalid expression or invalid statement. /// (2) VB invalid expression or invalid statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Invalid"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInvalidOperation : IOperation { } /// <summary> /// Represents a block containing a sequence of operations and local declarations. /// <para> /// Current usage: /// (1) C# "{ ... }" block statement. /// (2) VB implicit block statement for method bodies and other block scoped statements. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Block"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IBlockOperation : IOperation { /// <summary> /// Operations contained within the block. /// </summary> ImmutableArray<IOperation> Operations { get; } /// <summary> /// Local declarations contained within the block. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } } /// <summary> /// Represents a variable declaration statement. /// </summary> /// <para> /// Current Usage: /// (1) C# local declaration statement /// (2) C# fixed statement /// (3) C# using statement /// (4) C# using declaration /// (5) VB Dim statement /// (6) VB Using statement /// </para> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.VariableDeclarationGroup"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IVariableDeclarationGroupOperation : IOperation { /// <summary> /// Variable declaration in the statement. /// </summary> /// <remarks> /// In C#, this will always be a single declaration, with all variables in <see cref="IVariableDeclarationOperation.Declarators" />. /// </remarks> ImmutableArray<IVariableDeclarationOperation> Declarations { get; } } /// <summary> /// Represents a switch operation with a value to be switched upon and switch cases. /// <para> /// Current usage: /// (1) C# switch statement. /// (2) VB Select Case statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Switch"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISwitchOperation : IOperation { /// <summary> /// Locals declared within the switch operation with scope spanning across all <see cref="Cases" />. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Value to be switched upon. /// </summary> IOperation Value { get; } /// <summary> /// Cases of the switch. /// </summary> ImmutableArray<ISwitchCaseOperation> Cases { get; } /// <summary> /// Exit label for the switch statement. /// </summary> ILabelSymbol ExitLabel { get; } } /// <summary> /// Represents a loop operation. /// <para> /// Current usage: /// (1) C# 'while', 'for', 'foreach' and 'do' loop statements /// (2) VB 'While', 'ForTo', 'ForEach', 'Do While' and 'Do Until' loop statements /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILoopOperation : IOperation { /// <summary> /// Kind of the loop. /// </summary> LoopKind LoopKind { get; } /// <summary> /// Body of the loop. /// </summary> IOperation Body { get; } /// <summary> /// Declared locals. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Loop continue label. /// </summary> ILabelSymbol ContinueLabel { get; } /// <summary> /// Loop exit/break label. /// </summary> ILabelSymbol ExitLabel { get; } } /// <summary> /// Represents a for each loop. /// <para> /// Current usage: /// (1) C# 'foreach' loop statement /// (2) VB 'For Each' loop statement /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IForEachLoopOperation : ILoopOperation { /// <summary> /// Refers to the operation for declaring a new local variable or reference an existing variable or an expression. /// </summary> IOperation LoopControlVariable { get; } /// <summary> /// Collection value over which the loop iterates. /// </summary> IOperation Collection { get; } /// <summary> /// Optional list of comma separated next variables at loop bottom in VB. /// This list is always empty for C#. /// </summary> ImmutableArray<IOperation> NextVariables { get; } /// <summary> /// Whether this for each loop is asynchronous. /// Always false for VB. /// </summary> bool IsAsynchronous { get; } } /// <summary> /// Represents a for loop. /// <para> /// Current usage: /// (1) C# 'for' loop statement /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IForLoopOperation : ILoopOperation { /// <summary> /// List of operations to execute before entry to the loop. For C#, this comes from the first clause of the for statement. /// </summary> ImmutableArray<IOperation> Before { get; } /// <summary> /// Locals declared within the loop Condition and are in scope throughout the <see cref="Condition" />, /// <see cref="ILoopOperation.Body" /> and <see cref="AtLoopBottom" />. /// They are considered to be declared per iteration. /// </summary> ImmutableArray<ILocalSymbol> ConditionLocals { get; } /// <summary> /// Condition of the loop. For C#, this comes from the second clause of the for statement. /// </summary> IOperation? Condition { get; } /// <summary> /// List of operations to execute at the bottom of the loop. For C#, this comes from the third clause of the for statement. /// </summary> ImmutableArray<IOperation> AtLoopBottom { get; } } /// <summary> /// Represents a for to loop with loop control variable and initial, limit and step values for the control variable. /// <para> /// Current usage: /// (1) VB 'For ... To ... Step' loop statement /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IForToLoopOperation : ILoopOperation { /// <summary> /// Refers to the operation for declaring a new local variable or reference an existing variable or an expression. /// </summary> IOperation LoopControlVariable { get; } /// <summary> /// Operation for setting the initial value of the loop control variable. This comes from the expression between the 'For' and 'To' keywords. /// </summary> IOperation InitialValue { get; } /// <summary> /// Operation for the limit value of the loop control variable. This comes from the expression after the 'To' keyword. /// </summary> IOperation LimitValue { get; } /// <summary> /// Operation for the step value of the loop control variable. This comes from the expression after the 'Step' keyword, /// or inferred by the compiler if 'Step' clause is omitted. /// </summary> IOperation StepValue { get; } /// <summary> /// <code>true</code> if arithmetic operations behind this loop are 'checked'. /// </summary> bool IsChecked { get; } /// <summary> /// Optional list of comma separated next variables at loop bottom. /// </summary> ImmutableArray<IOperation> NextVariables { get; } } /// <summary> /// Represents a while or do while loop. /// <para> /// Current usage: /// (1) C# 'while' and 'do while' loop statements. /// (2) VB 'While', 'Do While' and 'Do Until' loop statements. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IWhileLoopOperation : ILoopOperation { /// <summary> /// Condition of the loop. This can only be null in error scenarios. /// </summary> IOperation? Condition { get; } /// <summary> /// True if the <see cref="Condition" /> is evaluated at start of each loop iteration. /// False if it is evaluated at the end of each loop iteration. /// </summary> bool ConditionIsTop { get; } /// <summary> /// True if the loop has 'Until' loop semantics and the loop is executed while <see cref="Condition" /> is false. /// </summary> bool ConditionIsUntil { get; } /// <summary> /// Additional conditional supplied for loop in error cases, which is ignored by the compiler. /// For example, for VB 'Do While' or 'Do Until' loop with syntax errors where both the top and bottom conditions are provided. /// The top condition is preferred and exposed as <see cref="Condition" /> and the bottom condition is ignored and exposed by this property. /// This property should be null for all non-error cases. /// </summary> IOperation? IgnoredCondition { get; } } /// <summary> /// Represents an operation with a label. /// <para> /// Current usage: /// (1) C# labeled statement. /// (2) VB label statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Labeled"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILabeledOperation : IOperation { /// <summary> /// Label that can be the target of branches. /// </summary> ILabelSymbol Label { get; } /// <summary> /// Operation that has been labeled. In VB, this is always null. /// </summary> IOperation? Operation { get; } } /// <summary> /// Represents a branch operation. /// <para> /// Current usage: /// (1) C# goto, break, or continue statement. /// (2) VB GoTo, Exit ***, or Continue *** statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Branch"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IBranchOperation : IOperation { /// <summary> /// Label that is the target of the branch. /// </summary> ILabelSymbol Target { get; } /// <summary> /// Kind of the branch. /// </summary> BranchKind BranchKind { get; } } /// <summary> /// Represents an empty or no-op operation. /// <para> /// Current usage: /// (1) C# empty statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Empty"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IEmptyOperation : IOperation { } /// <summary> /// Represents a return from the method with an optional return value. /// <para> /// Current usage: /// (1) C# return statement and yield statement. /// (2) VB Return statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Return"/></description></item> /// <item><description><see cref="OperationKind.YieldBreak"/></description></item> /// <item><description><see cref="OperationKind.YieldReturn"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IReturnOperation : IOperation { /// <summary> /// Value to be returned. /// </summary> IOperation? ReturnedValue { get; } } /// <summary> /// Represents a <see cref="Body" /> of operations that are executed while holding a lock onto the <see cref="LockedValue" />. /// <para> /// Current usage: /// (1) C# lock statement. /// (2) VB SyncLock statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Lock"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILockOperation : IOperation { /// <summary> /// Operation producing a value to be locked. /// </summary> IOperation LockedValue { get; } /// <summary> /// Body of the lock, to be executed while holding the lock. /// </summary> IOperation Body { get; } } /// <summary> /// Represents a try operation for exception handling code with a body, catch clauses and a finally handler. /// <para> /// Current usage: /// (1) C# try statement. /// (2) VB Try statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Try"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITryOperation : IOperation { /// <summary> /// Body of the try, over which the handlers are active. /// </summary> IBlockOperation Body { get; } /// <summary> /// Catch clauses of the try. /// </summary> ImmutableArray<ICatchClauseOperation> Catches { get; } /// <summary> /// Finally handler of the try. /// </summary> IBlockOperation? Finally { get; } /// <summary> /// Exit label for the try. This will always be null for C#. /// </summary> ILabelSymbol? ExitLabel { get; } } /// <summary> /// Represents a <see cref="Body" /> of operations that are executed while using disposable <see cref="Resources" />. /// <para> /// Current usage: /// (1) C# using statement. /// (2) VB Using statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Using"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IUsingOperation : IOperation { /// <summary> /// Declaration introduced or resource held by the using. /// </summary> IOperation Resources { get; } /// <summary> /// Body of the using, over which the resources of the using are maintained. /// </summary> IOperation Body { get; } /// <summary> /// Locals declared within the <see cref="Resources" /> with scope spanning across this entire <see cref="IUsingOperation" />. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Whether this using is asynchronous. /// Always false for VB. /// </summary> bool IsAsynchronous { get; } } /// <summary> /// Represents an operation that drops the resulting value and the type of the underlying wrapped <see cref="Operation" />. /// <para> /// Current usage: /// (1) C# expression statement. /// (2) VB expression statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ExpressionStatement"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IExpressionStatementOperation : IOperation { /// <summary> /// Underlying operation with a value and type. /// </summary> IOperation Operation { get; } } /// <summary> /// Represents a local function defined within a method. /// <para> /// Current usage: /// (1) C# local function statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.LocalFunction"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILocalFunctionOperation : IOperation { /// <summary> /// Local function symbol. /// </summary> IMethodSymbol Symbol { get; } /// <summary> /// Body of the local function. /// </summary> /// <remarks> /// This can be null in error scenarios, or when the method is an extern method. /// </remarks> IBlockOperation? Body { get; } /// <summary> /// An extra body for the local function, if both a block body and expression body are specified in source. /// </summary> /// <remarks> /// This is only ever non-null in error situations. /// </remarks> IBlockOperation? IgnoredBody { get; } } /// <summary> /// Represents an operation to stop or suspend execution of code. /// <para> /// Current usage: /// (1) VB Stop statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Stop"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IStopOperation : IOperation { } /// <summary> /// Represents an operation that stops the execution of code abruptly. /// <para> /// Current usage: /// (1) VB End Statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.End"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IEndOperation : IOperation { } /// <summary> /// Represents an operation for raising an event. /// <para> /// Current usage: /// (1) VB raise event statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.RaiseEvent"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRaiseEventOperation : IOperation { /// <summary> /// Reference to the event to be raised. /// </summary> IEventReferenceOperation EventReference { get; } /// <summary> /// Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order. /// </summary> /// <remarks> /// If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. /// Default values are supplied for optional arguments missing in source. /// </remarks> ImmutableArray<IArgumentOperation> Arguments { get; } } /// <summary> /// Represents a textual literal numeric, string, etc. /// <para> /// Current usage: /// (1) C# literal expression. /// (2) VB literal expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Literal"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILiteralOperation : IOperation { } /// <summary> /// Represents a type conversion. /// <para> /// Current usage: /// (1) C# conversion expression. /// (2) VB conversion expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Conversion"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConversionOperation : IOperation { /// <summary> /// Value to be converted. /// </summary> IOperation Operand { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } /// <summary> /// Gets the underlying common conversion information. /// </summary> /// <remarks> /// If you need conversion information that is language specific, use either /// <see cref="T:Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetConversion(IConversionOperation)" /> or /// <see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.GetConversion(IConversionOperation)" />. /// </remarks> CommonConversion Conversion { get; } /// <summary> /// False if the conversion will fail with a <see cref="InvalidCastException" /> at runtime if the cast fails. This is true for C#'s /// <c>as</c> operator and for VB's <c>TryCast</c> operator. /// </summary> bool IsTryCast { get; } /// <summary> /// True if the conversion can fail at runtime with an overflow exception. This corresponds to C# checked and unchecked blocks. /// </summary> bool IsChecked { get; } } /// <summary> /// Represents an invocation of a method. /// <para> /// Current usage: /// (1) C# method invocation expression. /// (2) C# collection element initializer. /// For example, in the following collection initializer: <code>new C() { 1, 2, 3 }</code>, we will have /// 3 <see cref="IInvocationOperation" /> nodes, each of which will be a call to the corresponding Add method /// with either 1, 2, 3 as the argument. /// (3) VB method invocation expression. /// (4) VB collection element initializer. /// Similar to the C# example, <code>New C() From {1, 2, 3}</code> will have 3 <see cref="IInvocationOperation" /> /// nodes with 1, 2, and 3 as their arguments, respectively. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Invocation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInvocationOperation : IOperation { /// <summary> /// Method to be invoked. /// </summary> IMethodSymbol TargetMethod { get; } /// <summary> /// 'This' or 'Me' instance to be supplied to the method, or null if the method is static. /// </summary> IOperation? Instance { get; } /// <summary> /// True if the invocation uses a virtual mechanism, and false otherwise. /// </summary> bool IsVirtual { get; } /// <summary> /// Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order. /// </summary> /// <remarks> /// If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. /// Default values are supplied for optional arguments missing in source. /// </remarks> ImmutableArray<IArgumentOperation> Arguments { get; } } /// <summary> /// Represents a reference to an array element. /// <para> /// Current usage: /// (1) C# array element reference expression. /// (2) VB array element reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ArrayElementReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IArrayElementReferenceOperation : IOperation { /// <summary> /// Array to be indexed. /// </summary> IOperation ArrayReference { get; } /// <summary> /// Indices that specify an individual element. /// </summary> ImmutableArray<IOperation> Indices { get; } } /// <summary> /// Represents a reference to a declared local variable. /// <para> /// Current usage: /// (1) C# local reference expression. /// (2) VB local reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.LocalReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ILocalReferenceOperation : IOperation { /// <summary> /// Referenced local variable. /// </summary> ILocalSymbol Local { get; } /// <summary> /// True if this reference is also the declaration site of this variable. This is true in out variable declarations /// and in deconstruction operations where a new variable is being declared. /// </summary> bool IsDeclaration { get; } } /// <summary> /// Represents a reference to a parameter. /// <para> /// Current usage: /// (1) C# parameter reference expression. /// (2) VB parameter reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ParameterReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IParameterReferenceOperation : IOperation { /// <summary> /// Referenced parameter. /// </summary> IParameterSymbol Parameter { get; } } /// <summary> /// Represents a reference to a member of a class, struct, or interface. /// <para> /// Current usage: /// (1) C# member reference expression. /// (2) VB member reference expression. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMemberReferenceOperation : IOperation { /// <summary> /// Instance of the type. Null if the reference is to a static/shared member. /// </summary> IOperation? Instance { get; } /// <summary> /// Referenced member. /// </summary> ISymbol Member { get; } } /// <summary> /// Represents a reference to a field. /// <para> /// Current usage: /// (1) C# field reference expression. /// (2) VB field reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.FieldReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IFieldReferenceOperation : IMemberReferenceOperation { /// <summary> /// Referenced field. /// </summary> IFieldSymbol Field { get; } /// <summary> /// If the field reference is also where the field was declared. /// </summary> /// <remarks> /// This is only ever true in CSharp scripts, where a top-level statement creates a new variable /// in a reference, such as an out variable declaration or a deconstruction declaration. /// </remarks> bool IsDeclaration { get; } } /// <summary> /// Represents a reference to a method other than as the target of an invocation. /// <para> /// Current usage: /// (1) C# method reference expression. /// (2) VB method reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.MethodReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMethodReferenceOperation : IMemberReferenceOperation { /// <summary> /// Referenced method. /// </summary> IMethodSymbol Method { get; } /// <summary> /// Indicates whether the reference uses virtual semantics. /// </summary> bool IsVirtual { get; } } /// <summary> /// Represents a reference to a property. /// <para> /// Current usage: /// (1) C# property reference expression. /// (2) VB property reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.PropertyReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPropertyReferenceOperation : IMemberReferenceOperation { /// <summary> /// Referenced property. /// </summary> IPropertySymbol Property { get; } /// <summary> /// Arguments of the indexer property reference, excluding the instance argument. Arguments are in evaluation order. /// </summary> /// <remarks> /// If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. /// Default values are supplied for optional arguments missing in source. /// </remarks> ImmutableArray<IArgumentOperation> Arguments { get; } } /// <summary> /// Represents a reference to an event. /// <para> /// Current usage: /// (1) C# event reference expression. /// (2) VB event reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.EventReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IEventReferenceOperation : IMemberReferenceOperation { /// <summary> /// Referenced event. /// </summary> IEventSymbol Event { get; } } /// <summary> /// Represents an operation with one operand and a unary operator. /// <para> /// Current usage: /// (1) C# unary operation expression. /// (2) VB unary operation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Unary"/></description></item> /// <item><description><see cref="OperationKind.UnaryOperator"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IUnaryOperation : IOperation { /// <summary> /// Kind of unary operation. /// </summary> UnaryOperatorKind OperatorKind { get; } /// <summary> /// Operand. /// </summary> IOperation Operand { get; } /// <summary> /// <see langword="true" /> if this is a 'lifted' unary operator. When there is an /// operator that is defined to work on a value type, 'lifted' operators are /// created to work on the <see cref="System.Nullable{T}" /> versions of those /// value types. /// </summary> bool IsLifted { get; } /// <summary> /// <see langword="true" /> if overflow checking is performed for the arithmetic operation. /// </summary> bool IsChecked { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } } /// <summary> /// Represents an operation with two operands and a binary operator that produces a result with a non-null type. /// <para> /// Current usage: /// (1) C# binary operator expression. /// (2) VB binary operator expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Binary"/></description></item> /// <item><description><see cref="OperationKind.BinaryOperator"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IBinaryOperation : IOperation { /// <summary> /// Kind of binary operation. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// Left operand. /// </summary> IOperation LeftOperand { get; } /// <summary> /// Right operand. /// </summary> IOperation RightOperand { get; } /// <summary> /// <see langword="true" /> if this is a 'lifted' binary operator. When there is an /// operator that is defined to work on a value type, 'lifted' operators are /// created to work on the <see cref="System.Nullable{T}" /> versions of those /// value types. /// </summary> bool IsLifted { get; } /// <summary> /// <see langword="true" /> if this is a 'checked' binary operator. /// </summary> bool IsChecked { get; } /// <summary> /// <see langword="true" /> if the comparison is text based for string or object comparison in VB. /// </summary> bool IsCompareText { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } } /// <summary> /// Represents a conditional operation with: /// (1) <see cref="Condition" /> to be tested, /// (2) <see cref="WhenTrue" /> operation to be executed when <see cref="Condition" /> is true and /// (3) <see cref="WhenFalse" /> operation to be executed when the <see cref="Condition" /> is false. /// <para> /// Current usage: /// (1) C# ternary expression "a ? b : c" and if statement. /// (2) VB ternary expression "If(a, b, c)" and If Else statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Conditional"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConditionalOperation : IOperation { /// <summary> /// Condition to be tested. /// </summary> IOperation Condition { get; } /// <summary> /// Operation to be executed if the <see cref="Condition" /> is true. /// </summary> IOperation WhenTrue { get; } /// <summary> /// Operation to be executed if the <see cref="Condition" /> is false. /// </summary> IOperation? WhenFalse { get; } /// <summary> /// Is result a managed reference /// </summary> bool IsRef { get; } } /// <summary> /// Represents a coalesce operation with two operands: /// (1) <see cref="Value" />, which is the first operand that is unconditionally evaluated and is the result of the operation if non null. /// (2) <see cref="WhenNull" />, which is the second operand that is conditionally evaluated and is the result of the operation if <see cref="Value" /> is null. /// <para> /// Current usage: /// (1) C# null-coalescing expression "Value ?? WhenNull". /// (2) VB binary conditional expression "If(Value, WhenNull)". /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Coalesce"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICoalesceOperation : IOperation { /// <summary> /// Operation to be unconditionally evaluated. /// </summary> IOperation Value { get; } /// <summary> /// Operation to be conditionally evaluated if <see cref="Value" /> evaluates to null/Nothing. /// </summary> IOperation WhenNull { get; } /// <summary> /// Conversion associated with <see cref="Value" /> when it is not null/Nothing. /// Identity if result type of the operation is the same as type of <see cref="Value" />. /// Otherwise, if type of <see cref="Value" /> is nullable, then conversion is applied to an /// unwrapped <see cref="Value" />, otherwise to the <see cref="Value" /> itself. /// </summary> CommonConversion ValueConversion { get; } } /// <summary> /// Represents an anonymous function operation. /// <para> /// Current usage: /// (1) C# lambda expression. /// (2) VB anonymous delegate expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.AnonymousFunction"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAnonymousFunctionOperation : IOperation { /// <summary> /// Symbol of the anonymous function. /// </summary> IMethodSymbol Symbol { get; } /// <summary> /// Body of the anonymous function. /// </summary> IBlockOperation Body { get; } } /// <summary> /// Represents creation of an object instance. /// <para> /// Current usage: /// (1) C# new expression. /// (2) VB New expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ObjectCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IObjectCreationOperation : IOperation { /// <summary> /// Constructor to be invoked on the created instance. /// </summary> IMethodSymbol? Constructor { get; } /// <summary> /// Object or collection initializer, if any. /// </summary> IObjectOrCollectionInitializerOperation? Initializer { get; } /// <summary> /// Arguments of the object creation, excluding the instance argument. Arguments are in evaluation order. /// </summary> /// <remarks> /// If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. /// Default values are supplied for optional arguments missing in source. /// </remarks> ImmutableArray<IArgumentOperation> Arguments { get; } } /// <summary> /// Represents a creation of a type parameter object, i.e. new T(), where T is a type parameter with new constraint. /// <para> /// Current usage: /// (1) C# type parameter object creation expression. /// (2) VB type parameter object creation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TypeParameterObjectCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITypeParameterObjectCreationOperation : IOperation { /// <summary> /// Object or collection initializer, if any. /// </summary> IObjectOrCollectionInitializerOperation? Initializer { get; } } /// <summary> /// Represents the creation of an array instance. /// <para> /// Current usage: /// (1) C# array creation expression. /// (2) VB array creation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ArrayCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IArrayCreationOperation : IOperation { /// <summary> /// Sizes of the dimensions of the created array instance. /// </summary> ImmutableArray<IOperation> DimensionSizes { get; } /// <summary> /// Values of elements of the created array instance. /// </summary> IArrayInitializerOperation? Initializer { get; } } /// <summary> /// Represents an implicit/explicit reference to an instance. /// <para> /// Current usage: /// (1) C# this or base expression. /// (2) VB Me, MyClass, or MyBase expression. /// (3) C# object or collection or 'with' expression initializers. /// (4) VB With statements, object or collection initializers. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InstanceReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInstanceReferenceOperation : IOperation { /// <summary> /// The kind of reference that is being made. /// </summary> InstanceReferenceKind ReferenceKind { get; } } /// <summary> /// Represents an operation that tests if a value is of a specific type. /// <para> /// Current usage: /// (1) C# "is" operator expression. /// (2) VB "TypeOf" and "TypeOf IsNot" expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.IsType"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IIsTypeOperation : IOperation { /// <summary> /// Value to test. /// </summary> IOperation ValueOperand { get; } /// <summary> /// Type for which to test. /// </summary> ITypeSymbol TypeOperand { get; } /// <summary> /// Flag indicating if this is an "is not" type expression. /// True for VB "TypeOf ... IsNot ..." expression. /// False, otherwise. /// </summary> bool IsNegated { get; } } /// <summary> /// Represents an await operation. /// <para> /// Current usage: /// (1) C# await expression. /// (2) VB await expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Await"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAwaitOperation : IOperation { /// <summary> /// Awaited operation. /// </summary> IOperation Operation { get; } } /// <summary> /// Represents a base interface for assignments. /// <para> /// Current usage: /// (1) C# simple, compound and deconstruction assignment expressions. /// (2) VB simple and compound assignment expressions. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAssignmentOperation : IOperation { /// <summary> /// Target of the assignment. /// </summary> IOperation Target { get; } /// <summary> /// Value to be assigned to the target of the assignment. /// </summary> IOperation Value { get; } } /// <summary> /// Represents a simple assignment operation. /// <para> /// Current usage: /// (1) C# simple assignment expression. /// (2) VB simple assignment expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SimpleAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISimpleAssignmentOperation : IAssignmentOperation { /// <summary> /// Is this a ref assignment /// </summary> bool IsRef { get; } } /// <summary> /// Represents a compound assignment that mutates the target with the result of a binary operation. /// <para> /// Current usage: /// (1) C# compound assignment expression. /// (2) VB compound assignment expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.CompoundAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICompoundAssignmentOperation : IAssignmentOperation { /// <summary> /// Conversion applied to <see cref="IAssignmentOperation.Target" /> before the operation occurs. /// </summary> CommonConversion InConversion { get; } /// <summary> /// Conversion applied to the result of the binary operation, before it is assigned back to /// <see cref="IAssignmentOperation.Target" />. /// </summary> CommonConversion OutConversion { get; } /// <summary> /// Kind of binary operation. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// <see langword="true" /> if this assignment contains a 'lifted' binary operation. /// </summary> bool IsLifted { get; } /// <summary> /// <see langword="true" /> if overflow checking is performed for the arithmetic operation. /// </summary> bool IsChecked { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } } /// <summary> /// Represents a parenthesized operation. /// <para> /// Current usage: /// (1) VB parenthesized expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Parenthesized"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IParenthesizedOperation : IOperation { /// <summary> /// Operand enclosed in parentheses. /// </summary> IOperation Operand { get; } } /// <summary> /// Represents a binding of an event. /// <para> /// Current usage: /// (1) C# event assignment expression. /// (2) VB Add/Remove handler statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.EventAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IEventAssignmentOperation : IOperation { /// <summary> /// Reference to the event being bound. /// </summary> IOperation EventReference { get; } /// <summary> /// Handler supplied for the event. /// </summary> IOperation HandlerValue { get; } /// <summary> /// True for adding a binding, false for removing one. /// </summary> bool Adds { get; } } /// <summary> /// Represents a conditionally accessed operation. Note that <see cref="IConditionalAccessInstanceOperation" /> is used to refer to the value /// of <see cref="Operation" /> within <see cref="WhenNotNull" />. /// <para> /// Current usage: /// (1) C# conditional access expression (? or ?. operator). /// (2) VB conditional access expression (? or ?. operator). /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ConditionalAccess"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConditionalAccessOperation : IOperation { /// <summary> /// Operation that will be evaluated and accessed if non null. /// </summary> IOperation Operation { get; } /// <summary> /// Operation to be evaluated if <see cref="Operation" /> is non null. /// </summary> IOperation WhenNotNull { get; } } /// <summary> /// Represents the value of a conditionally-accessed operation within <see cref="IConditionalAccessOperation.WhenNotNull" />. /// For a conditional access operation of the form <c>someExpr?.Member</c>, this operation is used as the InstanceReceiver for the right operation <c>Member</c>. /// See https://github.com/dotnet/roslyn/issues/21279#issuecomment-323153041 for more details. /// <para> /// Current usage: /// (1) C# conditional access instance expression. /// (2) VB conditional access instance expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ConditionalAccessInstance"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConditionalAccessInstanceOperation : IOperation { } /// <summary> /// Represents an interpolated string. /// <para> /// Current usage: /// (1) C# interpolated string expression. /// (2) VB interpolated string expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InterpolatedString"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringOperation : IOperation { /// <summary> /// Constituent parts of interpolated string, each of which is an <see cref="IInterpolatedStringContentOperation" />. /// </summary> ImmutableArray<IInterpolatedStringContentOperation> Parts { get; } } /// <summary> /// Represents a creation of anonymous object. /// <para> /// Current usage: /// (1) C# "new { ... }" expression /// (2) VB "New With { ... }" expression /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.AnonymousObjectCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAnonymousObjectCreationOperation : IOperation { /// <summary> /// Property initializers. /// Each initializer is an <see cref="ISimpleAssignmentOperation" />, with an <see cref="IPropertyReferenceOperation" /> /// as the target whose Instance is an <see cref="IInstanceReferenceOperation" /> with <see cref="InstanceReferenceKind.ImplicitReceiver" /> kind. /// </summary> ImmutableArray<IOperation> Initializers { get; } } /// <summary> /// Represents an initialization for an object or collection creation. /// <para> /// Current usage: /// (1) C# object or collection initializer expression. /// (2) VB object or collection initializer expression. /// For example, object initializer "{ X = x }" within object creation "new Class() { X = x }" and /// collection initializer "{ x, y, 3 }" within collection creation "new MyList() { x, y, 3 }". /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ObjectOrCollectionInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IObjectOrCollectionInitializerOperation : IOperation { /// <summary> /// Object member or collection initializers. /// </summary> ImmutableArray<IOperation> Initializers { get; } } /// <summary> /// Represents an initialization of member within an object initializer with a nested object or collection initializer. /// <para> /// Current usage: /// (1) C# nested member initializer expression. /// For example, given an object creation with initializer "new Class() { X = x, Y = { x, y, 3 }, Z = { X = z } }", /// member initializers for Y and Z, i.e. "Y = { x, y, 3 }", and "Z = { X = z }" are nested member initializers represented by this operation. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.MemberInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMemberInitializerOperation : IOperation { /// <summary> /// Initialized member reference <see cref="IMemberReferenceOperation" /> or an invalid operation for error cases. /// </summary> IOperation InitializedMember { get; } /// <summary> /// Member initializer. /// </summary> IObjectOrCollectionInitializerOperation Initializer { get; } } /// <summary> /// Obsolete interface that used to represent a collection element initializer. It has been replaced by /// <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />, as appropriate. /// <para> /// Current usage: /// None. This API has been obsoleted in favor of <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.CollectionElementInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> [Obsolete("ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation), error: true)] public interface ICollectionElementInitializerOperation : IOperation { IMethodSymbol AddMethod { get; } ImmutableArray<IOperation> Arguments { get; } bool IsDynamic { get; } } /// <summary> /// Represents an operation that gets a string value for the <see cref="Argument" /> name. /// <para> /// Current usage: /// (1) C# nameof expression. /// (2) VB NameOf expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.NameOf"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface INameOfOperation : IOperation { /// <summary> /// Argument to the name of operation. /// </summary> IOperation Argument { get; } } /// <summary> /// Represents a tuple with one or more elements. /// <para> /// Current usage: /// (1) C# tuple expression. /// (2) VB tuple expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Tuple"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITupleOperation : IOperation { /// <summary> /// Tuple elements. /// </summary> ImmutableArray<IOperation> Elements { get; } /// <summary> /// Natural type of the tuple, or null if tuple doesn't have a natural type. /// Natural type can be different from <see cref="IOperation.Type" /> depending on the /// conversion context, in which the tuple is used. /// </summary> ITypeSymbol? NaturalType { get; } } /// <summary> /// Represents an object creation with a dynamically bound constructor. /// <para> /// Current usage: /// (1) C# "new" expression with dynamic argument(s). /// (2) VB late bound "New" expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DynamicObjectCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDynamicObjectCreationOperation : IOperation { /// <summary> /// Object or collection initializer, if any. /// </summary> IObjectOrCollectionInitializerOperation? Initializer { get; } /// <summary> /// Dynamically bound arguments, excluding the instance argument. /// </summary> ImmutableArray<IOperation> Arguments { get; } } /// <summary> /// Represents a reference to a member of a class, struct, or module that is dynamically bound. /// <para> /// Current usage: /// (1) C# dynamic member reference expression. /// (2) VB late bound member reference expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DynamicMemberReference"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDynamicMemberReferenceOperation : IOperation { /// <summary> /// Instance receiver, if it exists. /// </summary> IOperation? Instance { get; } /// <summary> /// Referenced member. /// </summary> string MemberName { get; } /// <summary> /// Type arguments. /// </summary> ImmutableArray<ITypeSymbol> TypeArguments { get; } /// <summary> /// The containing type of the referenced member, if different from type of the <see cref="Instance" />. /// </summary> ITypeSymbol? ContainingType { get; } } /// <summary> /// Represents a invocation that is dynamically bound. /// <para> /// Current usage: /// (1) C# dynamic invocation expression. /// (2) C# dynamic collection element initializer. /// For example, in the following collection initializer: <code>new C() { do1, do2, do3 }</code> where /// the doX objects are of type dynamic, we'll have 3 <see cref="IDynamicInvocationOperation" /> with do1, do2, and /// do3 as their arguments. /// (3) VB late bound invocation expression. /// (4) VB dynamic collection element initializer. /// Similar to the C# example, <code>New C() From {do1, do2, do3}</code> will generate 3 <see cref="IDynamicInvocationOperation" /> /// nodes with do1, do2, and do3 as their arguments, respectively. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DynamicInvocation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDynamicInvocationOperation : IOperation { /// <summary> /// Dynamically or late bound operation. /// </summary> IOperation Operation { get; } /// <summary> /// Dynamically bound arguments, excluding the instance argument. /// </summary> ImmutableArray<IOperation> Arguments { get; } } /// <summary> /// Represents an indexer access that is dynamically bound. /// <para> /// Current usage: /// (1) C# dynamic indexer access expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DynamicIndexerAccess"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDynamicIndexerAccessOperation : IOperation { /// <summary> /// Dynamically indexed operation. /// </summary> IOperation Operation { get; } /// <summary> /// Dynamically bound arguments, excluding the instance argument. /// </summary> ImmutableArray<IOperation> Arguments { get; } } /// <summary> /// Represents an unrolled/lowered query operation. /// For example, for a C# query expression "from x in set where x.Name != null select x.Name", the Operation tree has the following shape: /// ITranslatedQueryExpression /// IInvocationExpression ('Select' invocation for "select x.Name") /// IInvocationExpression ('Where' invocation for "where x.Name != null") /// IInvocationExpression ('From' invocation for "from x in set") /// <para> /// Current usage: /// (1) C# query expression. /// (2) VB query expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TranslatedQuery"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITranslatedQueryOperation : IOperation { /// <summary> /// Underlying unrolled operation. /// </summary> IOperation Operation { get; } } /// <summary> /// Represents a delegate creation. This is created whenever a new delegate is created. /// <para> /// Current usage: /// (1) C# delegate creation expression. /// (2) VB delegate creation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DelegateCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDelegateCreationOperation : IOperation { /// <summary> /// The lambda or method binding that this delegate is created from. /// </summary> IOperation Target { get; } } /// <summary> /// Represents a default value operation. /// <para> /// Current usage: /// (1) C# default value expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DefaultValue"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDefaultValueOperation : IOperation { } /// <summary> /// Represents an operation that gets <see cref="System.Type" /> for the given <see cref="TypeOperand" />. /// <para> /// Current usage: /// (1) C# typeof expression. /// (2) VB GetType expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TypeOf"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITypeOfOperation : IOperation { /// <summary> /// Type operand. /// </summary> ITypeSymbol TypeOperand { get; } } /// <summary> /// Represents an operation to compute the size of a given type. /// <para> /// Current usage: /// (1) C# sizeof expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SizeOf"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISizeOfOperation : IOperation { /// <summary> /// Type operand. /// </summary> ITypeSymbol TypeOperand { get; } } /// <summary> /// Represents an operation that creates a pointer value by taking the address of a reference. /// <para> /// Current usage: /// (1) C# address of expression /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.AddressOf"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IAddressOfOperation : IOperation { /// <summary> /// Addressed reference. /// </summary> IOperation Reference { get; } } /// <summary> /// Represents an operation that tests if a value matches a specific pattern. /// <para> /// Current usage: /// (1) C# is pattern expression. For example, "x is int i". /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.IsPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IIsPatternOperation : IOperation { /// <summary> /// Underlying operation to test. /// </summary> IOperation Value { get; } /// <summary> /// Pattern. /// </summary> IPatternOperation Pattern { get; } } /// <summary> /// Represents an <see cref="OperationKind.Increment" /> or <see cref="OperationKind.Decrement" /> operation. /// Note that this operation is different from an <see cref="IUnaryOperation" /> as it mutates the <see cref="Target" />, /// while unary operator expression does not mutate it's operand. /// <para> /// Current usage: /// (1) C# increment expression or decrement expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Increment"/></description></item> /// <item><description><see cref="OperationKind.Decrement"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IIncrementOrDecrementOperation : IOperation { /// <summary> /// <see langword="true" /> if this is a postfix expression. <see langword="false" /> if this is a prefix expression. /// </summary> bool IsPostfix { get; } /// <summary> /// <see langword="true" /> if this is a 'lifted' increment operator. When there /// is an operator that is defined to work on a value type, 'lifted' operators are /// created to work on the <see cref="System.Nullable{T}" /> versions of those /// value types. /// </summary> bool IsLifted { get; } /// <summary> /// <see langword="true" /> if overflow checking is performed for the arithmetic operation. /// </summary> bool IsChecked { get; } /// <summary> /// Target of the assignment. /// </summary> IOperation Target { get; } /// <summary> /// Operator method used by the operation, null if the operation does not use an operator method. /// </summary> IMethodSymbol? OperatorMethod { get; } } /// <summary> /// Represents an operation to throw an exception. /// <para> /// Current usage: /// (1) C# throw expression. /// (2) C# throw statement. /// (2) VB Throw statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Throw"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IThrowOperation : IOperation { /// <summary> /// Instance of an exception being thrown. /// </summary> IOperation? Exception { get; } } /// <summary> /// Represents a assignment with a deconstruction. /// <para> /// Current usage: /// (1) C# deconstruction assignment expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DeconstructionAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDeconstructionAssignmentOperation : IAssignmentOperation { } /// <summary> /// Represents a declaration expression operation. Unlike a regular variable declaration <see cref="IVariableDeclaratorOperation" /> and <see cref="IVariableDeclarationOperation" />, this operation represents an "expression" declaring a variable. /// <para> /// Current usage: /// (1) C# declaration expression. For example, /// (a) "var (x, y)" is a deconstruction declaration expression with variables x and y. /// (b) "(var x, var y)" is a tuple expression with two declaration expressions. /// (c) "M(out var x);" is an invocation expression with an out "var x" declaration expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DeclarationExpression"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDeclarationExpressionOperation : IOperation { /// <summary> /// Underlying expression. /// </summary> IOperation Expression { get; } } /// <summary> /// Represents an argument value that has been omitted in an invocation. /// <para> /// Current usage: /// (1) VB omitted argument in an invocation expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.OmittedArgument"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IOmittedArgumentOperation : IOperation { } /// <summary> /// Represents an initializer for a field, property, parameter or a local variable declaration. /// <para> /// Current usage: /// (1) C# field, property, parameter or local variable initializer. /// (2) VB field(s), property, parameter or local variable initializer. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISymbolInitializerOperation : IOperation { /// <summary> /// Local declared in and scoped to the <see cref="Value" />. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Underlying initializer value. /// </summary> IOperation Value { get; } } /// <summary> /// Represents an initialization of a field. /// <para> /// Current usage: /// (1) C# field initializer with equals value clause. /// (2) VB field(s) initializer with equals value clause or AsNew clause. Multiple fields can be initialized with AsNew clause in VB. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.FieldInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IFieldInitializerOperation : ISymbolInitializerOperation { /// <summary> /// Initialized fields. There can be multiple fields for Visual Basic fields declared with AsNew clause. /// </summary> ImmutableArray<IFieldSymbol> InitializedFields { get; } } /// <summary> /// Represents an initialization of a local variable. /// <para> /// Current usage: /// (1) C# local variable initializer with equals value clause. /// (2) VB local variable initializer with equals value clause or AsNew clause. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.VariableInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IVariableInitializerOperation : ISymbolInitializerOperation { } /// <summary> /// Represents an initialization of a property. /// <para> /// Current usage: /// (1) C# property initializer with equals value clause. /// (2) VB property initializer with equals value clause or AsNew clause. Multiple properties can be initialized with 'WithEvents' declaration with AsNew clause in VB. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.PropertyInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPropertyInitializerOperation : ISymbolInitializerOperation { /// <summary> /// Initialized properties. There can be multiple properties for Visual Basic 'WithEvents' declaration with AsNew clause. /// </summary> ImmutableArray<IPropertySymbol> InitializedProperties { get; } } /// <summary> /// Represents an initialization of a parameter at the point of declaration. /// <para> /// Current usage: /// (1) C# parameter initializer with equals value clause. /// (2) VB parameter initializer with equals value clause. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ParameterInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IParameterInitializerOperation : ISymbolInitializerOperation { /// <summary> /// Initialized parameter. /// </summary> IParameterSymbol Parameter { get; } } /// <summary> /// Represents the initialization of an array instance. /// <para> /// Current usage: /// (1) C# array initializer. /// (2) VB array initializer. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ArrayInitializer"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IArrayInitializerOperation : IOperation { /// <summary> /// Values to initialize array elements. /// </summary> ImmutableArray<IOperation> ElementValues { get; } } /// <summary> /// Represents a single variable declarator and initializer. /// </summary> /// <para> /// Current Usage: /// (1) C# variable declarator /// (2) C# catch variable declaration /// (3) VB single variable declaration /// (4) VB catch variable declaration /// </para> /// <remarks> /// In VB, the initializer for this node is only ever used for explicit array bounds initializers. This node corresponds to /// the VariableDeclaratorSyntax in C# and the ModifiedIdentifierSyntax in VB. /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.VariableDeclarator"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IVariableDeclaratorOperation : IOperation { /// <summary> /// Symbol declared by this variable declaration /// </summary> ILocalSymbol Symbol { get; } /// <summary> /// Optional initializer of the variable. /// </summary> /// <remarks> /// If this variable is in an <see cref="IVariableDeclarationOperation" />, the initializer may be located /// in the parent operation. Call <see cref="OperationExtensions.GetVariableInitializer(IVariableDeclaratorOperation)" /> /// to check in all locations. It is only possible to have initializers in both locations in VB invalid code scenarios. /// </remarks> IVariableInitializerOperation? Initializer { get; } /// <summary> /// Additional arguments supplied to the declarator in error cases, ignored by the compiler. This only used for the C# case of /// DeclaredArgumentSyntax nodes on a VariableDeclaratorSyntax. /// </summary> ImmutableArray<IOperation> IgnoredArguments { get; } } /// <summary> /// Represents a declarator that declares multiple individual variables. /// </summary> /// <para> /// Current Usage: /// (1) C# VariableDeclaration /// (2) C# fixed declarations /// (3) VB Dim statement declaration groups /// (4) VB Using statement variable declarations /// </para> /// <remarks> /// The initializer of this node is applied to all individual declarations in <see cref="Declarators" />. There cannot /// be initializers in both locations except in invalid code scenarios. /// In C#, this node will never have an initializer. /// This corresponds to the VariableDeclarationSyntax in C#, and the VariableDeclaratorSyntax in Visual Basic. /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.VariableDeclaration"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IVariableDeclarationOperation : IOperation { /// <summary> /// Individual variable declarations declared by this multiple declaration. /// </summary> /// <remarks> /// All <see cref="IVariableDeclarationGroupOperation" /> will have at least 1 <see cref="IVariableDeclarationOperation" />, /// even if the declaration group only declares 1 variable. /// </remarks> ImmutableArray<IVariableDeclaratorOperation> Declarators { get; } /// <summary> /// Optional initializer of the variable. /// </summary> /// <remarks> /// In C#, this will always be null. /// </remarks> IVariableInitializerOperation? Initializer { get; } /// <summary> /// Array dimensions supplied to an array declaration in error cases, ignored by the compiler. This is only used for the C# case of /// RankSpecifierSyntax nodes on an ArrayTypeSyntax. /// </summary> ImmutableArray<IOperation> IgnoredDimensions { get; } } /// <summary> /// Represents an argument to a method invocation. /// <para> /// Current usage: /// (1) C# argument to an invocation expression, object creation expression, etc. /// (2) VB argument to an invocation expression, object creation expression, etc. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Argument"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IArgumentOperation : IOperation { /// <summary> /// Kind of argument. /// </summary> ArgumentKind ArgumentKind { get; } /// <summary> /// Parameter the argument matches. This can be null for __arglist parameters. /// </summary> IParameterSymbol? Parameter { get; } /// <summary> /// Value supplied for the argument. /// </summary> IOperation Value { get; } /// <summary> /// Information of the conversion applied to the argument value passing it into the target method. Applicable only to VB Reference arguments. /// </summary> CommonConversion InConversion { get; } /// <summary> /// Information of the conversion applied to the argument value after the invocation. Applicable only to VB Reference arguments. /// </summary> CommonConversion OutConversion { get; } } /// <summary> /// Represents a catch clause. /// <para> /// Current usage: /// (1) C# catch clause. /// (2) VB Catch clause. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.CatchClause"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICatchClauseOperation : IOperation { /// <summary> /// Optional source for exception. This could be any of the following operation: /// 1. Declaration for the local catch variable bound to the caught exception (C# and VB) OR /// 2. Null, indicating no declaration or expression (C# and VB) /// 3. Reference to an existing local or parameter (VB) OR /// 4. Other expression for error scenarios (VB) /// </summary> IOperation? ExceptionDeclarationOrExpression { get; } /// <summary> /// Type of the exception handled by the catch clause. /// </summary> ITypeSymbol ExceptionType { get; } /// <summary> /// Locals declared by the <see cref="ExceptionDeclarationOrExpression" /> and/or <see cref="Filter" /> clause. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Filter operation to be executed to determine whether to handle the exception. /// </summary> IOperation? Filter { get; } /// <summary> /// Body of the exception handler. /// </summary> IBlockOperation Handler { get; } } /// <summary> /// Represents a switch case section with one or more case clauses to match and one or more operations to execute within the section. /// <para> /// Current usage: /// (1) C# switch section for one or more case clause and set of statements to execute. /// (2) VB case block with a case statement for one or more case clause and set of statements to execute. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SwitchCase"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISwitchCaseOperation : IOperation { /// <summary> /// Clauses of the case. /// </summary> ImmutableArray<ICaseClauseOperation> Clauses { get; } /// <summary> /// One or more operations to execute within the switch section. /// </summary> ImmutableArray<IOperation> Body { get; } /// <summary> /// Locals declared within the switch case section scoped to the section. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } } /// <summary> /// Represents a case clause. /// <para> /// Current usage: /// (1) C# case clause. /// (2) VB Case clause. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICaseClauseOperation : IOperation { /// <summary> /// Kind of the clause. /// </summary> CaseKind CaseKind { get; } /// <summary> /// Label associated with the case clause, if any. /// </summary> ILabelSymbol? Label { get; } } /// <summary> /// Represents a default case clause. /// <para> /// Current usage: /// (1) C# default clause. /// (2) VB Case Else clause. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDefaultCaseClauseOperation : ICaseClauseOperation { } /// <summary> /// Represents a case clause with a pattern and an optional guard operation. /// <para> /// Current usage: /// (1) C# pattern case clause. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPatternCaseClauseOperation : ICaseClauseOperation { /// <summary> /// Label associated with the case clause. /// </summary> new ILabelSymbol Label { get; } /// <summary> /// Pattern associated with case clause. /// </summary> IPatternOperation Pattern { get; } /// <summary> /// Guard associated with the pattern case clause. /// </summary> IOperation? Guard { get; } } /// <summary> /// Represents a case clause with range of values for comparison. /// <para> /// Current usage: /// (1) VB range case clause of the form "Case x To y". /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRangeCaseClauseOperation : ICaseClauseOperation { /// <summary> /// Minimum value of the case range. /// </summary> IOperation MinimumValue { get; } /// <summary> /// Maximum value of the case range. /// </summary> IOperation MaximumValue { get; } } /// <summary> /// Represents a case clause with custom relational operator for comparison. /// <para> /// Current usage: /// (1) VB relational case clause of the form "Case Is op x". /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRelationalCaseClauseOperation : ICaseClauseOperation { /// <summary> /// Case value. /// </summary> IOperation Value { get; } /// <summary> /// Relational operator used to compare the switch value with the case value. /// </summary> BinaryOperatorKind Relation { get; } } /// <summary> /// Represents a case clause with a single value for comparison. /// <para> /// Current usage: /// (1) C# case clause of the form "case x" /// (2) VB case clause of the form "Case x". /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISingleValueCaseClauseOperation : ICaseClauseOperation { /// <summary> /// Case value. /// </summary> IOperation Value { get; } } /// <summary> /// Represents a constituent part of an interpolated string. /// <para> /// Current usage: /// (1) C# interpolated string content. /// (2) VB interpolated string content. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringContentOperation : IOperation { } /// <summary> /// Represents a constituent string literal part of an interpolated string operation. /// <para> /// Current usage: /// (1) C# interpolated string text. /// (2) VB interpolated string text. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InterpolatedStringText"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringTextOperation : IInterpolatedStringContentOperation { /// <summary> /// Text content. /// </summary> IOperation Text { get; } } /// <summary> /// Represents a constituent interpolation part of an interpolated string operation. /// <para> /// Current usage: /// (1) C# interpolation part. /// (2) VB interpolation part. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Interpolation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolationOperation : IInterpolatedStringContentOperation { /// <summary> /// Expression of the interpolation. /// </summary> IOperation Expression { get; } /// <summary> /// Optional alignment of the interpolation. /// </summary> IOperation? Alignment { get; } /// <summary> /// Optional format string of the interpolation. /// </summary> IOperation? FormatString { get; } } /// <summary> /// Represents a pattern matching operation. /// <para> /// Current usage: /// (1) C# pattern. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPatternOperation : IOperation { /// <summary> /// The input type to the pattern-matching operation. /// </summary> ITypeSymbol InputType { get; } /// <summary> /// The narrowed type of the pattern-matching operation. /// </summary> ITypeSymbol NarrowedType { get; } } /// <summary> /// Represents a pattern with a constant value. /// <para> /// Current usage: /// (1) C# constant pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ConstantPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConstantPatternOperation : IPatternOperation { /// <summary> /// Constant value of the pattern operation. /// </summary> IOperation Value { get; } } /// <summary> /// Represents a pattern that declares a symbol. /// <para> /// Current usage: /// (1) C# declaration pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DeclarationPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDeclarationPatternOperation : IPatternOperation { /// <summary> /// The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#). /// </summary> ITypeSymbol? MatchedType { get; } /// <summary> /// True if the pattern is of a form that accepts null. /// For example, in C# the pattern `var x` will match a null input, /// while the pattern `string x` will not. /// </summary> bool MatchesNull { get; } /// <summary> /// Symbol declared by the pattern, if any. /// </summary> ISymbol? DeclaredSymbol { get; } } /// <summary> /// Represents a comparison of two operands that returns a bool type. /// <para> /// Current usage: /// (1) C# tuple binary operator expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TupleBinary"/></description></item> /// <item><description><see cref="OperationKind.TupleBinaryOperator"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITupleBinaryOperation : IOperation { /// <summary> /// Kind of binary operation. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// Left operand. /// </summary> IOperation LeftOperand { get; } /// <summary> /// Right operand. /// </summary> IOperation RightOperand { get; } } /// <summary> /// Represents a method body operation. /// <para> /// Current usage: /// (1) C# method body /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMethodBodyBaseOperation : IOperation { /// <summary> /// Method body corresponding to BaseMethodDeclarationSyntax.Body or AccessorDeclarationSyntax.Body /// </summary> IBlockOperation? BlockBody { get; } /// <summary> /// Method body corresponding to BaseMethodDeclarationSyntax.ExpressionBody or AccessorDeclarationSyntax.ExpressionBody /// </summary> IBlockOperation? ExpressionBody { get; } } /// <summary> /// Represents a method body operation. /// <para> /// Current usage: /// (1) C# method body for non-constructor /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.MethodBody"/></description></item> /// <item><description><see cref="OperationKind.MethodBodyOperation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IMethodBodyOperation : IMethodBodyBaseOperation { } /// <summary> /// Represents a constructor method body operation. /// <para> /// Current usage: /// (1) C# method body for constructor declaration /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ConstructorBody"/></description></item> /// <item><description><see cref="OperationKind.ConstructorBodyOperation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IConstructorBodyOperation : IMethodBodyBaseOperation { /// <summary> /// Local declarations contained within the <see cref="Initializer" />. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Constructor initializer, if any. /// </summary> IOperation? Initializer { get; } } /// <summary> /// Represents a discard operation. /// <para> /// Current usage: C# discard expressions /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Discard"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDiscardOperation : IOperation { /// <summary> /// The symbol of the discard operation. /// </summary> IDiscardSymbol DiscardSymbol { get; } } /// <summary> /// Represents a coalesce assignment operation with a target and a conditionally-evaluated value: /// (1) <see cref="IAssignmentOperation.Target" /> is evaluated for null. If it is null, <see cref="IAssignmentOperation.Value" /> is evaluated and assigned to target. /// (2) <see cref="IAssignmentOperation.Value" /> is conditionally evaluated if <see cref="IAssignmentOperation.Target" /> is null, and the result is assigned into <see cref="IAssignmentOperation.Target" />. /// The result of the entire expression is<see cref="IAssignmentOperation.Target" />, which is only evaluated once. /// <para> /// Current usage: /// (1) C# null-coalescing assignment operation <code>Target ??= Value</code>. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.CoalesceAssignment"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ICoalesceAssignmentOperation : IAssignmentOperation { } /// <summary> /// Represents a range operation. /// <para> /// Current usage: /// (1) C# range expressions /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.Range"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRangeOperation : IOperation { /// <summary> /// Left operand. /// </summary> IOperation? LeftOperand { get; } /// <summary> /// Right operand. /// </summary> IOperation? RightOperand { get; } /// <summary> /// <code>true</code> if this is a 'lifted' range operation. When there is an /// operator that is defined to work on a value type, 'lifted' operators are /// created to work on the <see cref="System.Nullable{T}" /> versions of those /// value types. /// </summary> bool IsLifted { get; } /// <summary> /// Factory method used to create this Range value. Can be null if appropriate /// symbol was not found. /// </summary> IMethodSymbol? Method { get; } } /// <summary> /// Represents the ReDim operation to re-allocate storage space for array variables. /// <para> /// Current usage: /// (1) VB ReDim statement. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ReDim"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IReDimOperation : IOperation { /// <summary> /// Individual clauses of the ReDim operation. /// </summary> ImmutableArray<IReDimClauseOperation> Clauses { get; } /// <summary> /// Modifier used to preserve the data in the existing array when you change the size of only the last dimension. /// </summary> bool Preserve { get; } } /// <summary> /// Represents an individual clause of an <see cref="IReDimOperation" /> to re-allocate storage space for a single array variable. /// <para> /// Current usage: /// (1) VB ReDim clause. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.ReDimClause"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IReDimClauseOperation : IOperation { /// <summary> /// Operand whose storage space needs to be re-allocated. /// </summary> IOperation Operand { get; } /// <summary> /// Sizes of the dimensions of the created array instance. /// </summary> ImmutableArray<IOperation> DimensionSizes { get; } } /// <summary> /// Represents a C# recursive pattern. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.RecursivePattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRecursivePatternOperation : IPatternOperation { /// <summary> /// The type accepted for the recursive pattern. /// </summary> ITypeSymbol MatchedType { get; } /// <summary> /// The symbol, if any, used for the fetching values for subpatterns. This is either a <code>Deconstruct</code> /// method, the type <code>System.Runtime.CompilerServices.ITuple</code>, or null (for example, in /// error cases or when matching a tuple type). /// </summary> ISymbol? DeconstructSymbol { get; } /// <summary> /// This contains the patterns contained within a deconstruction or positional subpattern. /// </summary> ImmutableArray<IPatternOperation> DeconstructionSubpatterns { get; } /// <summary> /// This contains the (symbol, property) pairs within a property subpattern. /// </summary> ImmutableArray<IPropertySubpatternOperation> PropertySubpatterns { get; } /// <summary> /// Symbol declared by the pattern. /// </summary> ISymbol? DeclaredSymbol { get; } } /// <summary> /// Represents a discard pattern. /// <para> /// Current usage: C# discard pattern /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.DiscardPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IDiscardPatternOperation : IPatternOperation { } /// <summary> /// Represents a switch expression. /// <para> /// Current usage: /// (1) C# switch expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SwitchExpression"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISwitchExpressionOperation : IOperation { /// <summary> /// Value to be switched upon. /// </summary> IOperation Value { get; } /// <summary> /// Arms of the switch expression. /// </summary> ImmutableArray<ISwitchExpressionArmOperation> Arms { get; } /// <summary> /// True if the switch expressions arms cover every possible input value. /// </summary> bool IsExhaustive { get; } } /// <summary> /// Represents one arm of a switch expression. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.SwitchExpressionArm"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ISwitchExpressionArmOperation : IOperation { /// <summary> /// The pattern to match. /// </summary> IPatternOperation Pattern { get; } /// <summary> /// Guard (when clause expression) associated with the switch arm, if any. /// </summary> IOperation? Guard { get; } /// <summary> /// Result value of the enclosing switch expression when this arm matches. /// </summary> IOperation Value { get; } /// <summary> /// Locals declared within the switch arm (e.g. pattern locals and locals declared in the guard) scoped to the arm. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } } /// <summary> /// Represents an element of a property subpattern, which identifies a member to be matched and the /// pattern to match it against. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.PropertySubpattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IPropertySubpatternOperation : IOperation { /// <summary> /// The member being matched in a property subpattern. This can be a <see cref="IMemberReferenceOperation" /> /// in non-error cases, or an <see cref="IInvalidOperation" /> in error cases. /// </summary> IOperation Member { get; } /// <summary> /// The pattern to which the member is matched in a property subpattern. /// </summary> IPatternOperation Pattern { get; } } /// <summary> /// Represents a standalone VB query Aggregate operation with more than one item in Into clause. /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IAggregateQueryOperation : IOperation { IOperation Group { get; } IOperation Aggregation { get; } } /// <summary> /// Represents a C# fixed statement. /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IFixedOperation : IOperation { /// <summary> /// Locals declared. /// </summary> ImmutableArray<ILocalSymbol> Locals { get; } /// <summary> /// Variables to be fixed. /// </summary> IVariableDeclarationGroupOperation Variables { get; } /// <summary> /// Body of the fixed, over which the variables are fixed. /// </summary> IOperation Body { get; } } /// <summary> /// Represents a creation of an instance of a NoPia interface, i.e. new I(), where I is an embedded NoPia interface. /// <para> /// Current usage: /// (1) C# NoPia interface instance creation expression. /// (2) VB NoPia interface instance creation expression. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface INoPiaObjectCreationOperation : IOperation { /// <summary> /// Object or collection initializer, if any. /// </summary> IObjectOrCollectionInitializerOperation? Initializer { get; } } /// <summary> /// Represents a general placeholder when no more specific kind of placeholder is available. /// A placeholder is an expression whose meaning is inferred from context. /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IPlaceholderOperation : IOperation { PlaceholderKind PlaceholderKind { get; } } /// <summary> /// Represents a reference through a pointer. /// <para> /// Current usage: /// (1) C# pointer indirection reference expression. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IPointerIndirectionReferenceOperation : IOperation { /// <summary> /// Pointer to be dereferenced. /// </summary> IOperation Pointer { get; } } /// <summary> /// Represents a <see cref="Body" /> of operations that are executed with implicit reference to the <see cref="Value" /> for member references. /// <para> /// Current usage: /// (1) VB With statement. /// </para> /// </summary> /// <remarks> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> internal interface IWithStatementOperation : IOperation { /// <summary> /// Body of the with. /// </summary> IOperation Body { get; } /// <summary> /// Value to whose members leading-dot-qualified references within the with body bind. /// </summary> IOperation Value { get; } } /// <summary> /// Represents using variable declaration, with scope spanning across the parent <see cref="IBlockOperation" />. /// <para> /// Current Usage: /// (1) C# using declaration /// (1) C# asynchronous using declaration /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.UsingDeclaration"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IUsingDeclarationOperation : IOperation { /// <summary> /// The variables declared by this using declaration. /// </summary> IVariableDeclarationGroupOperation DeclarationGroup { get; } /// <summary> /// True if this is an asynchronous using declaration. /// </summary> bool IsAsynchronous { get; } } /// <summary> /// Represents a negated pattern. /// <para> /// Current usage: /// (1) C# negated pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.NegatedPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface INegatedPatternOperation : IPatternOperation { /// <summary> /// The negated pattern. /// </summary> IPatternOperation Pattern { get; } } /// <summary> /// Represents a binary ("and" or "or") pattern. /// <para> /// Current usage: /// (1) C# "and" and "or" patterns. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.BinaryPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IBinaryPatternOperation : IPatternOperation { /// <summary> /// Kind of binary pattern; either <see cref="BinaryOperatorKind.And" /> or <see cref="BinaryOperatorKind.Or" />. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// The pattern on the left. /// </summary> IPatternOperation LeftPattern { get; } /// <summary> /// The pattern on the right. /// </summary> IPatternOperation RightPattern { get; } } /// <summary> /// Represents a pattern comparing the input with a given type. /// <para> /// Current usage: /// (1) C# type pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.TypePattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface ITypePatternOperation : IPatternOperation { /// <summary> /// The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#). /// </summary> ITypeSymbol MatchedType { get; } } /// <summary> /// Represents a pattern comparing the input with a constant value using a relational operator. /// <para> /// Current usage: /// (1) C# relational pattern. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.RelationalPattern"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IRelationalPatternOperation : IPatternOperation { /// <summary> /// The kind of the relational operator. /// </summary> BinaryOperatorKind OperatorKind { get; } /// <summary> /// Constant value of the pattern operation. /// </summary> IOperation Value { get; } } /// <summary> /// Represents cloning of an object instance. /// <para> /// Current usage: /// (1) C# with expression. /// </para> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.With"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IWithOperation : IOperation { /// <summary> /// Operand to be cloned. /// </summary> IOperation Operand { get; } /// <summary> /// Clone method to be invoked on the value. This can be null in error scenarios. /// </summary> IMethodSymbol? CloneMethod { get; } /// <summary> /// With collection initializer. /// </summary> IObjectOrCollectionInitializerOperation Initializer { get; } } /// <summary> /// Represents an interpolated string converted to a custom interpolated string handler type. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InterpolatedStringHandlerCreation"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringHandlerCreationOperation : IOperation { /// <summary> /// The construction of the interpolated string handler instance. This can be an <see cref="IObjectCreationOperation" /> for valid code, and /// <see cref="IDynamicObjectCreationOperation" /> or <see cref="IInvalidOperation" /> for invalid code. /// </summary> IOperation HandlerCreation { get; } /// <summary> /// True if the last parameter of <see cref="HandlerCreation" /> is an out <see langword="bool" /> parameter that will be checked before executing the code in /// <see cref="Content" />. False otherwise. /// </summary> bool HandlerCreationHasSuccessParameter { get; } /// <summary> /// True if the AppendLiteral or AppendFormatted calls in nested <see cref="IInterpolatedStringOperation.Parts" /> return <see langword="bool" />. When that is true, each part /// will be conditional on the return of the part before it, only being executed when the Append call returns true. False otherwise. /// </summary> /// <remarks> /// when this is true and <see cref="HandlerCreationHasSuccessParameter" /> is true, then the first part in nested <see cref="IInterpolatedStringOperation.Parts" /> is conditionally /// run. If this is true and <see cref="HandlerCreationHasSuccessParameter" /> is false, then the first part is unconditionally run. /// <br /> /// Just because this is true or false does not guarantee that all Append calls actually do return boolean values, as there could be dynamic calls or errors. /// It only governs what the compiler was expecting, based on the first calls it did see. /// </remarks> bool HandlerAppendCallsReturnBool { get; } /// <summary> /// The interpolated string expression or addition operation that makes up the content of this string. This is either an <see cref="IInterpolatedStringOperation" /> /// or an <see cref="IInterpolatedStringAdditionOperation" /> operation. /// </summary> IOperation Content { get; } } /// <summary> /// Represents an addition of multiple interpolated string literals being converted to an interpolated string handler type. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InterpolatedStringAddition"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringAdditionOperation : IOperation { /// <summary> /// The interpolated string expression or addition operation on the left side of the operator. This is either an <see cref="IInterpolatedStringOperation" /> /// or an <see cref="IInterpolatedStringAdditionOperation" /> operation. /// </summary> IOperation Left { get; } /// <summary> /// The interpolated string expression or addition operation on the right side of the operator. This is either an <see cref="IInterpolatedStringOperation" /> /// or an <see cref="IInterpolatedStringAdditionOperation" /> operation. /// </summary> IOperation Right { get; } } /// <summary> /// Represents a call to either AppendLiteral or AppendFormatted as part of an interpolated string handler conversion. /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InterpolatedStringAppendLiteral"/></description></item> /// <item><description><see cref="OperationKind.InterpolatedStringAppendFormatted"/></description></item> /// <item><description><see cref="OperationKind.InterpolatedStringAppendInvalid"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringAppendOperation : IInterpolatedStringContentOperation { /// <summary> /// If this interpolated string is subject to an interpolated string handler conversion, the construction of the interpolated string handler instance. /// This can be an <see cref="IInvocationOperation" /> or <see cref="IDynamicInvocationOperation" /> for valid code, and <see cref="IInvalidOperation" /> for invalid code. /// </summary> IOperation AppendCall { get; } } /// <summary> /// Represents an argument from the method call, indexer access, or constructor invocation that is creating the containing <see cref="IInterpolatedStringHandlerCreationOperation" /> /// </summary> /// <remarks> /// <para>This node is associated with the following operation kinds:</para> /// <list type="bullet"> /// <item><description><see cref="OperationKind.InterpolatedStringHandlerArgumentPlaceholder"/></description></item> /// </list> /// <para>This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future.</para> /// </remarks> public interface IInterpolatedStringHandlerArgumentPlaceholderOperation : IOperation { /// <summary> /// The index of the argument of the method call, indexer, or object creation containing the interpolated string handler conversion this placeholder is referencing. /// -1 if <see cref="PlaceholderKind" /> is anything other than <see cref="InterpolatedStringArgumentPlaceholderKind.CallsiteArgument" />. /// </summary> int ArgumentIndex { get; } /// <summary> /// The component this placeholder represents. /// </summary> InterpolatedStringArgumentPlaceholderKind PlaceholderKind { get; } } #endregion #region Implementations internal sealed partial class BlockOperation : Operation, IBlockOperation { internal BlockOperation(ImmutableArray<IOperation> operations, ImmutableArray<ILocalSymbol> locals, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operations = SetParentOperation(operations, this); Locals = locals; } public ImmutableArray<IOperation> Operations { get; } public ImmutableArray<ILocalSymbol> Locals { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Operations.Length => Operations[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Operations.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Operations.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Block; public override void Accept(OperationVisitor visitor) => visitor.VisitBlock(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitBlock(this, argument); } internal sealed partial class VariableDeclarationGroupOperation : Operation, IVariableDeclarationGroupOperation { internal VariableDeclarationGroupOperation(ImmutableArray<IVariableDeclarationOperation> declarations, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Declarations = SetParentOperation(declarations, this); } public ImmutableArray<IVariableDeclarationOperation> Declarations { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Declarations.Length => Declarations[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Declarations.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Declarations.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.VariableDeclarationGroup; public override void Accept(OperationVisitor visitor) => visitor.VisitVariableDeclarationGroup(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitVariableDeclarationGroup(this, argument); } internal sealed partial class SwitchOperation : Operation, ISwitchOperation { internal SwitchOperation(ImmutableArray<ILocalSymbol> locals, IOperation value, ImmutableArray<ISwitchCaseOperation> cases, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Locals = locals; Value = SetParentOperation(value, this); Cases = SetParentOperation(cases, this); ExitLabel = exitLabel; } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation Value { get; } public ImmutableArray<ISwitchCaseOperation> Cases { get; } public ILabelSymbol ExitLabel { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when index < Cases.Length => Cases[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (!Cases.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Cases.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Switch; public override void Accept(OperationVisitor visitor) => visitor.VisitSwitch(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSwitch(this, argument); } internal abstract partial class BaseLoopOperation : Operation, ILoopOperation { protected BaseLoopOperation(IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Body = SetParentOperation(body, this); Locals = locals; ContinueLabel = continueLabel; ExitLabel = exitLabel; } public abstract LoopKind LoopKind { get; } public IOperation Body { get; } public ImmutableArray<ILocalSymbol> Locals { get; } public ILabelSymbol ContinueLabel { get; } public ILabelSymbol ExitLabel { get; } } internal sealed partial class ForEachLoopOperation : BaseLoopOperation, IForEachLoopOperation { internal ForEachLoopOperation(IOperation loopControlVariable, IOperation collection, ImmutableArray<IOperation> nextVariables, ForEachLoopOperationInfo? info, bool isAsynchronous, IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) { LoopControlVariable = SetParentOperation(loopControlVariable, this); Collection = SetParentOperation(collection, this); NextVariables = SetParentOperation(nextVariables, this); Info = info; IsAsynchronous = isAsynchronous; } public IOperation LoopControlVariable { get; } public IOperation Collection { get; } public ImmutableArray<IOperation> NextVariables { get; } public ForEachLoopOperationInfo? Info { get; } public bool IsAsynchronous { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Collection != null => Collection, 1 when LoopControlVariable != null => LoopControlVariable, 2 when Body != null => Body, 3 when index < NextVariables.Length => NextVariables[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Collection != null) return (true, 0, 0); else goto case 0; case 0: if (LoopControlVariable != null) return (true, 1, 0); else goto case 1; case 1: if (Body != null) return (true, 2, 0); else goto case 2; case 2: if (!NextVariables.IsEmpty) return (true, 3, 0); else goto case 3; case 3 when previousIndex + 1 < NextVariables.Length: return (true, 3, previousIndex + 1); case 3: case 4: return (false, 4, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Loop; public override void Accept(OperationVisitor visitor) => visitor.VisitForEachLoop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitForEachLoop(this, argument); } internal sealed partial class ForLoopOperation : BaseLoopOperation, IForLoopOperation { internal ForLoopOperation(ImmutableArray<IOperation> before, ImmutableArray<ILocalSymbol> conditionLocals, IOperation? condition, ImmutableArray<IOperation> atLoopBottom, IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) { Before = SetParentOperation(before, this); ConditionLocals = conditionLocals; Condition = SetParentOperation(condition, this); AtLoopBottom = SetParentOperation(atLoopBottom, this); } public ImmutableArray<IOperation> Before { get; } public ImmutableArray<ILocalSymbol> ConditionLocals { get; } public IOperation? Condition { get; } public ImmutableArray<IOperation> AtLoopBottom { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Before.Length => Before[index], 1 when Condition != null => Condition, 2 when Body != null => Body, 3 when index < AtLoopBottom.Length => AtLoopBottom[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Before.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Before.Length: return (true, 0, previousIndex + 1); case 0: if (Condition != null) return (true, 1, 0); else goto case 1; case 1: if (Body != null) return (true, 2, 0); else goto case 2; case 2: if (!AtLoopBottom.IsEmpty) return (true, 3, 0); else goto case 3; case 3 when previousIndex + 1 < AtLoopBottom.Length: return (true, 3, previousIndex + 1); case 3: case 4: return (false, 4, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Loop; public override void Accept(OperationVisitor visitor) => visitor.VisitForLoop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitForLoop(this, argument); } internal sealed partial class ForToLoopOperation : BaseLoopOperation, IForToLoopOperation { internal ForToLoopOperation(IOperation loopControlVariable, IOperation initialValue, IOperation limitValue, IOperation stepValue, bool isChecked, ImmutableArray<IOperation> nextVariables, (ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo) info, IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) { LoopControlVariable = SetParentOperation(loopControlVariable, this); InitialValue = SetParentOperation(initialValue, this); LimitValue = SetParentOperation(limitValue, this); StepValue = SetParentOperation(stepValue, this); IsChecked = isChecked; NextVariables = SetParentOperation(nextVariables, this); Info = info; } public IOperation LoopControlVariable { get; } public IOperation InitialValue { get; } public IOperation LimitValue { get; } public IOperation StepValue { get; } public bool IsChecked { get; } public ImmutableArray<IOperation> NextVariables { get; } public (ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo) Info { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LoopControlVariable != null => LoopControlVariable, 1 when InitialValue != null => InitialValue, 2 when LimitValue != null => LimitValue, 3 when StepValue != null => StepValue, 4 when Body != null => Body, 5 when index < NextVariables.Length => NextVariables[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LoopControlVariable != null) return (true, 0, 0); else goto case 0; case 0: if (InitialValue != null) return (true, 1, 0); else goto case 1; case 1: if (LimitValue != null) return (true, 2, 0); else goto case 2; case 2: if (StepValue != null) return (true, 3, 0); else goto case 3; case 3: if (Body != null) return (true, 4, 0); else goto case 4; case 4: if (!NextVariables.IsEmpty) return (true, 5, 0); else goto case 5; case 5 when previousIndex + 1 < NextVariables.Length: return (true, 5, previousIndex + 1); case 5: case 6: return (false, 6, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Loop; public override void Accept(OperationVisitor visitor) => visitor.VisitForToLoop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitForToLoop(this, argument); } internal sealed partial class WhileLoopOperation : BaseLoopOperation, IWhileLoopOperation { internal WhileLoopOperation(IOperation? condition, bool conditionIsTop, bool conditionIsUntil, IOperation? ignoredCondition, IOperation body, ImmutableArray<ILocalSymbol> locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) { Condition = SetParentOperation(condition, this); ConditionIsTop = conditionIsTop; ConditionIsUntil = conditionIsUntil; IgnoredCondition = SetParentOperation(ignoredCondition, this); } public IOperation? Condition { get; } public bool ConditionIsTop { get; } public bool ConditionIsUntil { get; } public IOperation? IgnoredCondition { get; } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Loop; public override void Accept(OperationVisitor visitor) => visitor.VisitWhileLoop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitWhileLoop(this, argument); } internal sealed partial class LabeledOperation : Operation, ILabeledOperation { internal LabeledOperation(ILabelSymbol label, IOperation? operation, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Label = label; Operation = SetParentOperation(operation, this); } public ILabelSymbol Label { get; } public IOperation? Operation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Labeled; public override void Accept(OperationVisitor visitor) => visitor.VisitLabeled(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLabeled(this, argument); } internal sealed partial class BranchOperation : Operation, IBranchOperation { internal BranchOperation(ILabelSymbol target, BranchKind branchKind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Target = target; BranchKind = branchKind; } public ILabelSymbol Target { get; } public BranchKind BranchKind { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Branch; public override void Accept(OperationVisitor visitor) => visitor.VisitBranch(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitBranch(this, argument); } internal sealed partial class EmptyOperation : Operation, IEmptyOperation { internal EmptyOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Empty; public override void Accept(OperationVisitor visitor) => visitor.VisitEmpty(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitEmpty(this, argument); } internal sealed partial class ReturnOperation : Operation, IReturnOperation { internal ReturnOperation(IOperation? returnedValue, OperationKind kind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ReturnedValue = SetParentOperation(returnedValue, this); Kind = kind; } public IOperation? ReturnedValue { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when ReturnedValue != null => ReturnedValue, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (ReturnedValue != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind { get; } public override void Accept(OperationVisitor visitor) => visitor.VisitReturn(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitReturn(this, argument); } internal sealed partial class LockOperation : Operation, ILockOperation { internal LockOperation(IOperation lockedValue, IOperation body, ILocalSymbol? lockTakenSymbol, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { LockedValue = SetParentOperation(lockedValue, this); Body = SetParentOperation(body, this); LockTakenSymbol = lockTakenSymbol; } public IOperation LockedValue { get; } public IOperation Body { get; } public ILocalSymbol? LockTakenSymbol { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LockedValue != null => LockedValue, 1 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LockedValue != null) return (true, 0, 0); else goto case 0; case 0: if (Body != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Lock; public override void Accept(OperationVisitor visitor) => visitor.VisitLock(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLock(this, argument); } internal sealed partial class TryOperation : Operation, ITryOperation { internal TryOperation(IBlockOperation body, ImmutableArray<ICatchClauseOperation> catches, IBlockOperation? @finally, ILabelSymbol? exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Body = SetParentOperation(body, this); Catches = SetParentOperation(catches, this); Finally = SetParentOperation(@finally, this); ExitLabel = exitLabel; } public IBlockOperation Body { get; } public ImmutableArray<ICatchClauseOperation> Catches { get; } public IBlockOperation? Finally { get; } public ILabelSymbol? ExitLabel { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Body != null => Body, 1 when index < Catches.Length => Catches[index], 2 when Finally != null => Finally, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Body != null) return (true, 0, 0); else goto case 0; case 0: if (!Catches.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Catches.Length: return (true, 1, previousIndex + 1); case 1: if (Finally != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Try; public override void Accept(OperationVisitor visitor) => visitor.VisitTry(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTry(this, argument); } internal sealed partial class UsingOperation : Operation, IUsingOperation { internal UsingOperation(IOperation resources, IOperation body, ImmutableArray<ILocalSymbol> locals, bool isAsynchronous, DisposeOperationInfo disposeInfo, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Resources = SetParentOperation(resources, this); Body = SetParentOperation(body, this); Locals = locals; IsAsynchronous = isAsynchronous; DisposeInfo = disposeInfo; } public IOperation Resources { get; } public IOperation Body { get; } public ImmutableArray<ILocalSymbol> Locals { get; } public bool IsAsynchronous { get; } public DisposeOperationInfo DisposeInfo { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Resources != null => Resources, 1 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Resources != null) return (true, 0, 0); else goto case 0; case 0: if (Body != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Using; public override void Accept(OperationVisitor visitor) => visitor.VisitUsing(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitUsing(this, argument); } internal sealed partial class ExpressionStatementOperation : Operation, IExpressionStatementOperation { internal ExpressionStatementOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operation = SetParentOperation(operation, this); } public IOperation Operation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ExpressionStatement; public override void Accept(OperationVisitor visitor) => visitor.VisitExpressionStatement(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitExpressionStatement(this, argument); } internal sealed partial class LocalFunctionOperation : Operation, ILocalFunctionOperation { internal LocalFunctionOperation(IMethodSymbol symbol, IBlockOperation? body, IBlockOperation? ignoredBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Symbol = symbol; Body = SetParentOperation(body, this); IgnoredBody = SetParentOperation(ignoredBody, this); } public IMethodSymbol Symbol { get; } public IBlockOperation? Body { get; } public IBlockOperation? IgnoredBody { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Body != null => Body, 1 when IgnoredBody != null => IgnoredBody, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Body != null) return (true, 0, 0); else goto case 0; case 0: if (IgnoredBody != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.LocalFunction; public override void Accept(OperationVisitor visitor) => visitor.VisitLocalFunction(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLocalFunction(this, argument); } internal sealed partial class StopOperation : Operation, IStopOperation { internal StopOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Stop; public override void Accept(OperationVisitor visitor) => visitor.VisitStop(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitStop(this, argument); } internal sealed partial class EndOperation : Operation, IEndOperation { internal EndOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.End; public override void Accept(OperationVisitor visitor) => visitor.VisitEnd(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitEnd(this, argument); } internal sealed partial class RaiseEventOperation : Operation, IRaiseEventOperation { internal RaiseEventOperation(IEventReferenceOperation eventReference, ImmutableArray<IArgumentOperation> arguments, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { EventReference = SetParentOperation(eventReference, this); Arguments = SetParentOperation(arguments, this); } public IEventReferenceOperation EventReference { get; } public ImmutableArray<IArgumentOperation> Arguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when EventReference != null => EventReference, 1 when index < Arguments.Length => Arguments[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (EventReference != null) return (true, 0, 0); else goto case 0; case 0: if (!Arguments.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Arguments.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.RaiseEvent; public override void Accept(OperationVisitor visitor) => visitor.VisitRaiseEvent(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRaiseEvent(this, argument); } internal sealed partial class LiteralOperation : Operation, ILiteralOperation { internal LiteralOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperationConstantValue = constantValue; Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Literal; public override void Accept(OperationVisitor visitor) => visitor.VisitLiteral(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLiteral(this, argument); } internal sealed partial class ConversionOperation : Operation, IConversionOperation { internal ConversionOperation(IOperation operand, IConvertibleConversion conversion, bool isTryCast, bool isChecked, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); ConversionConvertible = conversion; IsTryCast = isTryCast; IsChecked = isChecked; OperationConstantValue = constantValue; Type = type; } public IOperation Operand { get; } internal IConvertibleConversion ConversionConvertible { get; } public CommonConversion Conversion => ConversionConvertible.ToCommonConversion(); public bool IsTryCast { get; } public bool IsChecked { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Conversion; public override void Accept(OperationVisitor visitor) => visitor.VisitConversion(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConversion(this, argument); } internal sealed partial class InvocationOperation : Operation, IInvocationOperation { internal InvocationOperation(IMethodSymbol targetMethod, IOperation? instance, bool isVirtual, ImmutableArray<IArgumentOperation> arguments, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { TargetMethod = targetMethod; Instance = SetParentOperation(instance, this); IsVirtual = isVirtual; Arguments = SetParentOperation(arguments, this); Type = type; } public IMethodSymbol TargetMethod { get; } public IOperation? Instance { get; } public bool IsVirtual { get; } public ImmutableArray<IArgumentOperation> Arguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, 1 when index < Arguments.Length => Arguments[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: if (!Arguments.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Arguments.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Invocation; public override void Accept(OperationVisitor visitor) => visitor.VisitInvocation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInvocation(this, argument); } internal sealed partial class ArrayElementReferenceOperation : Operation, IArrayElementReferenceOperation { internal ArrayElementReferenceOperation(IOperation arrayReference, ImmutableArray<IOperation> indices, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ArrayReference = SetParentOperation(arrayReference, this); Indices = SetParentOperation(indices, this); Type = type; } public IOperation ArrayReference { get; } public ImmutableArray<IOperation> Indices { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when ArrayReference != null => ArrayReference, 1 when index < Indices.Length => Indices[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (ArrayReference != null) return (true, 0, 0); else goto case 0; case 0: if (!Indices.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Indices.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ArrayElementReference; public override void Accept(OperationVisitor visitor) => visitor.VisitArrayElementReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitArrayElementReference(this, argument); } internal sealed partial class LocalReferenceOperation : Operation, ILocalReferenceOperation { internal LocalReferenceOperation(ILocalSymbol local, bool isDeclaration, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Local = local; IsDeclaration = isDeclaration; OperationConstantValue = constantValue; Type = type; } public ILocalSymbol Local { get; } public bool IsDeclaration { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.LocalReference; public override void Accept(OperationVisitor visitor) => visitor.VisitLocalReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitLocalReference(this, argument); } internal sealed partial class ParameterReferenceOperation : Operation, IParameterReferenceOperation { internal ParameterReferenceOperation(IParameterSymbol parameter, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Parameter = parameter; Type = type; } public IParameterSymbol Parameter { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ParameterReference; public override void Accept(OperationVisitor visitor) => visitor.VisitParameterReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitParameterReference(this, argument); } internal abstract partial class BaseMemberReferenceOperation : Operation, IMemberReferenceOperation { protected BaseMemberReferenceOperation(IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Instance = SetParentOperation(instance, this); } public IOperation? Instance { get; } } internal sealed partial class FieldReferenceOperation : BaseMemberReferenceOperation, IFieldReferenceOperation { internal FieldReferenceOperation(IFieldSymbol field, bool isDeclaration, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(instance, semanticModel, syntax, isImplicit) { Field = field; IsDeclaration = isDeclaration; OperationConstantValue = constantValue; Type = type; } public IFieldSymbol Field { get; } public bool IsDeclaration { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.FieldReference; public override void Accept(OperationVisitor visitor) => visitor.VisitFieldReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFieldReference(this, argument); } internal sealed partial class MethodReferenceOperation : BaseMemberReferenceOperation, IMethodReferenceOperation { internal MethodReferenceOperation(IMethodSymbol method, bool isVirtual, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(instance, semanticModel, syntax, isImplicit) { Method = method; IsVirtual = isVirtual; Type = type; } public IMethodSymbol Method { get; } public bool IsVirtual { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.MethodReference; public override void Accept(OperationVisitor visitor) => visitor.VisitMethodReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitMethodReference(this, argument); } internal sealed partial class PropertyReferenceOperation : BaseMemberReferenceOperation, IPropertyReferenceOperation { internal PropertyReferenceOperation(IPropertySymbol property, ImmutableArray<IArgumentOperation> arguments, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(instance, semanticModel, syntax, isImplicit) { Property = property; Arguments = SetParentOperation(arguments, this); Type = type; } public IPropertySymbol Property { get; } public ImmutableArray<IArgumentOperation> Arguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, 1 when index < Arguments.Length => Arguments[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: if (!Arguments.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Arguments.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.PropertyReference; public override void Accept(OperationVisitor visitor) => visitor.VisitPropertyReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPropertyReference(this, argument); } internal sealed partial class EventReferenceOperation : BaseMemberReferenceOperation, IEventReferenceOperation { internal EventReferenceOperation(IEventSymbol @event, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(instance, semanticModel, syntax, isImplicit) { Event = @event; Type = type; } public IEventSymbol Event { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.EventReference; public override void Accept(OperationVisitor visitor) => visitor.VisitEventReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitEventReference(this, argument); } internal sealed partial class UnaryOperation : Operation, IUnaryOperation { internal UnaryOperation(UnaryOperatorKind operatorKind, IOperation operand, bool isLifted, bool isChecked, IMethodSymbol? operatorMethod, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; Operand = SetParentOperation(operand, this); IsLifted = isLifted; IsChecked = isChecked; OperatorMethod = operatorMethod; OperationConstantValue = constantValue; Type = type; } public UnaryOperatorKind OperatorKind { get; } public IOperation Operand { get; } public bool IsLifted { get; } public bool IsChecked { get; } public IMethodSymbol? OperatorMethod { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Unary; public override void Accept(OperationVisitor visitor) => visitor.VisitUnaryOperator(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitUnaryOperator(this, argument); } internal sealed partial class BinaryOperation : Operation, IBinaryOperation { internal BinaryOperation(BinaryOperatorKind operatorKind, IOperation leftOperand, IOperation rightOperand, bool isLifted, bool isChecked, bool isCompareText, IMethodSymbol? operatorMethod, IMethodSymbol? unaryOperatorMethod, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; LeftOperand = SetParentOperation(leftOperand, this); RightOperand = SetParentOperation(rightOperand, this); IsLifted = isLifted; IsChecked = isChecked; IsCompareText = isCompareText; OperatorMethod = operatorMethod; UnaryOperatorMethod = unaryOperatorMethod; OperationConstantValue = constantValue; Type = type; } public BinaryOperatorKind OperatorKind { get; } public IOperation LeftOperand { get; } public IOperation RightOperand { get; } public bool IsLifted { get; } public bool IsChecked { get; } public bool IsCompareText { get; } public IMethodSymbol? OperatorMethod { get; } public IMethodSymbol? UnaryOperatorMethod { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LeftOperand != null => LeftOperand, 1 when RightOperand != null => RightOperand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LeftOperand != null) return (true, 0, 0); else goto case 0; case 0: if (RightOperand != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Binary; public override void Accept(OperationVisitor visitor) => visitor.VisitBinaryOperator(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitBinaryOperator(this, argument); } internal sealed partial class ConditionalOperation : Operation, IConditionalOperation { internal ConditionalOperation(IOperation condition, IOperation whenTrue, IOperation? whenFalse, bool isRef, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Condition = SetParentOperation(condition, this); WhenTrue = SetParentOperation(whenTrue, this); WhenFalse = SetParentOperation(whenFalse, this); IsRef = isRef; OperationConstantValue = constantValue; Type = type; } public IOperation Condition { get; } public IOperation WhenTrue { get; } public IOperation? WhenFalse { get; } public bool IsRef { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Condition != null => Condition, 1 when WhenTrue != null => WhenTrue, 2 when WhenFalse != null => WhenFalse, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Condition != null) return (true, 0, 0); else goto case 0; case 0: if (WhenTrue != null) return (true, 1, 0); else goto case 1; case 1: if (WhenFalse != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Conditional; public override void Accept(OperationVisitor visitor) => visitor.VisitConditional(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConditional(this, argument); } internal sealed partial class CoalesceOperation : Operation, ICoalesceOperation { internal CoalesceOperation(IOperation value, IOperation whenNull, IConvertibleConversion valueConversion, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); WhenNull = SetParentOperation(whenNull, this); ValueConversionConvertible = valueConversion; OperationConstantValue = constantValue; Type = type; } public IOperation Value { get; } public IOperation WhenNull { get; } internal IConvertibleConversion ValueConversionConvertible { get; } public CommonConversion ValueConversion => ValueConversionConvertible.ToCommonConversion(); protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when WhenNull != null => WhenNull, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (WhenNull != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Coalesce; public override void Accept(OperationVisitor visitor) => visitor.VisitCoalesce(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCoalesce(this, argument); } internal sealed partial class AnonymousFunctionOperation : Operation, IAnonymousFunctionOperation { internal AnonymousFunctionOperation(IMethodSymbol symbol, IBlockOperation body, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Symbol = symbol; Body = SetParentOperation(body, this); } public IMethodSymbol Symbol { get; } public IBlockOperation Body { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Body != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.AnonymousFunction; public override void Accept(OperationVisitor visitor) => visitor.VisitAnonymousFunction(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAnonymousFunction(this, argument); } internal sealed partial class ObjectCreationOperation : Operation, IObjectCreationOperation { internal ObjectCreationOperation(IMethodSymbol? constructor, IObjectOrCollectionInitializerOperation? initializer, ImmutableArray<IArgumentOperation> arguments, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Constructor = constructor; Initializer = SetParentOperation(initializer, this); Arguments = SetParentOperation(arguments, this); OperationConstantValue = constantValue; Type = type; } public IMethodSymbol? Constructor { get; } public IObjectOrCollectionInitializerOperation? Initializer { get; } public ImmutableArray<IArgumentOperation> Arguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Arguments.Length => Arguments[index], 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Arguments.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Arguments.Length: return (true, 0, previousIndex + 1); case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.ObjectCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitObjectCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitObjectCreation(this, argument); } internal sealed partial class TypeParameterObjectCreationOperation : Operation, ITypeParameterObjectCreationOperation { internal TypeParameterObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Initializer = SetParentOperation(initializer, this); Type = type; } public IObjectOrCollectionInitializerOperation? Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Initializer != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TypeParameterObjectCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitTypeParameterObjectCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTypeParameterObjectCreation(this, argument); } internal sealed partial class ArrayCreationOperation : Operation, IArrayCreationOperation { internal ArrayCreationOperation(ImmutableArray<IOperation> dimensionSizes, IArrayInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { DimensionSizes = SetParentOperation(dimensionSizes, this); Initializer = SetParentOperation(initializer, this); Type = type; } public ImmutableArray<IOperation> DimensionSizes { get; } public IArrayInitializerOperation? Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < DimensionSizes.Length => DimensionSizes[index], 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!DimensionSizes.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < DimensionSizes.Length: return (true, 0, previousIndex + 1); case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ArrayCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitArrayCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitArrayCreation(this, argument); } internal sealed partial class InstanceReferenceOperation : Operation, IInstanceReferenceOperation { internal InstanceReferenceOperation(InstanceReferenceKind referenceKind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ReferenceKind = referenceKind; Type = type; } public InstanceReferenceKind ReferenceKind { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.InstanceReference; public override void Accept(OperationVisitor visitor) => visitor.VisitInstanceReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInstanceReference(this, argument); } internal sealed partial class IsTypeOperation : Operation, IIsTypeOperation { internal IsTypeOperation(IOperation valueOperand, ITypeSymbol typeOperand, bool isNegated, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ValueOperand = SetParentOperation(valueOperand, this); TypeOperand = typeOperand; IsNegated = isNegated; Type = type; } public IOperation ValueOperand { get; } public ITypeSymbol TypeOperand { get; } public bool IsNegated { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when ValueOperand != null => ValueOperand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (ValueOperand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.IsType; public override void Accept(OperationVisitor visitor) => visitor.VisitIsType(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitIsType(this, argument); } internal sealed partial class AwaitOperation : Operation, IAwaitOperation { internal AwaitOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operation = SetParentOperation(operation, this); Type = type; } public IOperation Operation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Await; public override void Accept(OperationVisitor visitor) => visitor.VisitAwait(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAwait(this, argument); } internal abstract partial class BaseAssignmentOperation : Operation, IAssignmentOperation { protected BaseAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Target = SetParentOperation(target, this); Value = SetParentOperation(value, this); } public IOperation Target { get; } public IOperation Value { get; } } internal sealed partial class SimpleAssignmentOperation : BaseAssignmentOperation, ISimpleAssignmentOperation { internal SimpleAssignmentOperation(bool isRef, IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(target, value, semanticModel, syntax, isImplicit) { IsRef = isRef; OperationConstantValue = constantValue; Type = type; } public bool IsRef { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, 1 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: if (Value != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.SimpleAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitSimpleAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSimpleAssignment(this, argument); } internal sealed partial class CompoundAssignmentOperation : BaseAssignmentOperation, ICompoundAssignmentOperation { internal CompoundAssignmentOperation(IConvertibleConversion inConversion, IConvertibleConversion outConversion, BinaryOperatorKind operatorKind, bool isLifted, bool isChecked, IMethodSymbol? operatorMethod, IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(target, value, semanticModel, syntax, isImplicit) { InConversionConvertible = inConversion; OutConversionConvertible = outConversion; OperatorKind = operatorKind; IsLifted = isLifted; IsChecked = isChecked; OperatorMethod = operatorMethod; Type = type; } internal IConvertibleConversion InConversionConvertible { get; } public CommonConversion InConversion => InConversionConvertible.ToCommonConversion(); internal IConvertibleConversion OutConversionConvertible { get; } public CommonConversion OutConversion => OutConversionConvertible.ToCommonConversion(); public BinaryOperatorKind OperatorKind { get; } public bool IsLifted { get; } public bool IsChecked { get; } public IMethodSymbol? OperatorMethod { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, 1 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: if (Value != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CompoundAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitCompoundAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCompoundAssignment(this, argument); } internal sealed partial class ParenthesizedOperation : Operation, IParenthesizedOperation { internal ParenthesizedOperation(IOperation operand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); OperationConstantValue = constantValue; Type = type; } public IOperation Operand { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.Parenthesized; public override void Accept(OperationVisitor visitor) => visitor.VisitParenthesized(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitParenthesized(this, argument); } internal sealed partial class EventAssignmentOperation : Operation, IEventAssignmentOperation { internal EventAssignmentOperation(IOperation eventReference, IOperation handlerValue, bool adds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { EventReference = SetParentOperation(eventReference, this); HandlerValue = SetParentOperation(handlerValue, this); Adds = adds; Type = type; } public IOperation EventReference { get; } public IOperation HandlerValue { get; } public bool Adds { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when EventReference != null => EventReference, 1 when HandlerValue != null => HandlerValue, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (EventReference != null) return (true, 0, 0); else goto case 0; case 0: if (HandlerValue != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.EventAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitEventAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitEventAssignment(this, argument); } internal sealed partial class ConditionalAccessOperation : Operation, IConditionalAccessOperation { internal ConditionalAccessOperation(IOperation operation, IOperation whenNotNull, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operation = SetParentOperation(operation, this); WhenNotNull = SetParentOperation(whenNotNull, this); Type = type; } public IOperation Operation { get; } public IOperation WhenNotNull { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, 1 when WhenNotNull != null => WhenNotNull, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: if (WhenNotNull != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ConditionalAccess; public override void Accept(OperationVisitor visitor) => visitor.VisitConditionalAccess(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConditionalAccess(this, argument); } internal sealed partial class ConditionalAccessInstanceOperation : Operation, IConditionalAccessInstanceOperation { internal ConditionalAccessInstanceOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ConditionalAccessInstance; public override void Accept(OperationVisitor visitor) => visitor.VisitConditionalAccessInstance(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConditionalAccessInstance(this, argument); } internal sealed partial class InterpolatedStringOperation : Operation, IInterpolatedStringOperation { internal InterpolatedStringOperation(ImmutableArray<IInterpolatedStringContentOperation> parts, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Parts = SetParentOperation(parts, this); OperationConstantValue = constantValue; Type = type; } public ImmutableArray<IInterpolatedStringContentOperation> Parts { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Parts.Length => Parts[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Parts.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Parts.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.InterpolatedString; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolatedString(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolatedString(this, argument); } internal sealed partial class AnonymousObjectCreationOperation : Operation, IAnonymousObjectCreationOperation { internal AnonymousObjectCreationOperation(ImmutableArray<IOperation> initializers, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Initializers = SetParentOperation(initializers, this); Type = type; } public ImmutableArray<IOperation> Initializers { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Initializers.Length => Initializers[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Initializers.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Initializers.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.AnonymousObjectCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitAnonymousObjectCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAnonymousObjectCreation(this, argument); } internal sealed partial class ObjectOrCollectionInitializerOperation : Operation, IObjectOrCollectionInitializerOperation { internal ObjectOrCollectionInitializerOperation(ImmutableArray<IOperation> initializers, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Initializers = SetParentOperation(initializers, this); Type = type; } public ImmutableArray<IOperation> Initializers { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Initializers.Length => Initializers[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Initializers.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Initializers.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ObjectOrCollectionInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitObjectOrCollectionInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitObjectOrCollectionInitializer(this, argument); } internal sealed partial class MemberInitializerOperation : Operation, IMemberInitializerOperation { internal MemberInitializerOperation(IOperation initializedMember, IObjectOrCollectionInitializerOperation initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { InitializedMember = SetParentOperation(initializedMember, this); Initializer = SetParentOperation(initializer, this); Type = type; } public IOperation InitializedMember { get; } public IObjectOrCollectionInitializerOperation Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when InitializedMember != null => InitializedMember, 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (InitializedMember != null) return (true, 0, 0); else goto case 0; case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.MemberInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitMemberInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitMemberInitializer(this, argument); } internal sealed partial class NameOfOperation : Operation, INameOfOperation { internal NameOfOperation(IOperation argument, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Argument = SetParentOperation(argument, this); OperationConstantValue = constantValue; Type = type; } public IOperation Argument { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Argument != null => Argument, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Argument != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.NameOf; public override void Accept(OperationVisitor visitor) => visitor.VisitNameOf(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitNameOf(this, argument); } internal sealed partial class TupleOperation : Operation, ITupleOperation { internal TupleOperation(ImmutableArray<IOperation> elements, ITypeSymbol? naturalType, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Elements = SetParentOperation(elements, this); NaturalType = naturalType; Type = type; } public ImmutableArray<IOperation> Elements { get; } public ITypeSymbol? NaturalType { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Elements.Length => Elements[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Elements.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Elements.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Tuple; public override void Accept(OperationVisitor visitor) => visitor.VisitTuple(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTuple(this, argument); } internal sealed partial class DynamicMemberReferenceOperation : Operation, IDynamicMemberReferenceOperation { internal DynamicMemberReferenceOperation(IOperation? instance, string memberName, ImmutableArray<ITypeSymbol> typeArguments, ITypeSymbol? containingType, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Instance = SetParentOperation(instance, this); MemberName = memberName; TypeArguments = typeArguments; ContainingType = containingType; Type = type; } public IOperation? Instance { get; } public string MemberName { get; } public ImmutableArray<ITypeSymbol> TypeArguments { get; } public ITypeSymbol? ContainingType { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Instance != null => Instance, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Instance != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DynamicMemberReference; public override void Accept(OperationVisitor visitor) => visitor.VisitDynamicMemberReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDynamicMemberReference(this, argument); } internal sealed partial class TranslatedQueryOperation : Operation, ITranslatedQueryOperation { internal TranslatedQueryOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operation = SetParentOperation(operation, this); Type = type; } public IOperation Operation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operation != null => Operation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operation != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TranslatedQuery; public override void Accept(OperationVisitor visitor) => visitor.VisitTranslatedQuery(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTranslatedQuery(this, argument); } internal sealed partial class DelegateCreationOperation : Operation, IDelegateCreationOperation { internal DelegateCreationOperation(IOperation target, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Target = SetParentOperation(target, this); Type = type; } public IOperation Target { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DelegateCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitDelegateCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDelegateCreation(this, argument); } internal sealed partial class DefaultValueOperation : Operation, IDefaultValueOperation { internal DefaultValueOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperationConstantValue = constantValue; Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.DefaultValue; public override void Accept(OperationVisitor visitor) => visitor.VisitDefaultValue(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDefaultValue(this, argument); } internal sealed partial class TypeOfOperation : Operation, ITypeOfOperation { internal TypeOfOperation(ITypeSymbol typeOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { TypeOperand = typeOperand; Type = type; } public ITypeSymbol TypeOperand { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TypeOf; public override void Accept(OperationVisitor visitor) => visitor.VisitTypeOf(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTypeOf(this, argument); } internal sealed partial class SizeOfOperation : Operation, ISizeOfOperation { internal SizeOfOperation(ITypeSymbol typeOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { TypeOperand = typeOperand; OperationConstantValue = constantValue; Type = type; } public ITypeSymbol TypeOperand { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.SizeOf; public override void Accept(OperationVisitor visitor) => visitor.VisitSizeOf(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSizeOf(this, argument); } internal sealed partial class AddressOfOperation : Operation, IAddressOfOperation { internal AddressOfOperation(IOperation reference, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Reference = SetParentOperation(reference, this); Type = type; } public IOperation Reference { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Reference != null => Reference, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Reference != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.AddressOf; public override void Accept(OperationVisitor visitor) => visitor.VisitAddressOf(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAddressOf(this, argument); } internal sealed partial class IsPatternOperation : Operation, IIsPatternOperation { internal IsPatternOperation(IOperation value, IPatternOperation pattern, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); Pattern = SetParentOperation(pattern, this); Type = type; } public IOperation Value { get; } public IPatternOperation Pattern { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when Pattern != null => Pattern, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (Pattern != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.IsPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitIsPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitIsPattern(this, argument); } internal sealed partial class IncrementOrDecrementOperation : Operation, IIncrementOrDecrementOperation { internal IncrementOrDecrementOperation(bool isPostfix, bool isLifted, bool isChecked, IOperation target, IMethodSymbol? operatorMethod, OperationKind kind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { IsPostfix = isPostfix; IsLifted = isLifted; IsChecked = isChecked; Target = SetParentOperation(target, this); OperatorMethod = operatorMethod; Type = type; Kind = kind; } public bool IsPostfix { get; } public bool IsLifted { get; } public bool IsChecked { get; } public IOperation Target { get; } public IMethodSymbol? OperatorMethod { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind { get; } public override void Accept(OperationVisitor visitor) => visitor.VisitIncrementOrDecrement(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitIncrementOrDecrement(this, argument); } internal sealed partial class ThrowOperation : Operation, IThrowOperation { internal ThrowOperation(IOperation? exception, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Exception = SetParentOperation(exception, this); Type = type; } public IOperation? Exception { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Exception != null => Exception, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Exception != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Throw; public override void Accept(OperationVisitor visitor) => visitor.VisitThrow(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitThrow(this, argument); } internal sealed partial class DeconstructionAssignmentOperation : BaseAssignmentOperation, IDeconstructionAssignmentOperation { internal DeconstructionAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(target, value, semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, 1 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: if (Value != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DeconstructionAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitDeconstructionAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDeconstructionAssignment(this, argument); } internal sealed partial class DeclarationExpressionOperation : Operation, IDeclarationExpressionOperation { internal DeclarationExpressionOperation(IOperation expression, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Expression = SetParentOperation(expression, this); Type = type; } public IOperation Expression { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Expression != null => Expression, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Expression != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DeclarationExpression; public override void Accept(OperationVisitor visitor) => visitor.VisitDeclarationExpression(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDeclarationExpression(this, argument); } internal sealed partial class OmittedArgumentOperation : Operation, IOmittedArgumentOperation { internal OmittedArgumentOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.OmittedArgument; public override void Accept(OperationVisitor visitor) => visitor.VisitOmittedArgument(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitOmittedArgument(this, argument); } internal abstract partial class BaseSymbolInitializerOperation : Operation, ISymbolInitializerOperation { protected BaseSymbolInitializerOperation(ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Locals = locals; Value = SetParentOperation(value, this); } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation Value { get; } } internal sealed partial class FieldInitializerOperation : BaseSymbolInitializerOperation, IFieldInitializerOperation { internal FieldInitializerOperation(ImmutableArray<IFieldSymbol> initializedFields, ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(locals, value, semanticModel, syntax, isImplicit) { InitializedFields = initializedFields; } public ImmutableArray<IFieldSymbol> InitializedFields { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.FieldInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitFieldInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFieldInitializer(this, argument); } internal sealed partial class VariableInitializerOperation : BaseSymbolInitializerOperation, IVariableInitializerOperation { internal VariableInitializerOperation(ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(locals, value, semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.VariableInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitVariableInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitVariableInitializer(this, argument); } internal sealed partial class PropertyInitializerOperation : BaseSymbolInitializerOperation, IPropertyInitializerOperation { internal PropertyInitializerOperation(ImmutableArray<IPropertySymbol> initializedProperties, ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(locals, value, semanticModel, syntax, isImplicit) { InitializedProperties = initializedProperties; } public ImmutableArray<IPropertySymbol> InitializedProperties { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.PropertyInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitPropertyInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPropertyInitializer(this, argument); } internal sealed partial class ParameterInitializerOperation : BaseSymbolInitializerOperation, IParameterInitializerOperation { internal ParameterInitializerOperation(IParameterSymbol parameter, ImmutableArray<ILocalSymbol> locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(locals, value, semanticModel, syntax, isImplicit) { Parameter = parameter; } public IParameterSymbol Parameter { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ParameterInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitParameterInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitParameterInitializer(this, argument); } internal sealed partial class ArrayInitializerOperation : Operation, IArrayInitializerOperation { internal ArrayInitializerOperation(ImmutableArray<IOperation> elementValues, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ElementValues = SetParentOperation(elementValues, this); } public ImmutableArray<IOperation> ElementValues { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < ElementValues.Length => ElementValues[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!ElementValues.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < ElementValues.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ArrayInitializer; public override void Accept(OperationVisitor visitor) => visitor.VisitArrayInitializer(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitArrayInitializer(this, argument); } internal sealed partial class VariableDeclaratorOperation : Operation, IVariableDeclaratorOperation { internal VariableDeclaratorOperation(ILocalSymbol symbol, IVariableInitializerOperation? initializer, ImmutableArray<IOperation> ignoredArguments, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Symbol = symbol; Initializer = SetParentOperation(initializer, this); IgnoredArguments = SetParentOperation(ignoredArguments, this); } public ILocalSymbol Symbol { get; } public IVariableInitializerOperation? Initializer { get; } public ImmutableArray<IOperation> IgnoredArguments { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < IgnoredArguments.Length => IgnoredArguments[index], 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!IgnoredArguments.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < IgnoredArguments.Length: return (true, 0, previousIndex + 1); case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.VariableDeclarator; public override void Accept(OperationVisitor visitor) => visitor.VisitVariableDeclarator(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitVariableDeclarator(this, argument); } internal sealed partial class VariableDeclarationOperation : Operation, IVariableDeclarationOperation { internal VariableDeclarationOperation(ImmutableArray<IVariableDeclaratorOperation> declarators, IVariableInitializerOperation? initializer, ImmutableArray<IOperation> ignoredDimensions, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Declarators = SetParentOperation(declarators, this); Initializer = SetParentOperation(initializer, this); IgnoredDimensions = SetParentOperation(ignoredDimensions, this); } public ImmutableArray<IVariableDeclaratorOperation> Declarators { get; } public IVariableInitializerOperation? Initializer { get; } public ImmutableArray<IOperation> IgnoredDimensions { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < IgnoredDimensions.Length => IgnoredDimensions[index], 1 when index < Declarators.Length => Declarators[index], 2 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!IgnoredDimensions.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < IgnoredDimensions.Length: return (true, 0, previousIndex + 1); case 0: if (!Declarators.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Declarators.Length: return (true, 1, previousIndex + 1); case 1: if (Initializer != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.VariableDeclaration; public override void Accept(OperationVisitor visitor) => visitor.VisitVariableDeclaration(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitVariableDeclaration(this, argument); } internal sealed partial class ArgumentOperation : Operation, IArgumentOperation { internal ArgumentOperation(ArgumentKind argumentKind, IParameterSymbol? parameter, IOperation value, IConvertibleConversion inConversion, IConvertibleConversion outConversion, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ArgumentKind = argumentKind; Parameter = parameter; Value = SetParentOperation(value, this); InConversionConvertible = inConversion; OutConversionConvertible = outConversion; } public ArgumentKind ArgumentKind { get; } public IParameterSymbol? Parameter { get; } public IOperation Value { get; } internal IConvertibleConversion InConversionConvertible { get; } public CommonConversion InConversion => InConversionConvertible.ToCommonConversion(); internal IConvertibleConversion OutConversionConvertible { get; } public CommonConversion OutConversion => OutConversionConvertible.ToCommonConversion(); protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Argument; public override void Accept(OperationVisitor visitor) => visitor.VisitArgument(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitArgument(this, argument); } internal sealed partial class CatchClauseOperation : Operation, ICatchClauseOperation { internal CatchClauseOperation(IOperation? exceptionDeclarationOrExpression, ITypeSymbol exceptionType, ImmutableArray<ILocalSymbol> locals, IOperation? filter, IBlockOperation handler, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ExceptionDeclarationOrExpression = SetParentOperation(exceptionDeclarationOrExpression, this); ExceptionType = exceptionType; Locals = locals; Filter = SetParentOperation(filter, this); Handler = SetParentOperation(handler, this); } public IOperation? ExceptionDeclarationOrExpression { get; } public ITypeSymbol ExceptionType { get; } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation? Filter { get; } public IBlockOperation Handler { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when ExceptionDeclarationOrExpression != null => ExceptionDeclarationOrExpression, 1 when Filter != null => Filter, 2 when Handler != null => Handler, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (ExceptionDeclarationOrExpression != null) return (true, 0, 0); else goto case 0; case 0: if (Filter != null) return (true, 1, 0); else goto case 1; case 1: if (Handler != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CatchClause; public override void Accept(OperationVisitor visitor) => visitor.VisitCatchClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCatchClause(this, argument); } internal sealed partial class SwitchCaseOperation : Operation, ISwitchCaseOperation { internal SwitchCaseOperation(ImmutableArray<ICaseClauseOperation> clauses, ImmutableArray<IOperation> body, ImmutableArray<ILocalSymbol> locals, IOperation? condition, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Clauses = SetParentOperation(clauses, this); Body = SetParentOperation(body, this); Locals = locals; Condition = SetParentOperation(condition, this); } public ImmutableArray<ICaseClauseOperation> Clauses { get; } public ImmutableArray<IOperation> Body { get; } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation? Condition { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Clauses.Length => Clauses[index], 1 when index < Body.Length => Body[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Clauses.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Clauses.Length: return (true, 0, previousIndex + 1); case 0: if (!Body.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Body.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.SwitchCase; public override void Accept(OperationVisitor visitor) => visitor.VisitSwitchCase(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSwitchCase(this, argument); } internal abstract partial class BaseCaseClauseOperation : Operation, ICaseClauseOperation { protected BaseCaseClauseOperation(ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Label = label; } public abstract CaseKind CaseKind { get; } public ILabelSymbol? Label { get; } } internal sealed partial class DefaultCaseClauseOperation : BaseCaseClauseOperation, IDefaultCaseClauseOperation { internal DefaultCaseClauseOperation(ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitDefaultCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDefaultCaseClause(this, argument); } internal sealed partial class PatternCaseClauseOperation : BaseCaseClauseOperation, IPatternCaseClauseOperation { internal PatternCaseClauseOperation(ILabelSymbol label, IPatternOperation pattern, IOperation? guard, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { Pattern = SetParentOperation(pattern, this); Guard = SetParentOperation(guard, this); } public new ILabelSymbol Label => base.Label!; public IPatternOperation Pattern { get; } public IOperation? Guard { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Pattern != null => Pattern, 1 when Guard != null => Guard, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Pattern != null) return (true, 0, 0); else goto case 0; case 0: if (Guard != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitPatternCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPatternCaseClause(this, argument); } internal sealed partial class RangeCaseClauseOperation : BaseCaseClauseOperation, IRangeCaseClauseOperation { internal RangeCaseClauseOperation(IOperation minimumValue, IOperation maximumValue, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { MinimumValue = SetParentOperation(minimumValue, this); MaximumValue = SetParentOperation(maximumValue, this); } public IOperation MinimumValue { get; } public IOperation MaximumValue { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when MinimumValue != null => MinimumValue, 1 when MaximumValue != null => MaximumValue, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (MinimumValue != null) return (true, 0, 0); else goto case 0; case 0: if (MaximumValue != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitRangeCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRangeCaseClause(this, argument); } internal sealed partial class RelationalCaseClauseOperation : BaseCaseClauseOperation, IRelationalCaseClauseOperation { internal RelationalCaseClauseOperation(IOperation value, BinaryOperatorKind relation, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); Relation = relation; } public IOperation Value { get; } public BinaryOperatorKind Relation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitRelationalCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRelationalCaseClause(this, argument); } internal sealed partial class SingleValueCaseClauseOperation : BaseCaseClauseOperation, ISingleValueCaseClauseOperation { internal SingleValueCaseClauseOperation(IOperation value, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(label, semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaseClause; public override void Accept(OperationVisitor visitor) => visitor.VisitSingleValueCaseClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSingleValueCaseClause(this, argument); } internal abstract partial class BaseInterpolatedStringContentOperation : Operation, IInterpolatedStringContentOperation { protected BaseInterpolatedStringContentOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { } } internal sealed partial class InterpolatedStringTextOperation : BaseInterpolatedStringContentOperation, IInterpolatedStringTextOperation { internal InterpolatedStringTextOperation(IOperation text, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Text = SetParentOperation(text, this); } public IOperation Text { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Text != null => Text, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Text != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.InterpolatedStringText; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolatedStringText(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolatedStringText(this, argument); } internal sealed partial class InterpolationOperation : BaseInterpolatedStringContentOperation, IInterpolationOperation { internal InterpolationOperation(IOperation expression, IOperation? alignment, IOperation? formatString, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Expression = SetParentOperation(expression, this); Alignment = SetParentOperation(alignment, this); FormatString = SetParentOperation(formatString, this); } public IOperation Expression { get; } public IOperation? Alignment { get; } public IOperation? FormatString { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Expression != null => Expression, 1 when Alignment != null => Alignment, 2 when FormatString != null => FormatString, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Expression != null) return (true, 0, 0); else goto case 0; case 0: if (Alignment != null) return (true, 1, 0); else goto case 1; case 1: if (FormatString != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Interpolation; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolation(this, argument); } internal abstract partial class BasePatternOperation : Operation, IPatternOperation { protected BasePatternOperation(ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { InputType = inputType; NarrowedType = narrowedType; } public ITypeSymbol InputType { get; } public ITypeSymbol NarrowedType { get; } } internal sealed partial class ConstantPatternOperation : BasePatternOperation, IConstantPatternOperation { internal ConstantPatternOperation(IOperation value, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ConstantPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitConstantPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConstantPattern(this, argument); } internal sealed partial class DeclarationPatternOperation : BasePatternOperation, IDeclarationPatternOperation { internal DeclarationPatternOperation(ITypeSymbol? matchedType, bool matchesNull, ISymbol? declaredSymbol, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { MatchedType = matchedType; MatchesNull = matchesNull; DeclaredSymbol = declaredSymbol; } public ITypeSymbol? MatchedType { get; } public bool MatchesNull { get; } public ISymbol? DeclaredSymbol { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DeclarationPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitDeclarationPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDeclarationPattern(this, argument); } internal sealed partial class TupleBinaryOperation : Operation, ITupleBinaryOperation { internal TupleBinaryOperation(BinaryOperatorKind operatorKind, IOperation leftOperand, IOperation rightOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; LeftOperand = SetParentOperation(leftOperand, this); RightOperand = SetParentOperation(rightOperand, this); Type = type; } public BinaryOperatorKind OperatorKind { get; } public IOperation LeftOperand { get; } public IOperation RightOperand { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LeftOperand != null => LeftOperand, 1 when RightOperand != null => RightOperand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LeftOperand != null) return (true, 0, 0); else goto case 0; case 0: if (RightOperand != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TupleBinary; public override void Accept(OperationVisitor visitor) => visitor.VisitTupleBinaryOperator(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTupleBinaryOperator(this, argument); } internal abstract partial class BaseMethodBodyBaseOperation : Operation, IMethodBodyBaseOperation { protected BaseMethodBodyBaseOperation(IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { BlockBody = SetParentOperation(blockBody, this); ExpressionBody = SetParentOperation(expressionBody, this); } public IBlockOperation? BlockBody { get; } public IBlockOperation? ExpressionBody { get; } } internal sealed partial class MethodBodyOperation : BaseMethodBodyBaseOperation, IMethodBodyOperation { internal MethodBodyOperation(IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(blockBody, expressionBody, semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when BlockBody != null => BlockBody, 1 when ExpressionBody != null => ExpressionBody, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (BlockBody != null) return (true, 0, 0); else goto case 0; case 0: if (ExpressionBody != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.MethodBody; public override void Accept(OperationVisitor visitor) => visitor.VisitMethodBodyOperation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitMethodBodyOperation(this, argument); } internal sealed partial class ConstructorBodyOperation : BaseMethodBodyBaseOperation, IConstructorBodyOperation { internal ConstructorBodyOperation(ImmutableArray<ILocalSymbol> locals, IOperation? initializer, IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(blockBody, expressionBody, semanticModel, syntax, isImplicit) { Locals = locals; Initializer = SetParentOperation(initializer, this); } public ImmutableArray<ILocalSymbol> Locals { get; } public IOperation? Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Initializer != null => Initializer, 1 when BlockBody != null => BlockBody, 2 when ExpressionBody != null => ExpressionBody, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Initializer != null) return (true, 0, 0); else goto case 0; case 0: if (BlockBody != null) return (true, 1, 0); else goto case 1; case 1: if (ExpressionBody != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ConstructorBody; public override void Accept(OperationVisitor visitor) => visitor.VisitConstructorBodyOperation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitConstructorBodyOperation(this, argument); } internal sealed partial class DiscardOperation : Operation, IDiscardOperation { internal DiscardOperation(IDiscardSymbol discardSymbol, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { DiscardSymbol = discardSymbol; Type = type; } public IDiscardSymbol DiscardSymbol { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Discard; public override void Accept(OperationVisitor visitor) => visitor.VisitDiscardOperation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDiscardOperation(this, argument); } internal sealed partial class FlowCaptureOperation : Operation, IFlowCaptureOperation { internal FlowCaptureOperation(CaptureId id, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Id = id; Value = SetParentOperation(value, this); } public CaptureId Id { get; } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.FlowCapture; public override void Accept(OperationVisitor visitor) => visitor.VisitFlowCapture(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFlowCapture(this, argument); } internal sealed partial class FlowCaptureReferenceOperation : Operation, IFlowCaptureReferenceOperation { internal FlowCaptureReferenceOperation(CaptureId id, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Id = id; OperationConstantValue = constantValue; Type = type; } public CaptureId Id { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.FlowCaptureReference; public override void Accept(OperationVisitor visitor) => visitor.VisitFlowCaptureReference(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFlowCaptureReference(this, argument); } internal sealed partial class IsNullOperation : Operation, IIsNullOperation { internal IsNullOperation(IOperation operand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); OperationConstantValue = constantValue; Type = type; } public IOperation Operand { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue { get; } public override OperationKind Kind => OperationKind.IsNull; public override void Accept(OperationVisitor visitor) => visitor.VisitIsNull(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitIsNull(this, argument); } internal sealed partial class CaughtExceptionOperation : Operation, ICaughtExceptionOperation { internal CaughtExceptionOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CaughtException; public override void Accept(OperationVisitor visitor) => visitor.VisitCaughtException(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCaughtException(this, argument); } internal sealed partial class StaticLocalInitializationSemaphoreOperation : Operation, IStaticLocalInitializationSemaphoreOperation { internal StaticLocalInitializationSemaphoreOperation(ILocalSymbol local, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Local = local; Type = type; } public ILocalSymbol Local { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.StaticLocalInitializationSemaphore; public override void Accept(OperationVisitor visitor) => visitor.VisitStaticLocalInitializationSemaphore(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitStaticLocalInitializationSemaphore(this, argument); } internal sealed partial class CoalesceAssignmentOperation : BaseAssignmentOperation, ICoalesceAssignmentOperation { internal CoalesceAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(target, value, semanticModel, syntax, isImplicit) { Type = type; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Target != null => Target, 1 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Target != null) return (true, 0, 0); else goto case 0; case 0: if (Value != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.CoalesceAssignment; public override void Accept(OperationVisitor visitor) => visitor.VisitCoalesceAssignment(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitCoalesceAssignment(this, argument); } internal sealed partial class RangeOperation : Operation, IRangeOperation { internal RangeOperation(IOperation? leftOperand, IOperation? rightOperand, bool isLifted, IMethodSymbol? method, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { LeftOperand = SetParentOperation(leftOperand, this); RightOperand = SetParentOperation(rightOperand, this); IsLifted = isLifted; Method = method; Type = type; } public IOperation? LeftOperand { get; } public IOperation? RightOperand { get; } public bool IsLifted { get; } public IMethodSymbol? Method { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LeftOperand != null => LeftOperand, 1 when RightOperand != null => RightOperand, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LeftOperand != null) return (true, 0, 0); else goto case 0; case 0: if (RightOperand != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.Range; public override void Accept(OperationVisitor visitor) => visitor.VisitRangeOperation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRangeOperation(this, argument); } internal sealed partial class ReDimOperation : Operation, IReDimOperation { internal ReDimOperation(ImmutableArray<IReDimClauseOperation> clauses, bool preserve, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Clauses = SetParentOperation(clauses, this); Preserve = preserve; } public ImmutableArray<IReDimClauseOperation> Clauses { get; } public bool Preserve { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < Clauses.Length => Clauses[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!Clauses.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < Clauses.Length: return (true, 0, previousIndex + 1); case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ReDim; public override void Accept(OperationVisitor visitor) => visitor.VisitReDim(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitReDim(this, argument); } internal sealed partial class ReDimClauseOperation : Operation, IReDimClauseOperation { internal ReDimClauseOperation(IOperation operand, ImmutableArray<IOperation> dimensionSizes, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); DimensionSizes = SetParentOperation(dimensionSizes, this); } public IOperation Operand { get; } public ImmutableArray<IOperation> DimensionSizes { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, 1 when index < DimensionSizes.Length => DimensionSizes[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: if (!DimensionSizes.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < DimensionSizes.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.ReDimClause; public override void Accept(OperationVisitor visitor) => visitor.VisitReDimClause(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitReDimClause(this, argument); } internal sealed partial class RecursivePatternOperation : BasePatternOperation, IRecursivePatternOperation { internal RecursivePatternOperation(ITypeSymbol matchedType, ISymbol? deconstructSymbol, ImmutableArray<IPatternOperation> deconstructionSubpatterns, ImmutableArray<IPropertySubpatternOperation> propertySubpatterns, ISymbol? declaredSymbol, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { MatchedType = matchedType; DeconstructSymbol = deconstructSymbol; DeconstructionSubpatterns = SetParentOperation(deconstructionSubpatterns, this); PropertySubpatterns = SetParentOperation(propertySubpatterns, this); DeclaredSymbol = declaredSymbol; } public ITypeSymbol MatchedType { get; } public ISymbol? DeconstructSymbol { get; } public ImmutableArray<IPatternOperation> DeconstructionSubpatterns { get; } public ImmutableArray<IPropertySubpatternOperation> PropertySubpatterns { get; } public ISymbol? DeclaredSymbol { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when index < DeconstructionSubpatterns.Length => DeconstructionSubpatterns[index], 1 when index < PropertySubpatterns.Length => PropertySubpatterns[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (!DeconstructionSubpatterns.IsEmpty) return (true, 0, 0); else goto case 0; case 0 when previousIndex + 1 < DeconstructionSubpatterns.Length: return (true, 0, previousIndex + 1); case 0: if (!PropertySubpatterns.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < PropertySubpatterns.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.RecursivePattern; public override void Accept(OperationVisitor visitor) => visitor.VisitRecursivePattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRecursivePattern(this, argument); } internal sealed partial class DiscardPatternOperation : BasePatternOperation, IDiscardPatternOperation { internal DiscardPatternOperation(ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.DiscardPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitDiscardPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitDiscardPattern(this, argument); } internal sealed partial class SwitchExpressionOperation : Operation, ISwitchExpressionOperation { internal SwitchExpressionOperation(IOperation value, ImmutableArray<ISwitchExpressionArmOperation> arms, bool isExhaustive, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Value = SetParentOperation(value, this); Arms = SetParentOperation(arms, this); IsExhaustive = isExhaustive; Type = type; } public IOperation Value { get; } public ImmutableArray<ISwitchExpressionArmOperation> Arms { get; } public bool IsExhaustive { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when index < Arms.Length => Arms[index], _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (!Arms.IsEmpty) return (true, 1, 0); else goto case 1; case 1 when previousIndex + 1 < Arms.Length: return (true, 1, previousIndex + 1); case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.SwitchExpression; public override void Accept(OperationVisitor visitor) => visitor.VisitSwitchExpression(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSwitchExpression(this, argument); } internal sealed partial class SwitchExpressionArmOperation : Operation, ISwitchExpressionArmOperation { internal SwitchExpressionArmOperation(IPatternOperation pattern, IOperation? guard, IOperation value, ImmutableArray<ILocalSymbol> locals, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Pattern = SetParentOperation(pattern, this); Guard = SetParentOperation(guard, this); Value = SetParentOperation(value, this); Locals = locals; } public IPatternOperation Pattern { get; } public IOperation? Guard { get; } public IOperation Value { get; } public ImmutableArray<ILocalSymbol> Locals { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Pattern != null => Pattern, 1 when Guard != null => Guard, 2 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Pattern != null) return (true, 0, 0); else goto case 0; case 0: if (Guard != null) return (true, 1, 0); else goto case 1; case 1: if (Value != null) return (true, 2, 0); else goto case 2; case 2: case 3: return (false, 3, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.SwitchExpressionArm; public override void Accept(OperationVisitor visitor) => visitor.VisitSwitchExpressionArm(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitSwitchExpressionArm(this, argument); } internal sealed partial class PropertySubpatternOperation : Operation, IPropertySubpatternOperation { internal PropertySubpatternOperation(IOperation member, IPatternOperation pattern, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Member = SetParentOperation(member, this); Pattern = SetParentOperation(pattern, this); } public IOperation Member { get; } public IPatternOperation Pattern { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Member != null => Member, 1 when Pattern != null => Pattern, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Member != null) return (true, 0, 0); else goto case 0; case 0: if (Pattern != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.PropertySubpattern; public override void Accept(OperationVisitor visitor) => visitor.VisitPropertySubpattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPropertySubpattern(this, argument); } internal sealed partial class AggregateQueryOperation : Operation, IAggregateQueryOperation { internal AggregateQueryOperation(IOperation group, IOperation aggregation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Group = SetParentOperation(group, this); Aggregation = SetParentOperation(aggregation, this); Type = type; } public IOperation Group { get; } public IOperation Aggregation { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Group != null => Group, 1 when Aggregation != null => Aggregation, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Group != null) return (true, 0, 0); else goto case 0; case 0: if (Aggregation != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitAggregateQuery(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitAggregateQuery(this, argument); } internal sealed partial class FixedOperation : Operation, IFixedOperation { internal FixedOperation(ImmutableArray<ILocalSymbol> locals, IVariableDeclarationGroupOperation variables, IOperation body, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Locals = locals; Variables = SetParentOperation(variables, this); Body = SetParentOperation(body, this); } public ImmutableArray<ILocalSymbol> Locals { get; } public IVariableDeclarationGroupOperation Variables { get; } public IOperation Body { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Variables != null => Variables, 1 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Variables != null) return (true, 0, 0); else goto case 0; case 0: if (Body != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitFixed(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitFixed(this, argument); } internal sealed partial class NoPiaObjectCreationOperation : Operation, INoPiaObjectCreationOperation { internal NoPiaObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Initializer = SetParentOperation(initializer, this); Type = type; } public IObjectOrCollectionInitializerOperation? Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Initializer != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitNoPiaObjectCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitNoPiaObjectCreation(this, argument); } internal sealed partial class PlaceholderOperation : Operation, IPlaceholderOperation { internal PlaceholderOperation(PlaceholderKind placeholderKind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { PlaceholderKind = placeholderKind; Type = type; } public PlaceholderKind PlaceholderKind { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitPlaceholder(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitPlaceholder(this, argument); } internal sealed partial class WithStatementOperation : Operation, IWithStatementOperation { internal WithStatementOperation(IOperation body, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Body = SetParentOperation(body, this); Value = SetParentOperation(value, this); } public IOperation Body { get; } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, 1 when Body != null => Body, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: if (Body != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.None; public override void Accept(OperationVisitor visitor) => visitor.VisitWithStatement(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitWithStatement(this, argument); } internal sealed partial class UsingDeclarationOperation : Operation, IUsingDeclarationOperation { internal UsingDeclarationOperation(IVariableDeclarationGroupOperation declarationGroup, bool isAsynchronous, DisposeOperationInfo disposeInfo, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { DeclarationGroup = SetParentOperation(declarationGroup, this); IsAsynchronous = isAsynchronous; DisposeInfo = disposeInfo; } public IVariableDeclarationGroupOperation DeclarationGroup { get; } public bool IsAsynchronous { get; } public DisposeOperationInfo DisposeInfo { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when DeclarationGroup != null => DeclarationGroup, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (DeclarationGroup != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.UsingDeclaration; public override void Accept(OperationVisitor visitor) => visitor.VisitUsingDeclaration(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitUsingDeclaration(this, argument); } internal sealed partial class NegatedPatternOperation : BasePatternOperation, INegatedPatternOperation { internal NegatedPatternOperation(IPatternOperation pattern, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { Pattern = SetParentOperation(pattern, this); } public IPatternOperation Pattern { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Pattern != null => Pattern, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Pattern != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.NegatedPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitNegatedPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitNegatedPattern(this, argument); } internal sealed partial class BinaryPatternOperation : BasePatternOperation, IBinaryPatternOperation { internal BinaryPatternOperation(BinaryOperatorKind operatorKind, IPatternOperation leftPattern, IPatternOperation rightPattern, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; LeftPattern = SetParentOperation(leftPattern, this); RightPattern = SetParentOperation(rightPattern, this); } public BinaryOperatorKind OperatorKind { get; } public IPatternOperation LeftPattern { get; } public IPatternOperation RightPattern { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when LeftPattern != null => LeftPattern, 1 when RightPattern != null => RightPattern, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (LeftPattern != null) return (true, 0, 0); else goto case 0; case 0: if (RightPattern != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.BinaryPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitBinaryPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitBinaryPattern(this, argument); } internal sealed partial class TypePatternOperation : BasePatternOperation, ITypePatternOperation { internal TypePatternOperation(ITypeSymbol matchedType, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { MatchedType = matchedType; } public ITypeSymbol MatchedType { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.TypePattern; public override void Accept(OperationVisitor visitor) => visitor.VisitTypePattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitTypePattern(this, argument); } internal sealed partial class RelationalPatternOperation : BasePatternOperation, IRelationalPatternOperation { internal RelationalPatternOperation(BinaryOperatorKind operatorKind, IOperation value, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(inputType, narrowedType, semanticModel, syntax, isImplicit) { OperatorKind = operatorKind; Value = SetParentOperation(value, this); } public BinaryOperatorKind OperatorKind { get; } public IOperation Value { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Value != null => Value, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Value != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.RelationalPattern; public override void Accept(OperationVisitor visitor) => visitor.VisitRelationalPattern(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitRelationalPattern(this, argument); } internal sealed partial class WithOperation : Operation, IWithOperation { internal WithOperation(IOperation operand, IMethodSymbol? cloneMethod, IObjectOrCollectionInitializerOperation initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Operand = SetParentOperation(operand, this); CloneMethod = cloneMethod; Initializer = SetParentOperation(initializer, this); Type = type; } public IOperation Operand { get; } public IMethodSymbol? CloneMethod { get; } public IObjectOrCollectionInitializerOperation Initializer { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Operand != null => Operand, 1 when Initializer != null => Initializer, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Operand != null) return (true, 0, 0); else goto case 0; case 0: if (Initializer != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.With; public override void Accept(OperationVisitor visitor) => visitor.VisitWith(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitWith(this, argument); } internal sealed partial class InterpolatedStringHandlerCreationOperation : Operation, IInterpolatedStringHandlerCreationOperation { internal InterpolatedStringHandlerCreationOperation(IOperation handlerCreation, bool handlerCreationHasSuccessParameter, bool handlerAppendCallsReturnBool, IOperation content, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) : base(semanticModel, syntax, isImplicit) { HandlerCreation = SetParentOperation(handlerCreation, this); HandlerCreationHasSuccessParameter = handlerCreationHasSuccessParameter; HandlerAppendCallsReturnBool = handlerAppendCallsReturnBool; Content = SetParentOperation(content, this); Type = type; } public IOperation HandlerCreation { get; } public bool HandlerCreationHasSuccessParameter { get; } public bool HandlerAppendCallsReturnBool { get; } public IOperation Content { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when HandlerCreation != null => HandlerCreation, 1 when Content != null => Content, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (HandlerCreation != null) return (true, 0, 0); else goto case 0; case 0: if (Content != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type { get; } internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.InterpolatedStringHandlerCreation; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolatedStringHandlerCreation(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolatedStringHandlerCreation(this, argument); } internal sealed partial class InterpolatedStringAdditionOperation : Operation, IInterpolatedStringAdditionOperation { internal InterpolatedStringAdditionOperation(IOperation left, IOperation right, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { Left = SetParentOperation(left, this); Right = SetParentOperation(right, this); } public IOperation Left { get; } public IOperation Right { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when Left != null => Left, 1 when Right != null => Right, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (Left != null) return (true, 0, 0); else goto case 0; case 0: if (Right != null) return (true, 1, 0); else goto case 1; case 1: case 2: return (false, 2, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.InterpolatedStringAddition; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolatedStringAddition(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolatedStringAddition(this, argument); } internal sealed partial class InterpolatedStringAppendOperation : BaseInterpolatedStringContentOperation, IInterpolatedStringAppendOperation { internal InterpolatedStringAppendOperation(IOperation appendCall, OperationKind kind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { AppendCall = SetParentOperation(appendCall, this); Kind = kind; } public IOperation AppendCall { get; } protected override IOperation GetCurrent(int slot, int index) => slot switch { 0 when AppendCall != null => AppendCall, _ => throw ExceptionUtilities.UnexpectedValue((slot, index)), }; protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) { switch (previousSlot) { case -1: if (AppendCall != null) return (true, 0, 0); else goto case 0; case 0: case 1: return (false, 1, 0); default: throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); } } public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind { get; } public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolatedStringAppend(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolatedStringAppend(this, argument); } internal sealed partial class InterpolatedStringHandlerArgumentPlaceholderOperation : Operation, IInterpolatedStringHandlerArgumentPlaceholderOperation { internal InterpolatedStringHandlerArgumentPlaceholderOperation(int argumentIndex, InterpolatedStringArgumentPlaceholderKind placeholderKind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) : base(semanticModel, syntax, isImplicit) { ArgumentIndex = argumentIndex; PlaceholderKind = placeholderKind; } public int ArgumentIndex { get; } public InterpolatedStringArgumentPlaceholderKind PlaceholderKind { get; } protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index)); protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue); public override ITypeSymbol? Type => null; internal override ConstantValue? OperationConstantValue => null; public override OperationKind Kind => OperationKind.InterpolatedStringHandlerArgumentPlaceholder; public override void Accept(OperationVisitor visitor) => visitor.VisitInterpolatedStringHandlerArgumentPlaceholder(this); public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default => visitor.VisitInterpolatedStringHandlerArgumentPlaceholder(this, argument); } #endregion #region Cloner internal sealed partial class OperationCloner : OperationVisitor<object?, IOperation> { private static readonly OperationCloner s_instance = new OperationCloner(); /// <summary>Deep clone given IOperation</summary> public static T CloneOperation<T>(T operation) where T : IOperation => s_instance.Visit(operation); public OperationCloner() { } [return: NotNullIfNotNull("node")] private T? Visit<T>(T? node) where T : IOperation? => (T?)Visit(node, argument: null); public override IOperation DefaultVisit(IOperation operation, object? argument) => throw ExceptionUtilities.Unreachable; private ImmutableArray<T> VisitArray<T>(ImmutableArray<T> nodes) where T : IOperation => nodes.SelectAsArray((n, @this) => @this.Visit(n), this)!; private ImmutableArray<(ISymbol, T)> VisitArray<T>(ImmutableArray<(ISymbol, T)> nodes) where T : IOperation => nodes.SelectAsArray((n, @this) => (n.Item1, @this.Visit(n.Item2)), this)!; public override IOperation VisitBlock(IBlockOperation operation, object? argument) { var internalOperation = (BlockOperation)operation; return new BlockOperation(VisitArray(internalOperation.Operations), internalOperation.Locals, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, object? argument) { var internalOperation = (VariableDeclarationGroupOperation)operation; return new VariableDeclarationGroupOperation(VisitArray(internalOperation.Declarations), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitSwitch(ISwitchOperation operation, object? argument) { var internalOperation = (SwitchOperation)operation; return new SwitchOperation(internalOperation.Locals, Visit(internalOperation.Value), VisitArray(internalOperation.Cases), internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitForEachLoop(IForEachLoopOperation operation, object? argument) { var internalOperation = (ForEachLoopOperation)operation; return new ForEachLoopOperation(Visit(internalOperation.LoopControlVariable), Visit(internalOperation.Collection), VisitArray(internalOperation.NextVariables), internalOperation.Info, internalOperation.IsAsynchronous, Visit(internalOperation.Body), internalOperation.Locals, internalOperation.ContinueLabel, internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitForLoop(IForLoopOperation operation, object? argument) { var internalOperation = (ForLoopOperation)operation; return new ForLoopOperation(VisitArray(internalOperation.Before), internalOperation.ConditionLocals, Visit(internalOperation.Condition), VisitArray(internalOperation.AtLoopBottom), Visit(internalOperation.Body), internalOperation.Locals, internalOperation.ContinueLabel, internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitForToLoop(IForToLoopOperation operation, object? argument) { var internalOperation = (ForToLoopOperation)operation; return new ForToLoopOperation(Visit(internalOperation.LoopControlVariable), Visit(internalOperation.InitialValue), Visit(internalOperation.LimitValue), Visit(internalOperation.StepValue), internalOperation.IsChecked, VisitArray(internalOperation.NextVariables), internalOperation.Info, Visit(internalOperation.Body), internalOperation.Locals, internalOperation.ContinueLabel, internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitWhileLoop(IWhileLoopOperation operation, object? argument) { var internalOperation = (WhileLoopOperation)operation; return new WhileLoopOperation(Visit(internalOperation.Condition), internalOperation.ConditionIsTop, internalOperation.ConditionIsUntil, Visit(internalOperation.IgnoredCondition), Visit(internalOperation.Body), internalOperation.Locals, internalOperation.ContinueLabel, internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitLabeled(ILabeledOperation operation, object? argument) { var internalOperation = (LabeledOperation)operation; return new LabeledOperation(internalOperation.Label, Visit(internalOperation.Operation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitBranch(IBranchOperation operation, object? argument) { var internalOperation = (BranchOperation)operation; return new BranchOperation(internalOperation.Target, internalOperation.BranchKind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitEmpty(IEmptyOperation operation, object? argument) { var internalOperation = (EmptyOperation)operation; return new EmptyOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitReturn(IReturnOperation operation, object? argument) { var internalOperation = (ReturnOperation)operation; return new ReturnOperation(Visit(internalOperation.ReturnedValue), internalOperation.Kind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitLock(ILockOperation operation, object? argument) { var internalOperation = (LockOperation)operation; return new LockOperation(Visit(internalOperation.LockedValue), Visit(internalOperation.Body), internalOperation.LockTakenSymbol, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitTry(ITryOperation operation, object? argument) { var internalOperation = (TryOperation)operation; return new TryOperation(Visit(internalOperation.Body), VisitArray(internalOperation.Catches), Visit(internalOperation.Finally), internalOperation.ExitLabel, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitUsing(IUsingOperation operation, object? argument) { var internalOperation = (UsingOperation)operation; return new UsingOperation(Visit(internalOperation.Resources), Visit(internalOperation.Body), internalOperation.Locals, internalOperation.IsAsynchronous, internalOperation.DisposeInfo, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitExpressionStatement(IExpressionStatementOperation operation, object? argument) { var internalOperation = (ExpressionStatementOperation)operation; return new ExpressionStatementOperation(Visit(internalOperation.Operation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitLocalFunction(ILocalFunctionOperation operation, object? argument) { var internalOperation = (LocalFunctionOperation)operation; return new LocalFunctionOperation(internalOperation.Symbol, Visit(internalOperation.Body), Visit(internalOperation.IgnoredBody), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitStop(IStopOperation operation, object? argument) { var internalOperation = (StopOperation)operation; return new StopOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitEnd(IEndOperation operation, object? argument) { var internalOperation = (EndOperation)operation; return new EndOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRaiseEvent(IRaiseEventOperation operation, object? argument) { var internalOperation = (RaiseEventOperation)operation; return new RaiseEventOperation(Visit(internalOperation.EventReference), VisitArray(internalOperation.Arguments), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitLiteral(ILiteralOperation operation, object? argument) { var internalOperation = (LiteralOperation)operation; return new LiteralOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitConversion(IConversionOperation operation, object? argument) { var internalOperation = (ConversionOperation)operation; return new ConversionOperation(Visit(internalOperation.Operand), internalOperation.ConversionConvertible, internalOperation.IsTryCast, internalOperation.IsChecked, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitInvocation(IInvocationOperation operation, object? argument) { var internalOperation = (InvocationOperation)operation; return new InvocationOperation(internalOperation.TargetMethod, Visit(internalOperation.Instance), internalOperation.IsVirtual, VisitArray(internalOperation.Arguments), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitArrayElementReference(IArrayElementReferenceOperation operation, object? argument) { var internalOperation = (ArrayElementReferenceOperation)operation; return new ArrayElementReferenceOperation(Visit(internalOperation.ArrayReference), VisitArray(internalOperation.Indices), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitLocalReference(ILocalReferenceOperation operation, object? argument) { var internalOperation = (LocalReferenceOperation)operation; return new LocalReferenceOperation(internalOperation.Local, internalOperation.IsDeclaration, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitParameterReference(IParameterReferenceOperation operation, object? argument) { var internalOperation = (ParameterReferenceOperation)operation; return new ParameterReferenceOperation(internalOperation.Parameter, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitFieldReference(IFieldReferenceOperation operation, object? argument) { var internalOperation = (FieldReferenceOperation)operation; return new FieldReferenceOperation(internalOperation.Field, internalOperation.IsDeclaration, Visit(internalOperation.Instance), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitMethodReference(IMethodReferenceOperation operation, object? argument) { var internalOperation = (MethodReferenceOperation)operation; return new MethodReferenceOperation(internalOperation.Method, internalOperation.IsVirtual, Visit(internalOperation.Instance), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitPropertyReference(IPropertyReferenceOperation operation, object? argument) { var internalOperation = (PropertyReferenceOperation)operation; return new PropertyReferenceOperation(internalOperation.Property, VisitArray(internalOperation.Arguments), Visit(internalOperation.Instance), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitEventReference(IEventReferenceOperation operation, object? argument) { var internalOperation = (EventReferenceOperation)operation; return new EventReferenceOperation(internalOperation.Event, Visit(internalOperation.Instance), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitUnaryOperator(IUnaryOperation operation, object? argument) { var internalOperation = (UnaryOperation)operation; return new UnaryOperation(internalOperation.OperatorKind, Visit(internalOperation.Operand), internalOperation.IsLifted, internalOperation.IsChecked, internalOperation.OperatorMethod, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitBinaryOperator(IBinaryOperation operation, object? argument) { var internalOperation = (BinaryOperation)operation; return new BinaryOperation(internalOperation.OperatorKind, Visit(internalOperation.LeftOperand), Visit(internalOperation.RightOperand), internalOperation.IsLifted, internalOperation.IsChecked, internalOperation.IsCompareText, internalOperation.OperatorMethod, internalOperation.UnaryOperatorMethod, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitConditional(IConditionalOperation operation, object? argument) { var internalOperation = (ConditionalOperation)operation; return new ConditionalOperation(Visit(internalOperation.Condition), Visit(internalOperation.WhenTrue), Visit(internalOperation.WhenFalse), internalOperation.IsRef, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitCoalesce(ICoalesceOperation operation, object? argument) { var internalOperation = (CoalesceOperation)operation; return new CoalesceOperation(Visit(internalOperation.Value), Visit(internalOperation.WhenNull), internalOperation.ValueConversionConvertible, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitAnonymousFunction(IAnonymousFunctionOperation operation, object? argument) { var internalOperation = (AnonymousFunctionOperation)operation; return new AnonymousFunctionOperation(internalOperation.Symbol, Visit(internalOperation.Body), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitObjectCreation(IObjectCreationOperation operation, object? argument) { var internalOperation = (ObjectCreationOperation)operation; return new ObjectCreationOperation(internalOperation.Constructor, Visit(internalOperation.Initializer), VisitArray(internalOperation.Arguments), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, object? argument) { var internalOperation = (TypeParameterObjectCreationOperation)operation; return new TypeParameterObjectCreationOperation(Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitArrayCreation(IArrayCreationOperation operation, object? argument) { var internalOperation = (ArrayCreationOperation)operation; return new ArrayCreationOperation(VisitArray(internalOperation.DimensionSizes), Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitInstanceReference(IInstanceReferenceOperation operation, object? argument) { var internalOperation = (InstanceReferenceOperation)operation; return new InstanceReferenceOperation(internalOperation.ReferenceKind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitIsType(IIsTypeOperation operation, object? argument) { var internalOperation = (IsTypeOperation)operation; return new IsTypeOperation(Visit(internalOperation.ValueOperand), internalOperation.TypeOperand, internalOperation.IsNegated, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitAwait(IAwaitOperation operation, object? argument) { var internalOperation = (AwaitOperation)operation; return new AwaitOperation(Visit(internalOperation.Operation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitSimpleAssignment(ISimpleAssignmentOperation operation, object? argument) { var internalOperation = (SimpleAssignmentOperation)operation; return new SimpleAssignmentOperation(internalOperation.IsRef, Visit(internalOperation.Target), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitCompoundAssignment(ICompoundAssignmentOperation operation, object? argument) { var internalOperation = (CompoundAssignmentOperation)operation; return new CompoundAssignmentOperation(internalOperation.InConversionConvertible, internalOperation.OutConversionConvertible, internalOperation.OperatorKind, internalOperation.IsLifted, internalOperation.IsChecked, internalOperation.OperatorMethod, Visit(internalOperation.Target), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitParenthesized(IParenthesizedOperation operation, object? argument) { var internalOperation = (ParenthesizedOperation)operation; return new ParenthesizedOperation(Visit(internalOperation.Operand), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitEventAssignment(IEventAssignmentOperation operation, object? argument) { var internalOperation = (EventAssignmentOperation)operation; return new EventAssignmentOperation(Visit(internalOperation.EventReference), Visit(internalOperation.HandlerValue), internalOperation.Adds, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitConditionalAccess(IConditionalAccessOperation operation, object? argument) { var internalOperation = (ConditionalAccessOperation)operation; return new ConditionalAccessOperation(Visit(internalOperation.Operation), Visit(internalOperation.WhenNotNull), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, object? argument) { var internalOperation = (ConditionalAccessInstanceOperation)operation; return new ConditionalAccessInstanceOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitInterpolatedString(IInterpolatedStringOperation operation, object? argument) { var internalOperation = (InterpolatedStringOperation)operation; return new InterpolatedStringOperation(VisitArray(internalOperation.Parts), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, object? argument) { var internalOperation = (AnonymousObjectCreationOperation)operation; return new AnonymousObjectCreationOperation(VisitArray(internalOperation.Initializers), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, object? argument) { var internalOperation = (ObjectOrCollectionInitializerOperation)operation; return new ObjectOrCollectionInitializerOperation(VisitArray(internalOperation.Initializers), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitMemberInitializer(IMemberInitializerOperation operation, object? argument) { var internalOperation = (MemberInitializerOperation)operation; return new MemberInitializerOperation(Visit(internalOperation.InitializedMember), Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitNameOf(INameOfOperation operation, object? argument) { var internalOperation = (NameOfOperation)operation; return new NameOfOperation(Visit(internalOperation.Argument), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitTuple(ITupleOperation operation, object? argument) { var internalOperation = (TupleOperation)operation; return new TupleOperation(VisitArray(internalOperation.Elements), internalOperation.NaturalType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, object? argument) { var internalOperation = (DynamicMemberReferenceOperation)operation; return new DynamicMemberReferenceOperation(Visit(internalOperation.Instance), internalOperation.MemberName, internalOperation.TypeArguments, internalOperation.ContainingType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitTranslatedQuery(ITranslatedQueryOperation operation, object? argument) { var internalOperation = (TranslatedQueryOperation)operation; return new TranslatedQueryOperation(Visit(internalOperation.Operation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDelegateCreation(IDelegateCreationOperation operation, object? argument) { var internalOperation = (DelegateCreationOperation)operation; return new DelegateCreationOperation(Visit(internalOperation.Target), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDefaultValue(IDefaultValueOperation operation, object? argument) { var internalOperation = (DefaultValueOperation)operation; return new DefaultValueOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitTypeOf(ITypeOfOperation operation, object? argument) { var internalOperation = (TypeOfOperation)operation; return new TypeOfOperation(internalOperation.TypeOperand, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitSizeOf(ISizeOfOperation operation, object? argument) { var internalOperation = (SizeOfOperation)operation; return new SizeOfOperation(internalOperation.TypeOperand, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitAddressOf(IAddressOfOperation operation, object? argument) { var internalOperation = (AddressOfOperation)operation; return new AddressOfOperation(Visit(internalOperation.Reference), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitIsPattern(IIsPatternOperation operation, object? argument) { var internalOperation = (IsPatternOperation)operation; return new IsPatternOperation(Visit(internalOperation.Value), Visit(internalOperation.Pattern), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, object? argument) { var internalOperation = (IncrementOrDecrementOperation)operation; return new IncrementOrDecrementOperation(internalOperation.IsPostfix, internalOperation.IsLifted, internalOperation.IsChecked, Visit(internalOperation.Target), internalOperation.OperatorMethod, internalOperation.Kind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitThrow(IThrowOperation operation, object? argument) { var internalOperation = (ThrowOperation)operation; return new ThrowOperation(Visit(internalOperation.Exception), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, object? argument) { var internalOperation = (DeconstructionAssignmentOperation)operation; return new DeconstructionAssignmentOperation(Visit(internalOperation.Target), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitDeclarationExpression(IDeclarationExpressionOperation operation, object? argument) { var internalOperation = (DeclarationExpressionOperation)operation; return new DeclarationExpressionOperation(Visit(internalOperation.Expression), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitOmittedArgument(IOmittedArgumentOperation operation, object? argument) { var internalOperation = (OmittedArgumentOperation)operation; return new OmittedArgumentOperation(internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitFieldInitializer(IFieldInitializerOperation operation, object? argument) { var internalOperation = (FieldInitializerOperation)operation; return new FieldInitializerOperation(internalOperation.InitializedFields, internalOperation.Locals, Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitVariableInitializer(IVariableInitializerOperation operation, object? argument) { var internalOperation = (VariableInitializerOperation)operation; return new VariableInitializerOperation(internalOperation.Locals, Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitPropertyInitializer(IPropertyInitializerOperation operation, object? argument) { var internalOperation = (PropertyInitializerOperation)operation; return new PropertyInitializerOperation(internalOperation.InitializedProperties, internalOperation.Locals, Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitParameterInitializer(IParameterInitializerOperation operation, object? argument) { var internalOperation = (ParameterInitializerOperation)operation; return new ParameterInitializerOperation(internalOperation.Parameter, internalOperation.Locals, Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitArrayInitializer(IArrayInitializerOperation operation, object? argument) { var internalOperation = (ArrayInitializerOperation)operation; return new ArrayInitializerOperation(VisitArray(internalOperation.ElementValues), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitVariableDeclarator(IVariableDeclaratorOperation operation, object? argument) { var internalOperation = (VariableDeclaratorOperation)operation; return new VariableDeclaratorOperation(internalOperation.Symbol, Visit(internalOperation.Initializer), VisitArray(internalOperation.IgnoredArguments), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitVariableDeclaration(IVariableDeclarationOperation operation, object? argument) { var internalOperation = (VariableDeclarationOperation)operation; return new VariableDeclarationOperation(VisitArray(internalOperation.Declarators), Visit(internalOperation.Initializer), VisitArray(internalOperation.IgnoredDimensions), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitArgument(IArgumentOperation operation, object? argument) { var internalOperation = (ArgumentOperation)operation; return new ArgumentOperation(internalOperation.ArgumentKind, internalOperation.Parameter, Visit(internalOperation.Value), internalOperation.InConversionConvertible, internalOperation.OutConversionConvertible, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitCatchClause(ICatchClauseOperation operation, object? argument) { var internalOperation = (CatchClauseOperation)operation; return new CatchClauseOperation(Visit(internalOperation.ExceptionDeclarationOrExpression), internalOperation.ExceptionType, internalOperation.Locals, Visit(internalOperation.Filter), Visit(internalOperation.Handler), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitSwitchCase(ISwitchCaseOperation operation, object? argument) { var internalOperation = (SwitchCaseOperation)operation; return new SwitchCaseOperation(VisitArray(internalOperation.Clauses), VisitArray(internalOperation.Body), internalOperation.Locals, Visit(internalOperation.Condition), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, object? argument) { var internalOperation = (DefaultCaseClauseOperation)operation; return new DefaultCaseClauseOperation(internalOperation.Label, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitPatternCaseClause(IPatternCaseClauseOperation operation, object? argument) { var internalOperation = (PatternCaseClauseOperation)operation; return new PatternCaseClauseOperation(internalOperation.Label, Visit(internalOperation.Pattern), Visit(internalOperation.Guard), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRangeCaseClause(IRangeCaseClauseOperation operation, object? argument) { var internalOperation = (RangeCaseClauseOperation)operation; return new RangeCaseClauseOperation(Visit(internalOperation.MinimumValue), Visit(internalOperation.MaximumValue), internalOperation.Label, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, object? argument) { var internalOperation = (RelationalCaseClauseOperation)operation; return new RelationalCaseClauseOperation(Visit(internalOperation.Value), internalOperation.Relation, internalOperation.Label, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, object? argument) { var internalOperation = (SingleValueCaseClauseOperation)operation; return new SingleValueCaseClauseOperation(Visit(internalOperation.Value), internalOperation.Label, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, object? argument) { var internalOperation = (InterpolatedStringTextOperation)operation; return new InterpolatedStringTextOperation(Visit(internalOperation.Text), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitInterpolation(IInterpolationOperation operation, object? argument) { var internalOperation = (InterpolationOperation)operation; return new InterpolationOperation(Visit(internalOperation.Expression), Visit(internalOperation.Alignment), Visit(internalOperation.FormatString), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitConstantPattern(IConstantPatternOperation operation, object? argument) { var internalOperation = (ConstantPatternOperation)operation; return new ConstantPatternOperation(Visit(internalOperation.Value), internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitDeclarationPattern(IDeclarationPatternOperation operation, object? argument) { var internalOperation = (DeclarationPatternOperation)operation; return new DeclarationPatternOperation(internalOperation.MatchedType, internalOperation.MatchesNull, internalOperation.DeclaredSymbol, internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitTupleBinaryOperator(ITupleBinaryOperation operation, object? argument) { var internalOperation = (TupleBinaryOperation)operation; return new TupleBinaryOperation(internalOperation.OperatorKind, Visit(internalOperation.LeftOperand), Visit(internalOperation.RightOperand), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitMethodBodyOperation(IMethodBodyOperation operation, object? argument) { var internalOperation = (MethodBodyOperation)operation; return new MethodBodyOperation(Visit(internalOperation.BlockBody), Visit(internalOperation.ExpressionBody), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitConstructorBodyOperation(IConstructorBodyOperation operation, object? argument) { var internalOperation = (ConstructorBodyOperation)operation; return new ConstructorBodyOperation(internalOperation.Locals, Visit(internalOperation.Initializer), Visit(internalOperation.BlockBody), Visit(internalOperation.ExpressionBody), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitDiscardOperation(IDiscardOperation operation, object? argument) { var internalOperation = (DiscardOperation)operation; return new DiscardOperation(internalOperation.DiscardSymbol, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, object? argument) { var internalOperation = (FlowCaptureReferenceOperation)operation; return new FlowCaptureReferenceOperation(internalOperation.Id, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.OperationConstantValue, internalOperation.IsImplicit); } public override IOperation VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, object? argument) { var internalOperation = (CoalesceAssignmentOperation)operation; return new CoalesceAssignmentOperation(Visit(internalOperation.Target), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitRangeOperation(IRangeOperation operation, object? argument) { var internalOperation = (RangeOperation)operation; return new RangeOperation(Visit(internalOperation.LeftOperand), Visit(internalOperation.RightOperand), internalOperation.IsLifted, internalOperation.Method, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitReDim(IReDimOperation operation, object? argument) { var internalOperation = (ReDimOperation)operation; return new ReDimOperation(VisitArray(internalOperation.Clauses), internalOperation.Preserve, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitReDimClause(IReDimClauseOperation operation, object? argument) { var internalOperation = (ReDimClauseOperation)operation; return new ReDimClauseOperation(Visit(internalOperation.Operand), VisitArray(internalOperation.DimensionSizes), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRecursivePattern(IRecursivePatternOperation operation, object? argument) { var internalOperation = (RecursivePatternOperation)operation; return new RecursivePatternOperation(internalOperation.MatchedType, internalOperation.DeconstructSymbol, VisitArray(internalOperation.DeconstructionSubpatterns), VisitArray(internalOperation.PropertySubpatterns), internalOperation.DeclaredSymbol, internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitDiscardPattern(IDiscardPatternOperation operation, object? argument) { var internalOperation = (DiscardPatternOperation)operation; return new DiscardPatternOperation(internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitSwitchExpression(ISwitchExpressionOperation operation, object? argument) { var internalOperation = (SwitchExpressionOperation)operation; return new SwitchExpressionOperation(Visit(internalOperation.Value), VisitArray(internalOperation.Arms), internalOperation.IsExhaustive, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation, object? argument) { var internalOperation = (SwitchExpressionArmOperation)operation; return new SwitchExpressionArmOperation(Visit(internalOperation.Pattern), Visit(internalOperation.Guard), Visit(internalOperation.Value), internalOperation.Locals, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitPropertySubpattern(IPropertySubpatternOperation operation, object? argument) { var internalOperation = (PropertySubpatternOperation)operation; return new PropertySubpatternOperation(Visit(internalOperation.Member), Visit(internalOperation.Pattern), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } internal override IOperation VisitAggregateQuery(IAggregateQueryOperation operation, object? argument) { var internalOperation = (AggregateQueryOperation)operation; return new AggregateQueryOperation(Visit(internalOperation.Group), Visit(internalOperation.Aggregation), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } internal override IOperation VisitFixed(IFixedOperation operation, object? argument) { var internalOperation = (FixedOperation)operation; return new FixedOperation(internalOperation.Locals, Visit(internalOperation.Variables), Visit(internalOperation.Body), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } internal override IOperation VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, object? argument) { var internalOperation = (NoPiaObjectCreationOperation)operation; return new NoPiaObjectCreationOperation(Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } internal override IOperation VisitPlaceholder(IPlaceholderOperation operation, object? argument) { var internalOperation = (PlaceholderOperation)operation; return new PlaceholderOperation(internalOperation.PlaceholderKind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } internal override IOperation VisitWithStatement(IWithStatementOperation operation, object? argument) { var internalOperation = (WithStatementOperation)operation; return new WithStatementOperation(Visit(internalOperation.Body), Visit(internalOperation.Value), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitUsingDeclaration(IUsingDeclarationOperation operation, object? argument) { var internalOperation = (UsingDeclarationOperation)operation; return new UsingDeclarationOperation(Visit(internalOperation.DeclarationGroup), internalOperation.IsAsynchronous, internalOperation.DisposeInfo, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitNegatedPattern(INegatedPatternOperation operation, object? argument) { var internalOperation = (NegatedPatternOperation)operation; return new NegatedPatternOperation(Visit(internalOperation.Pattern), internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitBinaryPattern(IBinaryPatternOperation operation, object? argument) { var internalOperation = (BinaryPatternOperation)operation; return new BinaryPatternOperation(internalOperation.OperatorKind, Visit(internalOperation.LeftPattern), Visit(internalOperation.RightPattern), internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitTypePattern(ITypePatternOperation operation, object? argument) { var internalOperation = (TypePatternOperation)operation; return new TypePatternOperation(internalOperation.MatchedType, internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitRelationalPattern(IRelationalPatternOperation operation, object? argument) { var internalOperation = (RelationalPatternOperation)operation; return new RelationalPatternOperation(internalOperation.OperatorKind, Visit(internalOperation.Value), internalOperation.InputType, internalOperation.NarrowedType, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitWith(IWithOperation operation, object? argument) { var internalOperation = (WithOperation)operation; return new WithOperation(Visit(internalOperation.Operand), internalOperation.CloneMethod, Visit(internalOperation.Initializer), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation, object? argument) { var internalOperation = (InterpolatedStringHandlerCreationOperation)operation; return new InterpolatedStringHandlerCreationOperation(Visit(internalOperation.HandlerCreation), internalOperation.HandlerCreationHasSuccessParameter, internalOperation.HandlerAppendCallsReturnBool, Visit(internalOperation.Content), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.Type, internalOperation.IsImplicit); } public override IOperation VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation, object? argument) { var internalOperation = (InterpolatedStringAdditionOperation)operation; return new InterpolatedStringAdditionOperation(Visit(internalOperation.Left), Visit(internalOperation.Right), internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation, object? argument) { var internalOperation = (InterpolatedStringAppendOperation)operation; return new InterpolatedStringAppendOperation(Visit(internalOperation.AppendCall), internalOperation.Kind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } public override IOperation VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation, object? argument) { var internalOperation = (InterpolatedStringHandlerArgumentPlaceholderOperation)operation; return new InterpolatedStringHandlerArgumentPlaceholderOperation(internalOperation.ArgumentIndex, internalOperation.PlaceholderKind, internalOperation.OwningSemanticModel, internalOperation.Syntax, internalOperation.IsImplicit); } } #endregion #region Visitors public abstract partial class OperationVisitor { public virtual void Visit(IOperation? operation) => operation?.Accept(this); public virtual void DefaultVisit(IOperation operation) { /* no-op */ } internal virtual void VisitNoneOperation(IOperation operation) { /* no-op */ } public virtual void VisitInvalid(IInvalidOperation operation) => DefaultVisit(operation); public virtual void VisitBlock(IBlockOperation operation) => DefaultVisit(operation); public virtual void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) => DefaultVisit(operation); public virtual void VisitSwitch(ISwitchOperation operation) => DefaultVisit(operation); public virtual void VisitForEachLoop(IForEachLoopOperation operation) => DefaultVisit(operation); public virtual void VisitForLoop(IForLoopOperation operation) => DefaultVisit(operation); public virtual void VisitForToLoop(IForToLoopOperation operation) => DefaultVisit(operation); public virtual void VisitWhileLoop(IWhileLoopOperation operation) => DefaultVisit(operation); public virtual void VisitLabeled(ILabeledOperation operation) => DefaultVisit(operation); public virtual void VisitBranch(IBranchOperation operation) => DefaultVisit(operation); public virtual void VisitEmpty(IEmptyOperation operation) => DefaultVisit(operation); public virtual void VisitReturn(IReturnOperation operation) => DefaultVisit(operation); public virtual void VisitLock(ILockOperation operation) => DefaultVisit(operation); public virtual void VisitTry(ITryOperation operation) => DefaultVisit(operation); public virtual void VisitUsing(IUsingOperation operation) => DefaultVisit(operation); public virtual void VisitExpressionStatement(IExpressionStatementOperation operation) => DefaultVisit(operation); public virtual void VisitLocalFunction(ILocalFunctionOperation operation) => DefaultVisit(operation); public virtual void VisitStop(IStopOperation operation) => DefaultVisit(operation); public virtual void VisitEnd(IEndOperation operation) => DefaultVisit(operation); public virtual void VisitRaiseEvent(IRaiseEventOperation operation) => DefaultVisit(operation); public virtual void VisitLiteral(ILiteralOperation operation) => DefaultVisit(operation); public virtual void VisitConversion(IConversionOperation operation) => DefaultVisit(operation); public virtual void VisitInvocation(IInvocationOperation operation) => DefaultVisit(operation); public virtual void VisitArrayElementReference(IArrayElementReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitLocalReference(ILocalReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitParameterReference(IParameterReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitFieldReference(IFieldReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitMethodReference(IMethodReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitPropertyReference(IPropertyReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitEventReference(IEventReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitUnaryOperator(IUnaryOperation operation) => DefaultVisit(operation); public virtual void VisitBinaryOperator(IBinaryOperation operation) => DefaultVisit(operation); public virtual void VisitConditional(IConditionalOperation operation) => DefaultVisit(operation); public virtual void VisitCoalesce(ICoalesceOperation operation) => DefaultVisit(operation); public virtual void VisitAnonymousFunction(IAnonymousFunctionOperation operation) => DefaultVisit(operation); public virtual void VisitObjectCreation(IObjectCreationOperation operation) => DefaultVisit(operation); public virtual void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) => DefaultVisit(operation); public virtual void VisitArrayCreation(IArrayCreationOperation operation) => DefaultVisit(operation); public virtual void VisitInstanceReference(IInstanceReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitIsType(IIsTypeOperation operation) => DefaultVisit(operation); public virtual void VisitAwait(IAwaitOperation operation) => DefaultVisit(operation); public virtual void VisitSimpleAssignment(ISimpleAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitCompoundAssignment(ICompoundAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitParenthesized(IParenthesizedOperation operation) => DefaultVisit(operation); public virtual void VisitEventAssignment(IEventAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitConditionalAccess(IConditionalAccessOperation operation) => DefaultVisit(operation); public virtual void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolatedString(IInterpolatedStringOperation operation) => DefaultVisit(operation); public virtual void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) => DefaultVisit(operation); public virtual void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitMemberInitializer(IMemberInitializerOperation operation) => DefaultVisit(operation); [Obsolete("ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation), error: true)] public virtual void VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitNameOf(INameOfOperation operation) => DefaultVisit(operation); public virtual void VisitTuple(ITupleOperation operation) => DefaultVisit(operation); public virtual void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) => DefaultVisit(operation); public virtual void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitDynamicInvocation(IDynamicInvocationOperation operation) => DefaultVisit(operation); public virtual void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) => DefaultVisit(operation); public virtual void VisitTranslatedQuery(ITranslatedQueryOperation operation) => DefaultVisit(operation); public virtual void VisitDelegateCreation(IDelegateCreationOperation operation) => DefaultVisit(operation); public virtual void VisitDefaultValue(IDefaultValueOperation operation) => DefaultVisit(operation); public virtual void VisitTypeOf(ITypeOfOperation operation) => DefaultVisit(operation); public virtual void VisitSizeOf(ISizeOfOperation operation) => DefaultVisit(operation); public virtual void VisitAddressOf(IAddressOfOperation operation) => DefaultVisit(operation); public virtual void VisitIsPattern(IIsPatternOperation operation) => DefaultVisit(operation); public virtual void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) => DefaultVisit(operation); public virtual void VisitThrow(IThrowOperation operation) => DefaultVisit(operation); public virtual void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitDeclarationExpression(IDeclarationExpressionOperation operation) => DefaultVisit(operation); public virtual void VisitOmittedArgument(IOmittedArgumentOperation operation) => DefaultVisit(operation); public virtual void VisitFieldInitializer(IFieldInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitVariableInitializer(IVariableInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitPropertyInitializer(IPropertyInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitParameterInitializer(IParameterInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitArrayInitializer(IArrayInitializerOperation operation) => DefaultVisit(operation); public virtual void VisitVariableDeclarator(IVariableDeclaratorOperation operation) => DefaultVisit(operation); public virtual void VisitVariableDeclaration(IVariableDeclarationOperation operation) => DefaultVisit(operation); public virtual void VisitArgument(IArgumentOperation operation) => DefaultVisit(operation); public virtual void VisitCatchClause(ICatchClauseOperation operation) => DefaultVisit(operation); public virtual void VisitSwitchCase(ISwitchCaseOperation operation) => DefaultVisit(operation); public virtual void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitPatternCaseClause(IPatternCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitRangeCaseClause(IRangeCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolation(IInterpolationOperation operation) => DefaultVisit(operation); public virtual void VisitConstantPattern(IConstantPatternOperation operation) => DefaultVisit(operation); public virtual void VisitDeclarationPattern(IDeclarationPatternOperation operation) => DefaultVisit(operation); public virtual void VisitTupleBinaryOperator(ITupleBinaryOperation operation) => DefaultVisit(operation); public virtual void VisitMethodBodyOperation(IMethodBodyOperation operation) => DefaultVisit(operation); public virtual void VisitConstructorBodyOperation(IConstructorBodyOperation operation) => DefaultVisit(operation); public virtual void VisitDiscardOperation(IDiscardOperation operation) => DefaultVisit(operation); public virtual void VisitFlowCapture(IFlowCaptureOperation operation) => DefaultVisit(operation); public virtual void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) => DefaultVisit(operation); public virtual void VisitIsNull(IIsNullOperation operation) => DefaultVisit(operation); public virtual void VisitCaughtException(ICaughtExceptionOperation operation) => DefaultVisit(operation); public virtual void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) => DefaultVisit(operation); public virtual void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) => DefaultVisit(operation); public virtual void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) => DefaultVisit(operation); public virtual void VisitRangeOperation(IRangeOperation operation) => DefaultVisit(operation); public virtual void VisitReDim(IReDimOperation operation) => DefaultVisit(operation); public virtual void VisitReDimClause(IReDimClauseOperation operation) => DefaultVisit(operation); public virtual void VisitRecursivePattern(IRecursivePatternOperation operation) => DefaultVisit(operation); public virtual void VisitDiscardPattern(IDiscardPatternOperation operation) => DefaultVisit(operation); public virtual void VisitSwitchExpression(ISwitchExpressionOperation operation) => DefaultVisit(operation); public virtual void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) => DefaultVisit(operation); public virtual void VisitPropertySubpattern(IPropertySubpatternOperation operation) => DefaultVisit(operation); internal virtual void VisitAggregateQuery(IAggregateQueryOperation operation) => DefaultVisit(operation); internal virtual void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) => DefaultVisit(operation); internal virtual void VisitPlaceholder(IPlaceholderOperation operation) => DefaultVisit(operation); internal virtual void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) => DefaultVisit(operation); internal virtual void VisitWithStatement(IWithStatementOperation operation) => DefaultVisit(operation); public virtual void VisitUsingDeclaration(IUsingDeclarationOperation operation) => DefaultVisit(operation); public virtual void VisitNegatedPattern(INegatedPatternOperation operation) => DefaultVisit(operation); public virtual void VisitBinaryPattern(IBinaryPatternOperation operation) => DefaultVisit(operation); public virtual void VisitTypePattern(ITypePatternOperation operation) => DefaultVisit(operation); public virtual void VisitRelationalPattern(IRelationalPatternOperation operation) => DefaultVisit(operation); public virtual void VisitWith(IWithOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation) => DefaultVisit(operation); public virtual void VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation) => DefaultVisit(operation); } public abstract partial class OperationVisitor<TArgument, TResult> { public virtual TResult? Visit(IOperation? operation, TArgument argument) => operation is null ? default(TResult) : operation.Accept(this, argument); public virtual TResult? DefaultVisit(IOperation operation, TArgument argument) => default(TResult); internal virtual TResult? VisitNoneOperation(IOperation operation, TArgument argument) => default(TResult); public virtual TResult? VisitInvalid(IInvalidOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitBlock(IBlockOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSwitch(ISwitchOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitForEachLoop(IForEachLoopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitForLoop(IForLoopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitForToLoop(IForToLoopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitWhileLoop(IWhileLoopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLabeled(ILabeledOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitBranch(IBranchOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitEmpty(IEmptyOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitReturn(IReturnOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLock(ILockOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTry(ITryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitUsing(IUsingOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitExpressionStatement(IExpressionStatementOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLocalFunction(ILocalFunctionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitStop(IStopOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitEnd(IEndOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRaiseEvent(IRaiseEventOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLiteral(ILiteralOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConversion(IConversionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInvocation(IInvocationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitArrayElementReference(IArrayElementReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitLocalReference(ILocalReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitParameterReference(IParameterReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFieldReference(IFieldReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitMethodReference(IMethodReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitPropertyReference(IPropertyReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitEventReference(IEventReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitUnaryOperator(IUnaryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitBinaryOperator(IBinaryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConditional(IConditionalOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCoalesce(ICoalesceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitAnonymousFunction(IAnonymousFunctionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitObjectCreation(IObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitArrayCreation(IArrayCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInstanceReference(IInstanceReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitIsType(IIsTypeOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitAwait(IAwaitOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSimpleAssignment(ISimpleAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCompoundAssignment(ICompoundAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitParenthesized(IParenthesizedOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitEventAssignment(IEventAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConditionalAccess(IConditionalAccessOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolatedString(IInterpolatedStringOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitMemberInitializer(IMemberInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); [Obsolete("ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation), error: true)] public virtual TResult? VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitNameOf(INameOfOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTuple(ITupleOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDynamicInvocation(IDynamicInvocationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTranslatedQuery(ITranslatedQueryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDelegateCreation(IDelegateCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDefaultValue(IDefaultValueOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTypeOf(ITypeOfOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSizeOf(ISizeOfOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitAddressOf(IAddressOfOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitIsPattern(IIsPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitThrow(IThrowOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDeclarationExpression(IDeclarationExpressionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitOmittedArgument(IOmittedArgumentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFieldInitializer(IFieldInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitVariableInitializer(IVariableInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitPropertyInitializer(IPropertyInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitParameterInitializer(IParameterInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitArrayInitializer(IArrayInitializerOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitVariableDeclarator(IVariableDeclaratorOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitVariableDeclaration(IVariableDeclarationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitArgument(IArgumentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCatchClause(ICatchClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSwitchCase(ISwitchCaseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitPatternCaseClause(IPatternCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRangeCaseClause(IRangeCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolation(IInterpolationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConstantPattern(IConstantPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDeclarationPattern(IDeclarationPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTupleBinaryOperator(ITupleBinaryOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitMethodBodyOperation(IMethodBodyOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitConstructorBodyOperation(IConstructorBodyOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDiscardOperation(IDiscardOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFlowCapture(IFlowCaptureOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitIsNull(IIsNullOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCaughtException(ICaughtExceptionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRangeOperation(IRangeOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitReDim(IReDimOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitReDimClause(IReDimClauseOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRecursivePattern(IRecursivePatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitDiscardPattern(IDiscardPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSwitchExpression(ISwitchExpressionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitPropertySubpattern(IPropertySubpatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitAggregateQuery(IAggregateQueryOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitPlaceholder(IPlaceholderOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation, TArgument argument) => DefaultVisit(operation, argument); internal virtual TResult? VisitWithStatement(IWithStatementOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitUsingDeclaration(IUsingDeclarationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitNegatedPattern(INegatedPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitBinaryPattern(IBinaryPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitTypePattern(ITypePatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitRelationalPattern(IRelationalPatternOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitWith(IWithOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation, TArgument argument) => DefaultVisit(operation, argument); public virtual TResult? VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation, TArgument argument) => DefaultVisit(operation, argument); } #endregion }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis { /// <summary> /// Some basic concepts: /// - Basic blocks are sequences of statements/operations with no branching. The only branching /// allowed is at the end of the basic block. /// - Regions group blocks together and represent the lifetime of locals and captures, loosely similar to scopes in C#. /// There are different kinds of regions, <see cref="ControlFlowRegionKind"/>. /// - <see cref="ControlFlowGraphBuilder.SpillEvalStack"/> converts values on the stack into captures. /// - Error scenarios from initial binding need to be handled. /// </summary> internal sealed partial class ControlFlowGraphBuilder : OperationVisitor<int?, IOperation> { private readonly Compilation _compilation; private readonly BasicBlockBuilder _entry = new BasicBlockBuilder(BasicBlockKind.Entry); private readonly BasicBlockBuilder _exit = new BasicBlockBuilder(BasicBlockKind.Exit); private readonly ArrayBuilder<BasicBlockBuilder> _blocks; private readonly PooledDictionary<BasicBlockBuilder, RegionBuilder> _regionMap; private BasicBlockBuilder? _currentBasicBlock; private RegionBuilder? _currentRegion; private PooledDictionary<ILabelSymbol, BasicBlockBuilder>? _labeledBlocks; private bool _haveAnonymousFunction; private IOperation? _currentStatement; private readonly ArrayBuilder<(EvalStackFrame? frameOpt, IOperation? operationOpt)> _evalStack; private int _startSpillingAt; private ConditionalAccessOperationTracker _currentConditionalAccessTracker; private IOperation? _currentSwitchOperationExpression; private IOperation? _forToLoopBinaryOperatorLeftOperand; private IOperation? _forToLoopBinaryOperatorRightOperand; private IOperation? _currentAggregationGroup; private bool _forceImplicit; // Force all rewritten nodes to be marked as implicit regardless of their original state. private readonly CaptureIdDispenser _captureIdDispenser; /// <summary> /// Holds the current object being initialized if we're visiting an object initializer. /// Or the current anonymous type object being initialized if we're visiting an anonymous type object initializer. /// Or the target of a VB With statement. /// </summary> private ImplicitInstanceInfo _currentImplicitInstance; private ControlFlowGraphBuilder(Compilation compilation, CaptureIdDispenser? captureIdDispenser, ArrayBuilder<BasicBlockBuilder> blocks) { Debug.Assert(compilation != null); _compilation = compilation; _captureIdDispenser = captureIdDispenser ?? new CaptureIdDispenser(); _blocks = blocks; _regionMap = PooledDictionary<BasicBlockBuilder, RegionBuilder>.GetInstance(); _evalStack = ArrayBuilder<(EvalStackFrame? frameOpt, IOperation? operationOpt)>.GetInstance(); } private RegionBuilder CurrentRegionRequired { get { Debug.Assert(_currentRegion != null); return _currentRegion; } } private bool IsImplicit(IOperation operation) { return _forceImplicit || operation.IsImplicit; } public static ControlFlowGraph Create(IOperation body, ControlFlowGraph? parent = null, ControlFlowRegion? enclosing = null, CaptureIdDispenser? captureIdDispenser = null, in Context context = default) { Debug.Assert(body != null); Debug.Assert(((Operation)body).OwningSemanticModel != null); #if DEBUG if (enclosing == null) { Debug.Assert(body.Parent == null); Debug.Assert(body.Kind == OperationKind.Block || body.Kind == OperationKind.MethodBody || body.Kind == OperationKind.ConstructorBody || body.Kind == OperationKind.FieldInitializer || body.Kind == OperationKind.PropertyInitializer || body.Kind == OperationKind.ParameterInitializer, $"Unexpected root operation kind: {body.Kind}"); Debug.Assert(parent == null); } else { Debug.Assert(body.Kind == OperationKind.LocalFunction || body.Kind == OperationKind.AnonymousFunction); Debug.Assert(parent != null); } #endif var blocks = ArrayBuilder<BasicBlockBuilder>.GetInstance(); var builder = new ControlFlowGraphBuilder(((Operation)body).OwningSemanticModel!.Compilation, captureIdDispenser, blocks); var root = new RegionBuilder(ControlFlowRegionKind.Root); builder.EnterRegion(root); builder.AppendNewBlock(builder._entry, linkToPrevious: false); builder._currentBasicBlock = null; builder.SetCurrentContext(context); builder.EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime)); switch (body.Kind) { case OperationKind.LocalFunction: Debug.Assert(captureIdDispenser != null); builder.VisitLocalFunctionAsRoot((ILocalFunctionOperation)body); break; case OperationKind.AnonymousFunction: Debug.Assert(captureIdDispenser != null); var anonymousFunction = (IAnonymousFunctionOperation)body; builder.VisitStatement(anonymousFunction.Body); break; default: builder.VisitStatement(body); break; } builder.LeaveRegion(); builder.AppendNewBlock(builder._exit); builder.LeaveRegion(); builder._currentImplicitInstance.Free(); Debug.Assert(builder._currentRegion == null); CheckUnresolvedBranches(blocks, builder._labeledBlocks); Pack(blocks, root, builder._regionMap); var localFunctions = ArrayBuilder<IMethodSymbol>.GetInstance(); var localFunctionsMap = ImmutableDictionary.CreateBuilder<IMethodSymbol, (ControlFlowRegion, ILocalFunctionOperation, int)>(); ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion, int)>.Builder? anonymousFunctionsMapOpt = null; if (builder._haveAnonymousFunction) { anonymousFunctionsMapOpt = ImmutableDictionary.CreateBuilder<IFlowAnonymousFunctionOperation, (ControlFlowRegion, int)>(); } ControlFlowRegion region = root.ToImmutableRegionAndFree(blocks, localFunctions, localFunctionsMap, anonymousFunctionsMapOpt, enclosing); root = null; MarkReachableBlocks(blocks); Debug.Assert(builder._evalStack.Count == 0); builder._evalStack.Free(); builder._regionMap.Free(); builder._labeledBlocks?.Free(); return new ControlFlowGraph(body, parent, builder._captureIdDispenser, ToImmutableBlocks(blocks), region, localFunctions.ToImmutableAndFree(), localFunctionsMap.ToImmutable(), anonymousFunctionsMapOpt?.ToImmutable() ?? ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion, int)>.Empty); } private static ImmutableArray<BasicBlock> ToImmutableBlocks(ArrayBuilder<BasicBlockBuilder> blockBuilders) { var builder = ArrayBuilder<BasicBlock>.GetInstance(blockBuilders.Count); // Pass 1: Iterate through blocksBuilder to create basic blocks. foreach (BasicBlockBuilder blockBuilder in blockBuilders) { builder.Add(blockBuilder.ToImmutable()); } // Pass 2: Create control flow branches with source and destination info and // update the branch information for the created basic blocks. foreach (BasicBlockBuilder blockBuilder in blockBuilders) { ControlFlowBranch? successor = getFallThroughSuccessor(blockBuilder); ControlFlowBranch? conditionalSuccessor = getConditionalSuccessor(blockBuilder); builder[blockBuilder.Ordinal].SetSuccessors(successor, conditionalSuccessor); } // Pass 3: Set the predecessors for the created basic blocks. foreach (BasicBlockBuilder blockBuilder in blockBuilders) { builder[blockBuilder.Ordinal].SetPredecessors(blockBuilder.ConvertPredecessorsToBranches(builder)); } return builder.ToImmutableAndFree(); ControlFlowBranch? getFallThroughSuccessor(BasicBlockBuilder blockBuilder) { return blockBuilder.Kind != BasicBlockKind.Exit ? getBranch(in blockBuilder.FallThrough, blockBuilder, isConditionalSuccessor: false) : null; } ControlFlowBranch? getConditionalSuccessor(BasicBlockBuilder blockBuilder) { return blockBuilder.HasCondition ? getBranch(in blockBuilder.Conditional, blockBuilder, isConditionalSuccessor: true) : null; } ControlFlowBranch getBranch(in BasicBlockBuilder.Branch branch, BasicBlockBuilder source, bool isConditionalSuccessor) { return new ControlFlowBranch( source: builder[source.Ordinal], destination: branch.Destination != null ? builder[branch.Destination.Ordinal] : null, branch.Kind, isConditionalSuccessor); } } private static void MarkReachableBlocks(ArrayBuilder<BasicBlockBuilder> blocks) { // NOTE: This flow graph walking algorithm has been forked into Workspaces layer's // implementation of "CustomDataFlowAnalysis", // we should keep them in sync as much as possible. var continueDispatchAfterFinally = PooledDictionary<ControlFlowRegion, bool>.GetInstance(); var dispatchedExceptionsFromRegions = PooledHashSet<ControlFlowRegion>.GetInstance(); MarkReachableBlocks(blocks, firstBlockOrdinal: 0, lastBlockOrdinal: blocks.Count - 1, outOfRangeBlocksToVisit: null, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, out _); continueDispatchAfterFinally.Free(); dispatchedExceptionsFromRegions.Free(); } private static BitVector MarkReachableBlocks( ArrayBuilder<BasicBlockBuilder> blocks, int firstBlockOrdinal, int lastBlockOrdinal, ArrayBuilder<BasicBlockBuilder>? outOfRangeBlocksToVisit, PooledDictionary<ControlFlowRegion, bool> continueDispatchAfterFinally, PooledHashSet<ControlFlowRegion> dispatchedExceptionsFromRegions, out bool fellThrough) { var visited = BitVector.Empty; var toVisit = ArrayBuilder<BasicBlockBuilder>.GetInstance(); fellThrough = false; toVisit.Push(blocks[firstBlockOrdinal]); do { BasicBlockBuilder current = toVisit.Pop(); if (current.Ordinal < firstBlockOrdinal || current.Ordinal > lastBlockOrdinal) { Debug.Assert(outOfRangeBlocksToVisit != null); outOfRangeBlocksToVisit.Push(current); continue; } if (visited[current.Ordinal]) { continue; } visited[current.Ordinal] = true; current.IsReachable = true; bool fallThrough = true; if (current.HasCondition) { if (current.BranchValue.GetConstantValue() is { IsBoolean: true, BooleanValue: bool constant }) { if (constant == (current.ConditionKind == ControlFlowConditionKind.WhenTrue)) { followBranch(current, in current.Conditional); fallThrough = false; } } else { followBranch(current, in current.Conditional); } } if (fallThrough) { BasicBlockBuilder.Branch branch = current.FallThrough; followBranch(current, in branch); if (current.Ordinal == lastBlockOrdinal && branch.Kind != ControlFlowBranchSemantics.Throw && branch.Kind != ControlFlowBranchSemantics.Rethrow) { fellThrough = true; } } // We are using very simple approach: // If try block is reachable, we should dispatch an exception from it, even if it is empty. // To simplify implementation, we dispatch exception from every reachable basic block and rely // on dispatchedExceptionsFromRegions cache to avoid doing duplicate work. Debug.Assert(current.Region != null); dispatchException(current.Region); } while (toVisit.Count != 0); toVisit.Free(); return visited; void followBranch(BasicBlockBuilder current, in BasicBlockBuilder.Branch branch) { switch (branch.Kind) { case ControlFlowBranchSemantics.None: case ControlFlowBranchSemantics.ProgramTermination: case ControlFlowBranchSemantics.StructuredExceptionHandling: case ControlFlowBranchSemantics.Throw: case ControlFlowBranchSemantics.Rethrow: case ControlFlowBranchSemantics.Error: Debug.Assert(branch.Destination == null); return; case ControlFlowBranchSemantics.Regular: case ControlFlowBranchSemantics.Return: Debug.Assert(branch.Destination != null); Debug.Assert(current.Region != null); if (stepThroughFinally(current.Region, branch.Destination)) { toVisit.Add(branch.Destination); } return; default: throw ExceptionUtilities.UnexpectedValue(branch.Kind); } } // Returns whether we should proceed to the destination after finallies were taken care of. bool stepThroughFinally(ControlFlowRegion region, BasicBlockBuilder destination) { int destinationOrdinal = destination.Ordinal; while (!region.ContainsBlock(destinationOrdinal)) { Debug.Assert(region.Kind != ControlFlowRegionKind.Root); Debug.Assert(region.EnclosingRegion != null); ControlFlowRegion enclosing = region.EnclosingRegion; if (region.Kind == ControlFlowRegionKind.Try && enclosing.Kind == ControlFlowRegionKind.TryAndFinally) { Debug.Assert(enclosing.NestedRegions[0] == region); Debug.Assert(enclosing.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); if (!stepThroughSingleFinally(enclosing.NestedRegions[1])) { // The point that continues dispatch is not reachable. Cancel the dispatch. return false; } } region = enclosing; } return true; } // Returns whether we should proceed with dispatch after finally was taken care of. bool stepThroughSingleFinally(ControlFlowRegion @finally) { Debug.Assert(@finally.Kind == ControlFlowRegionKind.Finally); if (!continueDispatchAfterFinally.TryGetValue(@finally, out bool continueDispatch)) { // For simplicity, we do a complete walk of the finally/filter region in isolation // to make sure that the resume dispatch point is reachable from its beginning. // It could also be reachable through invalid branches into the finally and we don't want to consider // these cases for regular finally handling. BitVector isolated = MarkReachableBlocks(blocks, @finally.FirstBlockOrdinal, @finally.LastBlockOrdinal, outOfRangeBlocksToVisit: toVisit, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, out bool isolatedFellThrough); visited.UnionWith(isolated); continueDispatch = isolatedFellThrough && blocks[@finally.LastBlockOrdinal].FallThrough.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling; continueDispatchAfterFinally.Add(@finally, continueDispatch); } return continueDispatch; } void dispatchException([DisallowNull] ControlFlowRegion? fromRegion) { do { if (!dispatchedExceptionsFromRegions.Add(fromRegion)) { return; } ControlFlowRegion? enclosing = fromRegion.Kind == ControlFlowRegionKind.Root ? null : fromRegion.EnclosingRegion; if (fromRegion.Kind == ControlFlowRegionKind.Try) { switch (enclosing!.Kind) { case ControlFlowRegionKind.TryAndFinally: Debug.Assert(enclosing.NestedRegions[0] == fromRegion); Debug.Assert(enclosing.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); if (!stepThroughSingleFinally(enclosing.NestedRegions[1])) { // The point that continues dispatch is not reachable. Cancel the dispatch. return; } break; case ControlFlowRegionKind.TryAndCatch: Debug.Assert(enclosing.NestedRegions[0] == fromRegion); dispatchExceptionThroughCatches(enclosing, startAt: 1); break; default: throw ExceptionUtilities.UnexpectedValue(enclosing.Kind); } } else if (fromRegion.Kind == ControlFlowRegionKind.Filter) { // If filter throws, dispatch is resumed at the next catch with an original exception Debug.Assert(enclosing!.Kind == ControlFlowRegionKind.FilterAndHandler); Debug.Assert(enclosing.EnclosingRegion != null); ControlFlowRegion tryAndCatch = enclosing.EnclosingRegion; Debug.Assert(tryAndCatch.Kind == ControlFlowRegionKind.TryAndCatch); int index = tryAndCatch.NestedRegions.IndexOf(enclosing, startIndex: 1); if (index > 0) { dispatchExceptionThroughCatches(tryAndCatch, startAt: index + 1); fromRegion = tryAndCatch; continue; } throw ExceptionUtilities.Unreachable; } fromRegion = enclosing; } while (fromRegion != null); } void dispatchExceptionThroughCatches(ControlFlowRegion tryAndCatch, int startAt) { // For simplicity, we do not try to figure out whether a catch clause definitely // handles all exceptions. Debug.Assert(tryAndCatch.Kind == ControlFlowRegionKind.TryAndCatch); Debug.Assert(startAt > 0); Debug.Assert(startAt <= tryAndCatch.NestedRegions.Length); for (int i = startAt; i < tryAndCatch.NestedRegions.Length; i++) { ControlFlowRegion @catch = tryAndCatch.NestedRegions[i]; switch (@catch.Kind) { case ControlFlowRegionKind.Catch: toVisit.Add(blocks[@catch.FirstBlockOrdinal]); break; case ControlFlowRegionKind.FilterAndHandler: BasicBlockBuilder entryBlock = blocks[@catch.FirstBlockOrdinal]; Debug.Assert(@catch.NestedRegions[0].Kind == ControlFlowRegionKind.Filter); Debug.Assert(entryBlock.Ordinal == @catch.NestedRegions[0].FirstBlockOrdinal); toVisit.Add(entryBlock); break; default: throw ExceptionUtilities.UnexpectedValue(@catch.Kind); } } } } /// <summary> /// Do a pass to eliminate blocks without statements that can be merged with predecessor(s) and /// to eliminate regions that can be merged with parents. /// </summary> private static void Pack(ArrayBuilder<BasicBlockBuilder> blocks, RegionBuilder root, PooledDictionary<BasicBlockBuilder, RegionBuilder> regionMap) { bool regionsChanged = true; while (true) { regionsChanged |= PackRegions(root, blocks, regionMap); if (!regionsChanged || !PackBlocks(blocks, regionMap)) { break; } regionsChanged = false; } } private static bool PackRegions(RegionBuilder root, ArrayBuilder<BasicBlockBuilder> blocks, PooledDictionary<BasicBlockBuilder, RegionBuilder> regionMap) { return PackRegion(root); bool PackRegion(RegionBuilder region) { Debug.Assert(!region.IsEmpty); bool result = false; if (region.HasRegions) { for (int i = region.Regions.Count - 1; i >= 0; i--) { RegionBuilder r = region.Regions[i]; if (PackRegion(r)) { result = true; } if (r.Kind == ControlFlowRegionKind.LocalLifetime && r.Locals.IsEmpty && !r.HasLocalFunctions && !r.HasCaptureIds) { MergeSubRegionAndFree(r, blocks, regionMap); result = true; } } } switch (region.Kind) { case ControlFlowRegionKind.Root: case ControlFlowRegionKind.Filter: case ControlFlowRegionKind.Try: case ControlFlowRegionKind.Catch: case ControlFlowRegionKind.Finally: case ControlFlowRegionKind.LocalLifetime: case ControlFlowRegionKind.StaticLocalInitializer: case ControlFlowRegionKind.ErroneousBody: if (region.Regions?.Count == 1) { RegionBuilder subRegion = region.Regions[0]; if (subRegion.Kind == ControlFlowRegionKind.LocalLifetime && subRegion.FirstBlock == region.FirstBlock && subRegion.LastBlock == region.LastBlock) { Debug.Assert(region.Kind != ControlFlowRegionKind.Root); // Transfer all content of the sub-region into the current region region.Locals = region.Locals.Concat(subRegion.Locals); region.AddRange(subRegion.LocalFunctions); region.AddCaptureIds(subRegion.CaptureIds); MergeSubRegionAndFree(subRegion, blocks, regionMap); result = true; break; } } if (region.HasRegions) { for (int i = region.Regions.Count - 1; i >= 0; i--) { RegionBuilder subRegion = region.Regions[i]; if (subRegion.Kind == ControlFlowRegionKind.LocalLifetime && !subRegion.HasLocalFunctions && !subRegion.HasRegions && subRegion.FirstBlock == subRegion.LastBlock) { Debug.Assert(subRegion.FirstBlock != null); BasicBlockBuilder block = subRegion.FirstBlock; if (!block.HasStatements && block.BranchValue == null) { Debug.Assert(!subRegion.HasCaptureIds); // This sub-region has no executable code, merge block into the parent and drop the sub-region Debug.Assert(regionMap[block] == subRegion); regionMap[block] = region; #if DEBUG subRegion.AboutToFree(); #endif subRegion.Free(); region.Regions.RemoveAt(i); result = true; } } } } break; case ControlFlowRegionKind.TryAndCatch: case ControlFlowRegionKind.TryAndFinally: case ControlFlowRegionKind.FilterAndHandler: break; default: throw ExceptionUtilities.UnexpectedValue(region.Kind); } return result; } } /// <summary> /// Merge content of <paramref name="subRegion"/> into its enclosing region and free it. /// </summary> private static void MergeSubRegionAndFree(RegionBuilder subRegion, ArrayBuilder<BasicBlockBuilder> blocks, PooledDictionary<BasicBlockBuilder, RegionBuilder> regionMap, bool canHaveEmptyRegion = false) { Debug.Assert(subRegion.Kind != ControlFlowRegionKind.Root); Debug.Assert(subRegion.Enclosing != null); RegionBuilder enclosing = subRegion.Enclosing; #if DEBUG subRegion.AboutToFree(); #endif if (subRegion.IsEmpty) { Debug.Assert(canHaveEmptyRegion); Debug.Assert(!subRegion.HasRegions); enclosing.Remove(subRegion); subRegion.Free(); return; } int firstBlockToMove = subRegion.FirstBlock.Ordinal; if (subRegion.HasRegions) { foreach (RegionBuilder r in subRegion.Regions) { Debug.Assert(!r.IsEmpty); for (int i = firstBlockToMove; i < r.FirstBlock.Ordinal; i++) { Debug.Assert(regionMap[blocks[i]] == subRegion); regionMap[blocks[i]] = enclosing; } firstBlockToMove = r.LastBlock.Ordinal + 1; } enclosing.ReplaceRegion(subRegion, subRegion.Regions); } else { enclosing.Remove(subRegion); } for (int i = firstBlockToMove; i <= subRegion.LastBlock.Ordinal; i++) { Debug.Assert(regionMap[blocks[i]] == subRegion); regionMap[blocks[i]] = enclosing; } subRegion.Free(); } /// <summary> /// Do a pass to eliminate blocks without statements that can be merged with predecessor(s). /// Returns true if any blocks were eliminated /// </summary> private static bool PackBlocks(ArrayBuilder<BasicBlockBuilder> blocks, PooledDictionary<BasicBlockBuilder, RegionBuilder> regionMap) { ArrayBuilder<RegionBuilder>? fromCurrent = null; ArrayBuilder<RegionBuilder>? fromDestination = null; ArrayBuilder<RegionBuilder>? fromPredecessor = null; ArrayBuilder<BasicBlockBuilder>? predecessorsBuilder = null; bool anyRemoved = false; bool retry; do { // We set this local to true during the loop below when we make some changes that might enable // transformations for basic blocks that were already looked at. We simply keep repeating the // pass until no such changes are made. retry = false; int count = blocks.Count - 1; for (int i = 1; i < count; i++) { BasicBlockBuilder block = blocks[i]; block.Ordinal = i; if (block.HasStatements) { // See if we can move all statements to the previous block BasicBlockBuilder? predecessor = block.GetSingletonPredecessorOrDefault(); if (predecessor != null && !predecessor.HasCondition && predecessor.Ordinal < block.Ordinal && predecessor.Kind != BasicBlockKind.Entry && predecessor.FallThrough.Destination == block && regionMap[predecessor] == regionMap[block]) { Debug.Assert(predecessor.BranchValue == null); Debug.Assert(predecessor.FallThrough.Kind == ControlFlowBranchSemantics.Regular); predecessor.MoveStatementsFrom(block); retry = true; } else { continue; } } ref BasicBlockBuilder.Branch next = ref block.FallThrough; Debug.Assert((block.BranchValue != null && !block.HasCondition) == (next.Kind == ControlFlowBranchSemantics.Return || next.Kind == ControlFlowBranchSemantics.Throw)); Debug.Assert((next.Destination == null) == (next.Kind == ControlFlowBranchSemantics.ProgramTermination || next.Kind == ControlFlowBranchSemantics.Throw || next.Kind == ControlFlowBranchSemantics.Rethrow || next.Kind == ControlFlowBranchSemantics.Error || next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling)); #if DEBUG if (next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling) { RegionBuilder currentRegion = regionMap[block]; Debug.Assert(currentRegion.Kind == ControlFlowRegionKind.Filter || currentRegion.Kind == ControlFlowRegionKind.Finally); Debug.Assert(block == currentRegion.LastBlock); } #endif if (!block.HasCondition) { if (next.Destination == block) { continue; } RegionBuilder currentRegion = regionMap[block]; // Is this the only block in the region if (currentRegion.FirstBlock == currentRegion.LastBlock) { Debug.Assert(currentRegion.FirstBlock == block); Debug.Assert(!currentRegion.HasRegions); // Remove Try/Finally if Finally is empty if (currentRegion.Kind == ControlFlowRegionKind.Finally && next.Destination == null && next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling && !block.HasPredecessors) { // Nothing useful is happening in this finally, let's remove it Debug.Assert(currentRegion.Enclosing != null); RegionBuilder tryAndFinally = currentRegion.Enclosing; Debug.Assert(tryAndFinally.Kind == ControlFlowRegionKind.TryAndFinally); Debug.Assert(tryAndFinally.Regions!.Count == 2); RegionBuilder @try = tryAndFinally.Regions.First(); Debug.Assert(@try.Kind == ControlFlowRegionKind.Try); Debug.Assert(tryAndFinally.Regions.Last() == currentRegion); // If .try region has locals or methods or captures, let's convert it to .locals, otherwise drop it if (@try.Locals.IsEmpty && [email protected] && [email protected]) { Debug.Assert(@try.FirstBlock != null); i = @try.FirstBlock.Ordinal - 1; // restart at the first block of removed .try region MergeSubRegionAndFree(@try, blocks, regionMap); } else { @try.Kind = ControlFlowRegionKind.LocalLifetime; i--; // restart at the block that was following the tryAndFinally } MergeSubRegionAndFree(currentRegion, blocks, regionMap); Debug.Assert(tryAndFinally.Enclosing != null); RegionBuilder tryAndFinallyEnclosing = tryAndFinally.Enclosing; MergeSubRegionAndFree(tryAndFinally, blocks, regionMap); count--; Debug.Assert(regionMap[block] == tryAndFinallyEnclosing); removeBlock(block, tryAndFinallyEnclosing); anyRemoved = true; retry = true; } continue; } if (next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling) { Debug.Assert(block.HasCondition || block.BranchValue == null); Debug.Assert(next.Destination == null); // It is safe to drop an unreachable empty basic block if (block.HasPredecessors) { BasicBlockBuilder? predecessor = block.GetSingletonPredecessorOrDefault(); if (predecessor == null) { continue; } if (predecessor.Ordinal != i - 1 || predecessor.FallThrough.Destination != block || predecessor.Conditional.Destination == block || regionMap[predecessor] != currentRegion) { // Do not merge StructuredExceptionHandling into the middle of the filter or finally, // Do not merge StructuredExceptionHandling into conditional branch // Do not merge StructuredExceptionHandling into a different region // It is much easier to walk the graph when we can rely on the fact that a StructuredExceptionHandling // branch is only in the last block in the region, if it is present. continue; } predecessor.FallThrough = block.FallThrough; } } else { Debug.Assert(next.Kind == ControlFlowBranchSemantics.Regular || next.Kind == ControlFlowBranchSemantics.Return || next.Kind == ControlFlowBranchSemantics.Throw || next.Kind == ControlFlowBranchSemantics.Rethrow || next.Kind == ControlFlowBranchSemantics.Error || next.Kind == ControlFlowBranchSemantics.ProgramTermination); Debug.Assert(!block.HasCondition); // This is ensured by an "if" above. IOperation? value = block.BranchValue; RegionBuilder? implicitEntryRegion = tryGetImplicitEntryRegion(block, currentRegion); if (implicitEntryRegion != null) { // First blocks in filter/catch/finally do not capture all possible predecessors // Do not try to merge them, unless they are simply linked to the next block if (value != null || next.Destination != blocks[i + 1]) { continue; } Debug.Assert(implicitEntryRegion.LastBlock!.Ordinal >= next.Destination.Ordinal); } if (value != null) { if (!block.HasPredecessors && next.Kind == ControlFlowBranchSemantics.Return) { // Let's drop an unreachable compiler generated return that VB optimistically adds at the end of a method body Debug.Assert(next.Destination != null); if (next.Destination.Kind != BasicBlockKind.Exit || !value.IsImplicit || value.Kind != OperationKind.LocalReference || !((ILocalReferenceOperation)value).Local.IsFunctionValue) { continue; } } else { BasicBlockBuilder? predecessor = block.GetSingletonPredecessorOrDefault(); if (predecessor == null || predecessor.BranchValue != null || predecessor.Kind == BasicBlockKind.Entry || regionMap[predecessor] != currentRegion) { // Do not merge return/throw with expression with more than one predecessor // Do not merge return/throw into a block with conditional branch // Do not merge return/throw with expression with an entry block // Do not merge return/throw with expression into a different region continue; } Debug.Assert(predecessor.FallThrough.Destination == block); } } // For throw/re-throw assume there is no specific destination region RegionBuilder? destinationRegionOpt = next.Destination == null ? null : regionMap[next.Destination]; if (block.HasPredecessors) { if (predecessorsBuilder == null) { predecessorsBuilder = ArrayBuilder<BasicBlockBuilder>.GetInstance(); } else { predecessorsBuilder.Clear(); } block.GetPredecessors(predecessorsBuilder); // If source and destination are in different regions, it might // be unsafe to merge branches. if (currentRegion != destinationRegionOpt) { fromCurrent?.Clear(); fromDestination?.Clear(); if (!checkBranchesFromPredecessors(predecessorsBuilder, currentRegion, destinationRegionOpt)) { continue; } } foreach (BasicBlockBuilder predecessor in predecessorsBuilder) { if (tryMergeBranch(predecessor, ref predecessor.FallThrough, block)) { if (value != null) { Debug.Assert(predecessor.BranchValue == null); predecessor.BranchValue = value; } } if (tryMergeBranch(predecessor, ref predecessor.Conditional, block)) { Debug.Assert(value == null); } } } next.Destination?.RemovePredecessor(block); } i--; count--; removeBlock(block, currentRegion); anyRemoved = true; retry = true; } else { if (next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling) { continue; } Debug.Assert(next.Kind == ControlFlowBranchSemantics.Regular || next.Kind == ControlFlowBranchSemantics.Return || next.Kind == ControlFlowBranchSemantics.Throw || next.Kind == ControlFlowBranchSemantics.Rethrow || next.Kind == ControlFlowBranchSemantics.Error || next.Kind == ControlFlowBranchSemantics.ProgramTermination); BasicBlockBuilder? predecessor = block.GetSingletonPredecessorOrDefault(); if (predecessor == null) { continue; } RegionBuilder currentRegion = regionMap[block]; if (tryGetImplicitEntryRegion(block, currentRegion) != null) { // First blocks in filter/catch/finally do not capture all possible predecessors // Do not try to merge conditional branches in them continue; } if (predecessor.Kind != BasicBlockKind.Entry && predecessor.FallThrough.Destination == block && !predecessor.HasCondition && regionMap[predecessor] == currentRegion) { Debug.Assert(predecessor != block); Debug.Assert(predecessor.BranchValue == null); mergeBranch(predecessor, ref predecessor.FallThrough, ref next); next.Destination?.RemovePredecessor(block); predecessor.BranchValue = block.BranchValue; predecessor.ConditionKind = block.ConditionKind; predecessor.Conditional = block.Conditional; BasicBlockBuilder? destination = block.Conditional.Destination; if (destination != null) { destination.AddPredecessor(predecessor); destination.RemovePredecessor(block); } i--; count--; removeBlock(block, currentRegion); anyRemoved = true; retry = true; } } } blocks[0].Ordinal = 0; blocks[count].Ordinal = count; } while (retry); fromCurrent?.Free(); fromDestination?.Free(); fromPredecessor?.Free(); predecessorsBuilder?.Free(); return anyRemoved; RegionBuilder? tryGetImplicitEntryRegion(BasicBlockBuilder block, [DisallowNull] RegionBuilder? currentRegion) { do { if (currentRegion.FirstBlock != block) { return null; } switch (currentRegion.Kind) { case ControlFlowRegionKind.Filter: case ControlFlowRegionKind.Catch: case ControlFlowRegionKind.Finally: return currentRegion; } currentRegion = currentRegion.Enclosing; } while (currentRegion != null); return null; } void removeBlock(BasicBlockBuilder block, RegionBuilder region) { Debug.Assert(!region.IsEmpty); Debug.Assert(region.FirstBlock.Ordinal >= 0); Debug.Assert(region.FirstBlock.Ordinal <= region.LastBlock.Ordinal); Debug.Assert(region.FirstBlock.Ordinal <= block.Ordinal); Debug.Assert(block.Ordinal <= region.LastBlock.Ordinal); if (region.FirstBlock == block) { BasicBlockBuilder newFirst = blocks[block.Ordinal + 1]; region.FirstBlock = newFirst; Debug.Assert(region.Enclosing != null); RegionBuilder enclosing = region.Enclosing; while (enclosing != null && enclosing.FirstBlock == block) { enclosing.FirstBlock = newFirst; Debug.Assert(enclosing.Enclosing != null); enclosing = enclosing.Enclosing; } } else if (region.LastBlock == block) { BasicBlockBuilder newLast = blocks[block.Ordinal - 1]; region.LastBlock = newLast; Debug.Assert(region.Enclosing != null); RegionBuilder enclosing = region.Enclosing; while (enclosing != null && enclosing.LastBlock == block) { enclosing.LastBlock = newLast; Debug.Assert(enclosing.Enclosing != null); enclosing = enclosing.Enclosing; } } Debug.Assert(region.FirstBlock.Ordinal <= region.LastBlock.Ordinal); bool removed = regionMap.Remove(block); Debug.Assert(removed); Debug.Assert(blocks[block.Ordinal] == block); blocks.RemoveAt(block.Ordinal); block.Free(); } bool tryMergeBranch(BasicBlockBuilder predecessor, ref BasicBlockBuilder.Branch predecessorBranch, BasicBlockBuilder successor) { if (predecessorBranch.Destination == successor) { mergeBranch(predecessor, ref predecessorBranch, ref successor.FallThrough); return true; } return false; } void mergeBranch(BasicBlockBuilder predecessor, ref BasicBlockBuilder.Branch predecessorBranch, ref BasicBlockBuilder.Branch successorBranch) { predecessorBranch.Destination = successorBranch.Destination; successorBranch.Destination?.AddPredecessor(predecessor); Debug.Assert(predecessorBranch.Kind == ControlFlowBranchSemantics.Regular); predecessorBranch.Kind = successorBranch.Kind; } bool checkBranchesFromPredecessors(ArrayBuilder<BasicBlockBuilder> predecessors, RegionBuilder currentRegion, RegionBuilder? destinationRegionOpt) { foreach (BasicBlockBuilder predecessor in predecessors) { RegionBuilder predecessorRegion = regionMap[predecessor]; // If source and destination are in different regions, it might // be unsafe to merge branches. if (predecessorRegion != currentRegion) { if (destinationRegionOpt == null) { // destination is unknown and predecessor is in different region, do not merge return false; } fromPredecessor?.Clear(); collectAncestorsAndSelf(currentRegion, ref fromCurrent); collectAncestorsAndSelf(destinationRegionOpt, ref fromDestination); collectAncestorsAndSelf(predecessorRegion, ref fromPredecessor); // On the way from predecessor directly to the destination, are we going leave the same regions as on the way // from predecessor to the current block and then to the destination? int lastLeftRegionOnTheWayFromCurrentToDestination = getIndexOfLastLeftRegion(fromCurrent, fromDestination); int lastLeftRegionOnTheWayFromPredecessorToDestination = getIndexOfLastLeftRegion(fromPredecessor, fromDestination); int lastLeftRegionOnTheWayFromPredecessorToCurrentBlock = getIndexOfLastLeftRegion(fromPredecessor, fromCurrent); // Since we are navigating up and down the tree and only movements up are significant, if we made the same number // of movements up during direct and indirect transition, we must have made the same movements up. if ((fromPredecessor.Count - lastLeftRegionOnTheWayFromPredecessorToCurrentBlock + fromCurrent.Count - lastLeftRegionOnTheWayFromCurrentToDestination) != (fromPredecessor.Count - lastLeftRegionOnTheWayFromPredecessorToDestination)) { // We have different transitions return false; } } else if (predecessor.Kind == BasicBlockKind.Entry && destinationRegionOpt == null) { // Do not merge throw into an entry block return false; } } return true; } void collectAncestorsAndSelf([DisallowNull] RegionBuilder? from, [NotNull] ref ArrayBuilder<RegionBuilder>? builder) { if (builder == null) { builder = ArrayBuilder<RegionBuilder>.GetInstance(); } else if (builder.Count != 0) { return; } do { builder.Add(from); from = from.Enclosing; } while (from != null); builder.ReverseContents(); } // Can return index beyond bounds of "from" when no regions will be left. int getIndexOfLastLeftRegion(ArrayBuilder<RegionBuilder> from, ArrayBuilder<RegionBuilder> to) { int mismatch = 0; while (mismatch < from.Count && mismatch < to.Count && from[mismatch] == to[mismatch]) { mismatch++; } return mismatch; } } /// <summary> /// Deal with labeled blocks that were not added to the graph because labels were never found /// </summary> private static void CheckUnresolvedBranches(ArrayBuilder<BasicBlockBuilder> blocks, PooledDictionary<ILabelSymbol, BasicBlockBuilder>? labeledBlocks) { if (labeledBlocks == null) { return; } PooledHashSet<BasicBlockBuilder>? unresolved = null; foreach (BasicBlockBuilder labeled in labeledBlocks.Values) { if (labeled.Ordinal == -1) { if (unresolved == null) { unresolved = PooledHashSet<BasicBlockBuilder>.GetInstance(); } unresolved.Add(labeled); } } if (unresolved == null) { return; } // Mark branches using unresolved labels as errors. foreach (BasicBlockBuilder block in blocks) { fixupBranch(ref block.Conditional); fixupBranch(ref block.FallThrough); } unresolved.Free(); return; void fixupBranch(ref BasicBlockBuilder.Branch branch) { if (branch.Destination != null && unresolved.Contains(branch.Destination)) { Debug.Assert(branch.Kind == ControlFlowBranchSemantics.Regular); branch.Destination = null; branch.Kind = ControlFlowBranchSemantics.Error; } } } private void VisitStatement(IOperation? operation) { #if DEBUG int stackDepth = _evalStack.Count; Debug.Assert(stackDepth == 0 || _evalStack.Peek().frameOpt != null); #endif if (operation == null) { return; } IOperation? saveCurrentStatement = _currentStatement; _currentStatement = operation; EvalStackFrame frame = PushStackFrame(); AddStatement(base.Visit(operation, null)); PopStackFrameAndLeaveRegion(frame); #if DEBUG Debug.Assert(_evalStack.Count == stackDepth); Debug.Assert(stackDepth == 0 || _evalStack.Peek().frameOpt != null); #endif _currentStatement = saveCurrentStatement; } private BasicBlockBuilder CurrentBasicBlock { get { if (_currentBasicBlock == null) { AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); } return _currentBasicBlock; } } private void AddStatement( IOperation? statement #if DEBUG , bool spillingTheStack = false #endif ) { #if DEBUG Debug.Assert(spillingTheStack || _evalStack.All( slot => slot.operationOpt == null || slot.operationOpt.Kind == OperationKind.FlowCaptureReference || slot.operationOpt.Kind == OperationKind.DeclarationExpression || slot.operationOpt.Kind == OperationKind.Discard || slot.operationOpt.Kind == OperationKind.OmittedArgument)); #endif if (statement == null) { return; } Operation.SetParentOperation(statement, null); CurrentBasicBlock.AddStatement(statement); } [MemberNotNull(nameof(_currentBasicBlock))] private void AppendNewBlock(BasicBlockBuilder block, bool linkToPrevious = true) { Debug.Assert(block != null); Debug.Assert(_currentRegion != null); if (linkToPrevious) { BasicBlockBuilder prevBlock = _blocks.Last(); if (prevBlock.FallThrough.Destination == null) { LinkBlocks(prevBlock, block); } } if (block.Ordinal != -1) { throw ExceptionUtilities.Unreachable; } block.Ordinal = _blocks.Count; _blocks.Add(block); _currentBasicBlock = block; _currentRegion.ExtendToInclude(block); _regionMap.Add(block, _currentRegion); } private void EnterRegion(RegionBuilder region, bool spillingStack = false) { if (!spillingStack) { // Make sure all pending stack spilling regions are realised SpillEvalStack(); #if DEBUG Debug.Assert(_evalStack.Count == _startSpillingAt); VerifySpilledStackFrames(); #endif } _currentRegion?.Add(region); _currentRegion = region; _currentBasicBlock = null; } private void LeaveRegion() { // Ensure there is at least one block in the region Debug.Assert(_currentRegion != null); if (_currentRegion.IsEmpty) { AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); } RegionBuilder enclosed = _currentRegion; #if DEBUG // We shouldn't be leaving regions that are still associated with stack frames foreach ((EvalStackFrame? frameOpt, IOperation? operationOpt) in _evalStack) { Debug.Assert((frameOpt == null) != (operationOpt == null)); if (frameOpt != null) { Debug.Assert(enclosed != frameOpt.RegionBuilderOpt); } } #endif _currentRegion = _currentRegion.Enclosing; Debug.Assert(enclosed.LastBlock != null); _currentRegion?.ExtendToInclude(enclosed.LastBlock); _currentBasicBlock = null; } private static void LinkBlocks(BasicBlockBuilder prevBlock, BasicBlockBuilder nextBlock, ControlFlowBranchSemantics branchKind = ControlFlowBranchSemantics.Regular) { Debug.Assert(prevBlock.HasCondition || prevBlock.BranchValue == null); Debug.Assert(prevBlock.FallThrough.Destination == null); prevBlock.FallThrough.Destination = nextBlock; prevBlock.FallThrough.Kind = branchKind; nextBlock.AddPredecessor(prevBlock); } private void UnconditionalBranch(BasicBlockBuilder nextBlock) { LinkBlocks(CurrentBasicBlock, nextBlock); _currentBasicBlock = null; } public override IOperation? VisitBlock(IBlockOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals)); VisitStatements(operation.Operations); LeaveRegion(); return FinishVisitingStatement(operation); } private void StartVisitingStatement(IOperation operation) { Debug.Assert(_currentStatement == operation); Debug.Assert(_evalStack.Count == 0 || _evalStack.Peek().frameOpt != null); SpillEvalStack(); } [return: NotNullIfNotNull("result")] private IOperation? FinishVisitingStatement(IOperation originalOperation, IOperation? result = null) { Debug.Assert(((Operation)originalOperation).OwningSemanticModel != null, "Not an original node."); Debug.Assert(_currentStatement == originalOperation); Debug.Assert(_evalStack.Count == 0 || _evalStack.Peek().frameOpt != null); if (_currentStatement == originalOperation) { return result; } return result ?? MakeInvalidOperation(originalOperation.Syntax, originalOperation.Type, ImmutableArray<IOperation>.Empty); } private void VisitStatements(ImmutableArray<IOperation> statements) { for (int i = 0; i < statements.Length; i++) { if (VisitStatementsOneOrAll(statements[i], statements, i)) { break; } } } /// <summary> /// Either visits a single operation, or a using <see cref="IVariableDeclarationGroupOperation"/> and all subsequent statements /// </summary> /// <param name="operation">The statement to visit</param> /// <param name="statements">All statements in the block containing this node</param> /// <param name="startIndex">The current statement being visited in <paramref name="statements"/></param> /// <returns>True if this visited all of the statements</returns> /// <remarks> /// The operation being visited is not necessarily equal to statements[startIndex]. /// When traversing down a set of labels, we set operation to the label.Operation and recurse, but statements[startIndex] still refers to the original parent label /// as we haven't actually moved down the original statement list /// </remarks> private bool VisitStatementsOneOrAll(IOperation? operation, ImmutableArray<IOperation> statements, int startIndex) { switch (operation) { case IUsingDeclarationOperation usingDeclarationOperation: VisitUsingVariableDeclarationOperation(usingDeclarationOperation, statements.AsSpan()[(startIndex + 1)..]); return true; case ILabeledOperation { Operation: { } } labelOperation: return visitPossibleUsingDeclarationInLabel(labelOperation); default: VisitStatement(operation); return false; } bool visitPossibleUsingDeclarationInLabel(ILabeledOperation labelOperation) { var savedCurrentStatement = _currentStatement; _currentStatement = labelOperation; StartVisitingStatement(labelOperation); VisitLabel(labelOperation.Label); bool visitedAll = VisitStatementsOneOrAll(labelOperation.Operation, statements, startIndex); FinishVisitingStatement(labelOperation); _currentStatement = savedCurrentStatement; return visitedAll; } } internal override IOperation? VisitWithStatement(IWithStatementOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); ImplicitInstanceInfo previousInitializedInstance = _currentImplicitInstance; _currentImplicitInstance = new ImplicitInstanceInfo(VisitAndCapture(operation.Value)); VisitStatement(operation.Body); _currentImplicitInstance = previousInitializedInstance; return FinishVisitingStatement(operation); } public override IOperation? VisitConstructorBodyOperation(IConstructorBodyOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals)); if (operation.Initializer != null) { VisitStatement(operation.Initializer); } VisitMethodBodyBaseOperation(operation); LeaveRegion(); return FinishVisitingStatement(operation); } public override IOperation? VisitMethodBodyOperation(IMethodBodyOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); VisitMethodBodyBaseOperation(operation); return FinishVisitingStatement(operation); } private void VisitMethodBodyBaseOperation(IMethodBodyBaseOperation operation) { Debug.Assert(_currentStatement == operation); VisitMethodBodies(operation.BlockBody, operation.ExpressionBody); } private void VisitMethodBodies(IBlockOperation? blockBody, IBlockOperation? expressionBody) { if (blockBody != null) { VisitStatement(blockBody); // Check for error case with non-null BlockBody and non-null ExpressionBody. if (expressionBody != null) { // Link last block of visited BlockBody to the exit block. UnconditionalBranch(_exit); // Generate a special region for unreachable erroneous expression body. EnterRegion(new RegionBuilder(ControlFlowRegionKind.ErroneousBody)); VisitStatement(expressionBody); LeaveRegion(); } } else if (expressionBody != null) { VisitStatement(expressionBody); } } public override IOperation? VisitConditional(IConditionalOperation operation, int? captureIdForResult) { if (operation == _currentStatement) { if (operation.WhenFalse == null) { // if (condition) // consequence; // // becomes // // GotoIfFalse condition afterif; // consequence; // afterif: BasicBlockBuilder? afterIf = null; VisitConditionalBranch(operation.Condition, ref afterIf, jumpIfTrue: false); VisitStatement(operation.WhenTrue); AppendNewBlock(afterIf); } else { // if (condition) // consequence; // else // alternative // // becomes // // GotoIfFalse condition alt; // consequence // goto afterif; // alt: // alternative; // afterif: BasicBlockBuilder? whenFalse = null; VisitConditionalBranch(operation.Condition, ref whenFalse, jumpIfTrue: false); VisitStatement(operation.WhenTrue); var afterIf = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); VisitStatement(operation.WhenFalse); AppendNewBlock(afterIf); } return null; } else { // condition ? consequence : alternative // // becomes // // GotoIfFalse condition alt; // capture = consequence // goto afterif; // alt: // capture = alternative; // afterif: // result = capture Debug.Assert(operation is { WhenTrue: not null, WhenFalse: not null }); SpillEvalStack(); BasicBlockBuilder? whenFalse = null; VisitConditionalBranch(operation.Condition, ref whenFalse, jumpIfTrue: false); var afterIf = new BasicBlockBuilder(BasicBlockKind.Block); IOperation result; // Specially handle cases with "throw" as operation.WhenTrue or operation.WhenFalse. We don't need to create an additional // capture for the result because there won't be any result from the throwing branches. if (operation.WhenTrue is IConversionOperation whenTrueConversion && whenTrueConversion.Operand.Kind == OperationKind.Throw) { IOperation? rewrittenThrow = base.Visit(whenTrueConversion.Operand, null); Debug.Assert(rewrittenThrow!.Kind == OperationKind.None); Debug.Assert(rewrittenThrow.Children.IsEmpty()); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); result = VisitRequired(operation.WhenFalse); } else if (operation.WhenFalse is IConversionOperation whenFalseConversion && whenFalseConversion.Operand.Kind == OperationKind.Throw) { result = VisitRequired(operation.WhenTrue); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); IOperation rewrittenThrow = BaseVisitRequired(whenFalseConversion.Operand, null); Debug.Assert(rewrittenThrow.Kind == OperationKind.None); Debug.Assert(rewrittenThrow.Children.IsEmpty()); } else { var resultCaptureRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, isStackSpillRegion: true); EnterRegion(resultCaptureRegion); int captureId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); VisitAndCapture(operation.WhenTrue, captureId); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); VisitAndCapture(operation.WhenFalse, captureId); result = GetCaptureReference(captureId, operation); } AppendNewBlock(afterIf); return result; } } private void VisitAndCapture(IOperation operation, int captureId) { EvalStackFrame frame = PushStackFrame(); IOperation result = BaseVisitRequired(operation, captureId); PopStackFrame(frame); CaptureResultIfNotAlready(operation.Syntax, captureId, result); LeaveRegionIfAny(frame); } private IOperation VisitAndCapture(IOperation operation) { EvalStackFrame frame = PushStackFrame(); PushOperand(BaseVisitRequired(operation, null)); SpillEvalStack(); return PopStackFrame(frame, PopOperand()); } private void CaptureResultIfNotAlready(SyntaxNode syntax, int captureId, IOperation result) { Debug.Assert(_startSpillingAt == _evalStack.Count); if (result.Kind != OperationKind.FlowCaptureReference || captureId != ((IFlowCaptureReferenceOperation)result).Id.Value) { SpillEvalStack(); AddStatement(new FlowCaptureOperation(captureId, syntax, result)); } } /// <summary> /// This class captures information about beginning of stack frame /// and corresponding <see cref="RegionBuilder"/> if one was allocated to /// track <see cref="CaptureId"/>s used by the stack spilling, etc. /// Do not create instances of this type manually, use <see cref="PushStackFrame"/> /// helper instead. Also, do not assign <see cref="RegionBuilderOpt"/> explicitly. /// Let the builder machinery do this when appropriate. /// </summary> private class EvalStackFrame { private RegionBuilder? _lazyRegionBuilder; public RegionBuilder? RegionBuilderOpt { get { return _lazyRegionBuilder; } set { Debug.Assert(_lazyRegionBuilder == null); Debug.Assert(value != null); _lazyRegionBuilder = value; } } } private EvalStackFrame PushStackFrame() { var frame = new EvalStackFrame(); _evalStack.Push((frame, operationOpt: null)); return frame; } private void PopStackFrame(EvalStackFrame frame, bool mergeNestedRegions = true) { Debug.Assert(frame != null); int stackDepth = _evalStack.Count; Debug.Assert(_startSpillingAt <= stackDepth); if (_startSpillingAt == stackDepth) { _startSpillingAt--; } (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack.Pop(); Debug.Assert(frame == frameOpt); Debug.Assert(operationOpt == null); if (frame.RegionBuilderOpt != null && mergeNestedRegions) { while (_currentRegion != frame.RegionBuilderOpt) { Debug.Assert(_currentRegion != null); RegionBuilder toMerge = _currentRegion; Debug.Assert(toMerge.Enclosing != null); _currentRegion = toMerge.Enclosing; Debug.Assert(toMerge.IsStackSpillRegion); Debug.Assert(!toMerge.HasLocalFunctions); Debug.Assert(toMerge.Locals.IsEmpty); _currentRegion.AddCaptureIds(toMerge.CaptureIds); // This region can be empty in certain error scenarios, such as `new T {}`, where T does not // have a class constraint. There are no arguments or initializers, so nothing will have // been put into the region at this point if (!toMerge.IsEmpty) { _currentRegion.ExtendToInclude(toMerge.LastBlock); } MergeSubRegionAndFree(toMerge, _blocks, _regionMap, canHaveEmptyRegion: true); } } } private void PopStackFrameAndLeaveRegion(EvalStackFrame frame) { PopStackFrame(frame); LeaveRegionIfAny(frame); } private void LeaveRegionIfAny(EvalStackFrame frame) { RegionBuilder? toLeave = frame.RegionBuilderOpt; if (toLeave != null) { while (_currentRegion != toLeave) { Debug.Assert(_currentRegion!.IsStackSpillRegion); LeaveRegion(); } LeaveRegion(); } } private T PopStackFrame<T>(EvalStackFrame frame, T value) { PopStackFrame(frame); return value; } private void LeaveRegionsUpTo(RegionBuilder resultCaptureRegion) { while (_currentRegion != resultCaptureRegion) { LeaveRegion(); } } private int GetNextCaptureId(RegionBuilder owner) { Debug.Assert(owner != null); int captureId = _captureIdDispenser.GetNextId(); owner.AddCaptureId(captureId); return captureId; } private void SpillEvalStack() { Debug.Assert(_startSpillingAt <= _evalStack.Count); #if DEBUG VerifySpilledStackFrames(); #endif int currentFrameIndex = -1; for (int i = _startSpillingAt - 1; i >= 0; i--) { (EvalStackFrame? frameOpt, _) = _evalStack[i]; if (frameOpt != null) { currentFrameIndex = i; Debug.Assert(frameOpt.RegionBuilderOpt != null); break; } } for (int i = _startSpillingAt; i < _evalStack.Count; i++) { (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack[i]; Debug.Assert((frameOpt == null) != (operationOpt == null)); if (frameOpt != null) { currentFrameIndex = i; Debug.Assert(frameOpt.RegionBuilderOpt == null); frameOpt.RegionBuilderOpt = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, isStackSpillRegion: true); EnterRegion(frameOpt.RegionBuilderOpt, spillingStack: true); continue; } Debug.Assert(operationOpt != null); // Declarations cannot have control flow, so we don't need to spill them. if (operationOpt.Kind != OperationKind.FlowCaptureReference && operationOpt.Kind != OperationKind.DeclarationExpression && operationOpt.Kind != OperationKind.Discard && operationOpt.Kind != OperationKind.OmittedArgument) { // Here we need to decide what region should own the new capture. Due to the spilling operations occurred before, // we currently might be in a region that is not associated with the stack frame we are in, but it is one of its // directly or indirectly nested regions. The operation that we are about to spill is likely to remove references // to some captures from the stack. That means that, after the spilling, we should be able to leave the spill // regions that no longer own captures referenced on the stack. The new capture that we create, should belong to // the region that will become current after that. Here we are trying to compute what will be that region. // Obviously, we shouldn’t be leaving the region associated with the frame. EvalStackFrame? currentFrame = _evalStack[currentFrameIndex].frameOpt; Debug.Assert(currentFrame != null); RegionBuilder? currentSpillRegion = currentFrame.RegionBuilderOpt; Debug.Assert(currentSpillRegion != null); if (_currentRegion != currentSpillRegion) { var idsStillOnTheStack = PooledHashSet<CaptureId>.GetInstance(); for (int j = currentFrameIndex + 1; j < _evalStack.Count; j++) { IOperation? operation = _evalStack[j].operationOpt; if (operation != null) { if (j < i) { if (operation is IFlowCaptureReferenceOperation reference) { idsStillOnTheStack.Add(reference.Id); } } else if (j > i) { foreach (IFlowCaptureReferenceOperation reference in operation.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { idsStillOnTheStack.Add(reference.Id); } } } } RegionBuilder candidate = CurrentRegionRequired; do { Debug.Assert(candidate.IsStackSpillRegion); if (candidate.HasCaptureIds && candidate.CaptureIds.Any((id, set) => set.Contains(id), idsStillOnTheStack)) { currentSpillRegion = candidate; break; } Debug.Assert(candidate.Enclosing != null); candidate = candidate.Enclosing; } while (candidate != currentSpillRegion); idsStillOnTheStack.Free(); } int captureId = GetNextCaptureId(currentSpillRegion); AddStatement(new FlowCaptureOperation(captureId, operationOpt.Syntax, operationOpt) #if DEBUG , spillingTheStack: true #endif ); _evalStack[i] = (frameOpt: null, operationOpt: GetCaptureReference(captureId, operationOpt)); while (_currentRegion != currentSpillRegion) { Debug.Assert(CurrentRegionRequired.IsStackSpillRegion); LeaveRegion(); } } } _startSpillingAt = _evalStack.Count; } #if DEBUG private void VerifySpilledStackFrames() { for (int i = 0; i < _startSpillingAt; i++) { (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack[i]; if (frameOpt != null) { Debug.Assert(operationOpt == null); Debug.Assert(frameOpt.RegionBuilderOpt != null); } else { Debug.Assert(operationOpt != null); } } } #endif private void PushOperand(IOperation operation) { Debug.Assert(_evalStack.Count != 0); Debug.Assert(_evalStack.First().frameOpt != null); Debug.Assert(_evalStack.First().operationOpt == null); Debug.Assert(_startSpillingAt <= _evalStack.Count); Debug.Assert(operation != null); _evalStack.Push((frameOpt: null, operation)); } private IOperation PopOperand() { int stackDepth = _evalStack.Count; Debug.Assert(_startSpillingAt <= stackDepth); if (_startSpillingAt == stackDepth) { _startSpillingAt--; } (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack.Pop(); Debug.Assert(frameOpt == null); Debug.Assert(operationOpt != null); return operationOpt; } private IOperation PeekOperand() { Debug.Assert(_startSpillingAt <= _evalStack.Count); (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack.Peek(); Debug.Assert(frameOpt == null); Debug.Assert(operationOpt != null); return operationOpt; } private void VisitAndPushArray<T>(ImmutableArray<T> array, Func<T, IOperation>? unwrapper = null) where T : IOperation { Debug.Assert(unwrapper != null || typeof(T) == typeof(IOperation)); foreach (var element in array) { PushOperand(VisitRequired(unwrapper == null ? element : unwrapper(element))); } } private ImmutableArray<T> PopArray<T>(ImmutableArray<T> originalArray, Func<IOperation, int, ImmutableArray<T>, T>? wrapper = null) where T : IOperation { Debug.Assert(wrapper != null || typeof(T) == typeof(IOperation)); int numElements = originalArray.Length; if (numElements == 0) { return ImmutableArray<T>.Empty; } else { var builder = ArrayBuilder<T>.GetInstance(numElements); // Iterate in reverse order so the index corresponds to the original index when pushed onto the stack for (int i = numElements - 1; i >= 0; i--) { IOperation visitedElement = PopOperand(); builder.Add(wrapper != null ? wrapper(visitedElement, i, originalArray) : (T)visitedElement); } builder.ReverseContents(); return builder.ToImmutableAndFree(); } } private ImmutableArray<T> VisitArray<T>(ImmutableArray<T> originalArray, Func<T, IOperation>? unwrapper = null, Func<IOperation, int, ImmutableArray<T>, T>? wrapper = null) where T : IOperation { #if DEBUG int stackSizeBefore = _evalStack.Count; #endif VisitAndPushArray(originalArray, unwrapper); ImmutableArray<T> visitedArray = PopArray(originalArray, wrapper); #if DEBUG Debug.Assert(stackSizeBefore == _evalStack.Count); #endif return visitedArray; } private ImmutableArray<IArgumentOperation> VisitArguments(ImmutableArray<IArgumentOperation> arguments) { return VisitArray(arguments, UnwrapArgument, RewriteArgumentFromArray); } private static IOperation UnwrapArgument(IArgumentOperation argument) { return argument.Value; } private IArgumentOperation RewriteArgumentFromArray(IOperation visitedArgument, int index, ImmutableArray<IArgumentOperation> args) { Debug.Assert(index >= 0 && index < args.Length); var originalArgument = (ArgumentOperation)args[index]; return new ArgumentOperation(originalArgument.ArgumentKind, originalArgument.Parameter, visitedArgument, originalArgument.InConversionConvertible, originalArgument.OutConversionConvertible, semanticModel: null, originalArgument.Syntax, IsImplicit(originalArgument)); } public override IOperation VisitSimpleAssignment(ISimpleAssignmentOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.Target)); IOperation value = VisitRequired(operation.Value); return PopStackFrame(frame, new SimpleAssignmentOperation(operation.IsRef, PopOperand(), value, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); } public override IOperation VisitCompoundAssignment(ICompoundAssignmentOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); var compoundAssignment = (CompoundAssignmentOperation)operation; PushOperand(VisitRequired(compoundAssignment.Target)); IOperation value = VisitRequired(compoundAssignment.Value); return PopStackFrame(frame, new CompoundAssignmentOperation(compoundAssignment.InConversionConvertible, compoundAssignment.OutConversionConvertible, operation.OperatorKind, operation.IsLifted, operation.IsChecked, operation.OperatorMethod, PopOperand(), value, semanticModel: null, syntax: operation.Syntax, type: operation.Type, isImplicit: IsImplicit(operation))); } public override IOperation VisitArrayElementReference(IArrayElementReferenceOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.ArrayReference)); ImmutableArray<IOperation> visitedIndices = VisitArray(operation.Indices); IOperation visitedArrayReference = PopOperand(); PopStackFrame(frame); return new ArrayElementReferenceOperation(visitedArrayReference, visitedIndices, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } private static bool IsConditional(IBinaryOperation operation) { switch (operation.OperatorKind) { case BinaryOperatorKind.ConditionalOr: case BinaryOperatorKind.ConditionalAnd: return true; } return false; } public override IOperation VisitBinaryOperator(IBinaryOperation operation, int? captureIdForResult) { if (IsConditional(operation)) { if (operation.OperatorMethod == null) { if (ITypeSymbolHelpers.IsBooleanType(operation.Type) && ITypeSymbolHelpers.IsBooleanType(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsBooleanType(operation.RightOperand.Type)) { // Regular boolean logic return VisitBinaryConditionalOperator(operation, sense: true, captureIdForResult, fallToTrueOpt: null, fallToFalseOpt: null); } else if (operation.IsLifted && ITypeSymbolHelpers.IsNullableOfBoolean(operation.Type) && ITypeSymbolHelpers.IsNullableOfBoolean(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsNullableOfBoolean(operation.RightOperand.Type)) { // Three-value boolean logic (VB). return VisitNullableBinaryConditionalOperator(operation, captureIdForResult); } else if (ITypeSymbolHelpers.IsObjectType(operation.Type) && ITypeSymbolHelpers.IsObjectType(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsObjectType(operation.RightOperand.Type)) { return VisitObjectBinaryConditionalOperator(operation, captureIdForResult); } else if (ITypeSymbolHelpers.IsDynamicType(operation.Type) && (ITypeSymbolHelpers.IsDynamicType(operation.LeftOperand.Type) || ITypeSymbolHelpers.IsDynamicType(operation.RightOperand.Type))) { return VisitDynamicBinaryConditionalOperator(operation, captureIdForResult); } } else { return VisitUserDefinedBinaryConditionalOperator(operation, captureIdForResult); } } EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.LeftOperand)); IOperation rightOperand = VisitRequired(operation.RightOperand); return PopStackFrame(frame, new BinaryOperation(operation.OperatorKind, PopOperand(), rightOperand, operation.IsLifted, operation.IsChecked, operation.IsCompareText, operation.OperatorMethod, ((BinaryOperation)operation).UnaryOperatorMethod, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); } public override IOperation VisitTupleBinaryOperator(ITupleBinaryOperation operation, int? captureIdForResult) { (IOperation visitedLeft, IOperation visitedRight) = VisitPreservingTupleOperations(operation.LeftOperand, operation.RightOperand); return new TupleBinaryOperation(operation.OperatorKind, visitedLeft, visitedRight, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitUnaryOperator(IUnaryOperation operation, int? captureIdForResult) { if (IsBooleanLogicalNot(operation)) { return VisitConditionalExpression(operation, sense: true, captureIdForResult, fallToTrueOpt: null, fallToFalseOpt: null); } return new UnaryOperation(operation.OperatorKind, VisitRequired(operation.Operand), operation.IsLifted, operation.IsChecked, operation.OperatorMethod, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } private static bool IsBooleanLogicalNot(IUnaryOperation operation) { return operation.OperatorKind == UnaryOperatorKind.Not && operation.OperatorMethod == null && ITypeSymbolHelpers.IsBooleanType(operation.Type) && ITypeSymbolHelpers.IsBooleanType(operation.Operand.Type); } private static bool CalculateAndOrSense(IBinaryOperation binOp, bool sense) { switch (binOp.OperatorKind) { case BinaryOperatorKind.ConditionalOr: // Rewrite (a || b) as ~(~a && ~b) return !sense; case BinaryOperatorKind.ConditionalAnd: return sense; default: throw ExceptionUtilities.UnexpectedValue(binOp.OperatorKind); } } private IOperation VisitBinaryConditionalOperator(IBinaryOperation binOp, bool sense, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) { // ~(a && b) is equivalent to (~a || ~b) if (!CalculateAndOrSense(binOp, sense)) { // generate (~a || ~b) return VisitShortCircuitingOperator(binOp, sense: sense, stopSense: sense, stopValue: true, captureIdForResult, fallToTrueOpt, fallToFalseOpt); } else { // generate (a && b) return VisitShortCircuitingOperator(binOp, sense: sense, stopSense: !sense, stopValue: false, captureIdForResult, fallToTrueOpt, fallToFalseOpt); } } private IOperation VisitNullableBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) { SpillEvalStack(); IOperation left = binOp.LeftOperand; IOperation right = binOp.RightOperand; IOperation condition; bool isAndAlso = CalculateAndOrSense(binOp, true); // case BinaryOperatorKind.ConditionalOr: // Dim result As Boolean? // // If left.GetValueOrDefault Then // GoTo resultIsLeft // End If // // If Not ((Not right).GetValueOrDefault) Then // result = right // GoTo done // End If // //resultIsLeft: // result = left // //done: // Return result // case BinaryOperatorKind.ConditionalAnd: // Dim result As Boolean? // // If (Not left).GetValueOrDefault() Then // GoTo resultIsLeft // End If // // If Not (right.GetValueOrDefault()) Then // result = right // GoTo done // End If // //resultIsLeft: // result = left // //done: // Return result var resultCaptureRegion = CurrentRegionRequired; var done = new BasicBlockBuilder(BasicBlockKind.Block); var checkRight = new BasicBlockBuilder(BasicBlockKind.Block); var resultIsLeft = new BasicBlockBuilder(BasicBlockKind.Block); IOperation capturedLeft = VisitAndCapture(left); condition = capturedLeft; if (isAndAlso) { condition = negateNullable(condition); } condition = CallNullableMember(condition, SpecialMember.System_Nullable_T_GetValueOrDefault); ConditionalBranch(condition, jumpIfTrue: true, resultIsLeft); UnconditionalBranch(checkRight); int resultId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); AppendNewBlock(checkRight); EvalStackFrame frame = PushStackFrame(); IOperation capturedRight = VisitAndCapture(right); condition = capturedRight; if (!isAndAlso) { condition = negateNullable(condition); } condition = CallNullableMember(condition, SpecialMember.System_Nullable_T_GetValueOrDefault); ConditionalBranch(condition, jumpIfTrue: true, resultIsLeft); _currentBasicBlock = null; AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, OperationCloner.CloneOperation(capturedRight))); UnconditionalBranch(done); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(resultIsLeft); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, OperationCloner.CloneOperation(capturedLeft))); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(done); return GetCaptureReference(resultId, binOp); IOperation negateNullable(IOperation operand) { return new UnaryOperation(UnaryOperatorKind.Not, operand, isLifted: true, isChecked: false, operatorMethod: null, semanticModel: null, operand.Syntax, operand.Type, constantValue: null, isImplicit: true); } } private IOperation VisitObjectBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) { SpillEvalStack(); INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); IOperation left = binOp.LeftOperand; IOperation right = binOp.RightOperand; IOperation condition; bool isAndAlso = CalculateAndOrSense(binOp, true); var done = new BasicBlockBuilder(BasicBlockKind.Block); var checkRight = new BasicBlockBuilder(BasicBlockKind.Block); EvalStackFrame frame = PushStackFrame(); condition = CreateConversion(VisitRequired(left), booleanType); ConditionalBranch(condition, jumpIfTrue: isAndAlso, checkRight); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); var resultCaptureRegion = CurrentRegionRequired; int resultId = GetNextCaptureId(resultCaptureRegion); ConstantValue constantValue = ConstantValue.Create(!isAndAlso); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, new LiteralOperation(semanticModel: null, left.Syntax, booleanType, constantValue, isImplicit: true))); UnconditionalBranch(done); AppendNewBlock(checkRight); frame = PushStackFrame(); condition = CreateConversion(VisitRequired(right), booleanType); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, condition)); PopStackFrame(frame); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(done); condition = new FlowCaptureReferenceOperation(resultId, binOp.Syntax, booleanType, constantValue: null); Debug.Assert(binOp.Type is not null); return new ConversionOperation(condition, _compilation.ClassifyConvertibleConversion(condition, binOp.Type, out _), isTryCast: false, isChecked: false, semanticModel: null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), isImplicit: true); } private IOperation CreateConversion(IOperation operand, ITypeSymbol type) { return new ConversionOperation(operand, _compilation.ClassifyConvertibleConversion(operand, type, out ConstantValue? constantValue), isTryCast: false, isChecked: false, semanticModel: null, operand.Syntax, type, constantValue, isImplicit: true); } private IOperation VisitDynamicBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) { SpillEvalStack(); Debug.Assert(binOp.Type is not null); var resultCaptureRegion = CurrentRegionRequired; INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); IOperation left = binOp.LeftOperand; IOperation right = binOp.RightOperand; IMethodSymbol? unaryOperatorMethod = ((BinaryOperation)binOp).UnaryOperatorMethod; bool isAndAlso = CalculateAndOrSense(binOp, true); bool jumpIfTrue; IOperation condition; // Dynamic logical && and || operators are lowered as follows: // left && right -> IsFalse(left) ? left : And(left, right) // left || right -> IsTrue(left) ? left : Or(left, right) var done = new BasicBlockBuilder(BasicBlockKind.Block); var doBitWise = new BasicBlockBuilder(BasicBlockKind.Block); IOperation capturedLeft = VisitAndCapture(left); condition = capturedLeft; if (ITypeSymbolHelpers.IsBooleanType(left.Type)) { Debug.Assert(unaryOperatorMethod == null); jumpIfTrue = isAndAlso; } else if (ITypeSymbolHelpers.IsDynamicType(left.Type) || unaryOperatorMethod != null) { jumpIfTrue = false; if (unaryOperatorMethod == null || (ITypeSymbolHelpers.IsBooleanType(unaryOperatorMethod.ReturnType) && (ITypeSymbolHelpers.IsNullableType(left.Type) || !ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)))) { condition = new UnaryOperation(isAndAlso ? UnaryOperatorKind.False : UnaryOperatorKind.True, condition, isLifted: false, isChecked: false, operatorMethod: unaryOperatorMethod, semanticModel: null, condition.Syntax, booleanType, constantValue: null, isImplicit: true); } else { condition = MakeInvalidOperation(booleanType, condition); } } else { // This is either an error case, or left is implicitly convertible to boolean condition = CreateConversion(condition, booleanType); jumpIfTrue = isAndAlso; } ConditionalBranch(condition, jumpIfTrue, doBitWise); _currentBasicBlock = null; int resultId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); IOperation resultFromLeft = OperationCloner.CloneOperation(capturedLeft); if (!ITypeSymbolHelpers.IsDynamicType(left.Type)) { resultFromLeft = CreateConversion(resultFromLeft, binOp.Type); } AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, resultFromLeft)); UnconditionalBranch(done); AppendNewBlock(doBitWise); EvalStackFrame frame = PushStackFrame(); PushOperand(OperationCloner.CloneOperation(capturedLeft)); IOperation visitedRight = VisitRequired(right); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, new BinaryOperation(isAndAlso ? BinaryOperatorKind.And : BinaryOperatorKind.Or, PopOperand(), visitedRight, isLifted: false, binOp.IsChecked, binOp.IsCompareText, binOp.OperatorMethod, unaryOperatorMethod: null, semanticModel: null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), IsImplicit(binOp)))); PopStackFrameAndLeaveRegion(frame); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(done); return GetCaptureReference(resultId, binOp); } private IOperation VisitUserDefinedBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) { SpillEvalStack(); var resultCaptureRegion = CurrentRegionRequired; INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); bool isLifted = binOp.IsLifted; IOperation left = binOp.LeftOperand; IOperation right = binOp.RightOperand; IMethodSymbol? unaryOperatorMethod = ((BinaryOperation)binOp).UnaryOperatorMethod; bool isAndAlso = CalculateAndOrSense(binOp, true); IOperation condition; var done = new BasicBlockBuilder(BasicBlockKind.Block); var doBitWise = new BasicBlockBuilder(BasicBlockKind.Block); IOperation capturedLeft = VisitAndCapture(left); condition = capturedLeft; if (ITypeSymbolHelpers.IsNullableType(left.Type)) { if (unaryOperatorMethod == null ? isLifted : !ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)) { condition = MakeIsNullOperation(condition, booleanType); ConditionalBranch(condition, jumpIfTrue: true, doBitWise); _currentBasicBlock = null; Debug.Assert(unaryOperatorMethod == null || !ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)); condition = CallNullableMember(OperationCloner.CloneOperation(capturedLeft), SpecialMember.System_Nullable_T_GetValueOrDefault); } } else if (unaryOperatorMethod != null && ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)) { condition = MakeInvalidOperation(unaryOperatorMethod.Parameters[0].Type, condition); } if (unaryOperatorMethod != null && ITypeSymbolHelpers.IsBooleanType(unaryOperatorMethod.ReturnType)) { condition = new UnaryOperation(isAndAlso ? UnaryOperatorKind.False : UnaryOperatorKind.True, condition, isLifted: false, isChecked: false, operatorMethod: unaryOperatorMethod, semanticModel: null, condition.Syntax, unaryOperatorMethod.ReturnType, constantValue: null, isImplicit: true); } else { condition = MakeInvalidOperation(booleanType, condition); } ConditionalBranch(condition, jumpIfTrue: false, doBitWise); _currentBasicBlock = null; int resultId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, OperationCloner.CloneOperation(capturedLeft))); UnconditionalBranch(done); AppendNewBlock(doBitWise); EvalStackFrame frame = PushStackFrame(); PushOperand(OperationCloner.CloneOperation(capturedLeft)); IOperation visitedRight = VisitRequired(right); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, new BinaryOperation(isAndAlso ? BinaryOperatorKind.And : BinaryOperatorKind.Or, PopOperand(), visitedRight, isLifted, binOp.IsChecked, binOp.IsCompareText, binOp.OperatorMethod, unaryOperatorMethod: null, semanticModel: null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), IsImplicit(binOp)))); PopStackFrameAndLeaveRegion(frame); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(done); return GetCaptureReference(resultId, binOp); } private IOperation VisitShortCircuitingOperator(IBinaryOperation condition, bool sense, bool stopSense, bool stopValue, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) { Debug.Assert(IsBooleanConditionalOperator(condition)); // we generate: // // gotoif (a == stopSense) fallThrough // b == sense // goto labEnd // fallThrough: // stopValue // labEnd: // AND OR // +- ------ ----- // stopSense | !sense sense // stopValue | 0 1 SpillEvalStack(); ref BasicBlockBuilder? lazyFallThrough = ref stopValue ? ref fallToTrueOpt : ref fallToFalseOpt; bool newFallThroughBlock = (lazyFallThrough == null); VisitConditionalBranch(condition.LeftOperand, ref lazyFallThrough, stopSense); var resultCaptureRegion = CurrentRegionRequired; int captureId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); IOperation resultFromRight = VisitConditionalExpression(condition.RightOperand, sense, captureId, fallToTrueOpt, fallToFalseOpt); CaptureResultIfNotAlready(condition.RightOperand.Syntax, captureId, resultFromRight); LeaveRegionsUpTo(resultCaptureRegion); if (newFallThroughBlock) { var labEnd = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(labEnd); AppendNewBlock(lazyFallThrough); var constantValue = ConstantValue.Create(stopValue); SyntaxNode leftSyntax = (lazyFallThrough!.GetSingletonPredecessorOrDefault() != null ? condition.LeftOperand : condition).Syntax; AddStatement(new FlowCaptureOperation(captureId, leftSyntax, new LiteralOperation(semanticModel: null, leftSyntax, condition.Type, constantValue, isImplicit: true))); AppendNewBlock(labEnd); } return GetCaptureReference(captureId, condition); } private IOperation VisitConditionalExpression(IOperation condition, bool sense, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) { Debug.Assert(ITypeSymbolHelpers.IsBooleanType(condition.Type)); IUnaryOperation? lastUnary = null; do { switch (condition) { case IParenthesizedOperation parenthesized: condition = parenthesized.Operand; continue; case IUnaryOperation unary when IsBooleanLogicalNot(unary): lastUnary = unary; condition = unary.Operand; sense = !sense; continue; } break; } while (true); if (condition.Kind == OperationKind.Binary) { var binOp = (IBinaryOperation)condition; if (IsBooleanConditionalOperator(binOp)) { return VisitBinaryConditionalOperator(binOp, sense, captureIdForResult, fallToTrueOpt, fallToFalseOpt); } } condition = VisitRequired(condition); if (!sense) { return lastUnary != null ? new UnaryOperation(lastUnary.OperatorKind, condition, lastUnary.IsLifted, lastUnary.IsChecked, lastUnary.OperatorMethod, semanticModel: null, lastUnary.Syntax, lastUnary.Type, lastUnary.GetConstantValue(), IsImplicit(lastUnary)) : new UnaryOperation(UnaryOperatorKind.Not, condition, isLifted: false, isChecked: false, operatorMethod: null, semanticModel: null, condition.Syntax, condition.Type, constantValue: null, isImplicit: true); } return condition; } private static bool IsBooleanConditionalOperator(IBinaryOperation binOp) { return IsConditional(binOp) && binOp.OperatorMethod == null && ITypeSymbolHelpers.IsBooleanType(binOp.Type) && ITypeSymbolHelpers.IsBooleanType(binOp.LeftOperand.Type) && ITypeSymbolHelpers.IsBooleanType(binOp.RightOperand.Type); } private void VisitConditionalBranch(IOperation condition, [NotNull] ref BasicBlockBuilder? dest, bool jumpIfTrue) { SpillEvalStack(); #if DEBUG RegionBuilder? current = _currentRegion; #endif VisitConditionalBranchCore(condition, ref dest, jumpIfTrue); #if DEBUG Debug.Assert(current == _currentRegion); #endif } /// <summary> /// This function does not change the current region. The stack should be spilled before calling it. /// </summary> private void VisitConditionalBranchCore(IOperation condition, [NotNull] ref BasicBlockBuilder? dest, bool jumpIfTrue) { oneMoreTime: Debug.Assert(_startSpillingAt == _evalStack.Count); while (condition.Kind == OperationKind.Parenthesized) { condition = ((IParenthesizedOperation)condition).Operand; } switch (condition.Kind) { case OperationKind.Binary: var binOp = (IBinaryOperation)condition; if (IsBooleanConditionalOperator(binOp)) { if (CalculateAndOrSense(binOp, jumpIfTrue)) { // gotoif(LeftOperand != sense) fallThrough // gotoif(RightOperand == sense) dest // fallThrough: BasicBlockBuilder? fallThrough = null; VisitConditionalBranchCore(binOp.LeftOperand, ref fallThrough, !jumpIfTrue); VisitConditionalBranchCore(binOp.RightOperand, ref dest, jumpIfTrue); AppendNewBlock(fallThrough); return; } else { // gotoif(LeftOperand == sense) dest // gotoif(RightOperand == sense) dest VisitConditionalBranchCore(binOp.LeftOperand, ref dest, jumpIfTrue); condition = binOp.RightOperand; goto oneMoreTime; } } // none of above. // then it is regular binary expression - Or, And, Xor ... goto default; case OperationKind.Unary: var unOp = (IUnaryOperation)condition; if (IsBooleanLogicalNot(unOp)) { jumpIfTrue = !jumpIfTrue; condition = unOp.Operand; goto oneMoreTime; } goto default; case OperationKind.Conditional: if (ITypeSymbolHelpers.IsBooleanType(condition.Type)) { var conditional = (IConditionalOperation)condition; Debug.Assert(conditional.WhenFalse is not null); if (ITypeSymbolHelpers.IsBooleanType(conditional.WhenTrue.Type) && ITypeSymbolHelpers.IsBooleanType(conditional.WhenFalse.Type)) { BasicBlockBuilder? whenFalse = null; VisitConditionalBranchCore(conditional.Condition, ref whenFalse, jumpIfTrue: false); VisitConditionalBranchCore(conditional.WhenTrue, ref dest, jumpIfTrue); var afterIf = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); VisitConditionalBranchCore(conditional.WhenFalse, ref dest, jumpIfTrue); AppendNewBlock(afterIf); return; } } goto default; case OperationKind.Coalesce: if (ITypeSymbolHelpers.IsBooleanType(condition.Type)) { var coalesce = (ICoalesceOperation)condition; if (ITypeSymbolHelpers.IsBooleanType(coalesce.WhenNull.Type)) { var whenNull = new BasicBlockBuilder(BasicBlockKind.Block); EvalStackFrame frame = PushStackFrame(); IOperation convertedTestExpression = NullCheckAndConvertCoalesceValue(coalesce, whenNull); dest = dest ?? new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(convertedTestExpression, jumpIfTrue, dest); _currentBasicBlock = null; var afterCoalesce = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(afterCoalesce); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(whenNull); VisitConditionalBranchCore(coalesce.WhenNull, ref dest, jumpIfTrue); AppendNewBlock(afterCoalesce); return; } } goto default; case OperationKind.Conversion: var conversion = (IConversionOperation)condition; if (conversion.Operand.Kind == OperationKind.Throw) { IOperation? rewrittenThrow = base.Visit(conversion.Operand, null); Debug.Assert(rewrittenThrow != null); Debug.Assert(rewrittenThrow.Kind == OperationKind.None); Debug.Assert(rewrittenThrow.Children.IsEmpty()); dest = dest ?? new BasicBlockBuilder(BasicBlockKind.Block); return; } goto default; default: { EvalStackFrame frame = PushStackFrame(); condition = VisitRequired(condition); dest = dest ?? new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(condition, jumpIfTrue, dest); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); return; } } } private void ConditionalBranch(IOperation condition, bool jumpIfTrue, BasicBlockBuilder destination) { BasicBlockBuilder previous = CurrentBasicBlock; BasicBlockBuilder.Branch branch = RegularBranch(destination); Debug.Assert(previous.BranchValue == null); Debug.Assert(!previous.HasCondition); Debug.Assert(condition != null); Debug.Assert(branch.Destination != null); Operation.SetParentOperation(condition, null); branch.Destination.AddPredecessor(previous); previous.BranchValue = condition; previous.ConditionKind = jumpIfTrue ? ControlFlowConditionKind.WhenTrue : ControlFlowConditionKind.WhenFalse; previous.Conditional = branch; } /// <summary> /// Returns converted test expression. /// Caller is responsible for spilling the stack and pushing a stack frame before calling this helper. /// </summary> private IOperation NullCheckAndConvertCoalesceValue(ICoalesceOperation operation, BasicBlockBuilder whenNull) { Debug.Assert(_evalStack.Last().frameOpt != null); Debug.Assert(_startSpillingAt >= _evalStack.Count - 1); IOperation operationValue = operation.Value; SyntaxNode valueSyntax = operationValue.Syntax; ITypeSymbol? valueTypeOpt = operationValue.Type; PushOperand(VisitRequired(operationValue)); SpillEvalStack(); IOperation testExpression = PopOperand(); ConditionalBranch(MakeIsNullOperation(testExpression), jumpIfTrue: true, whenNull); _currentBasicBlock = null; CommonConversion testConversion = operation.ValueConversion; IOperation capturedValue = OperationCloner.CloneOperation(testExpression); IOperation? convertedTestExpression = null; if (testConversion.Exists) { IOperation? possiblyUnwrappedValue; if (ITypeSymbolHelpers.IsNullableType(valueTypeOpt) && (!testConversion.IsIdentity || !ITypeSymbolHelpers.IsNullableType(operation.Type))) { possiblyUnwrappedValue = TryCallNullableMember(capturedValue, SpecialMember.System_Nullable_T_GetValueOrDefault); } else { possiblyUnwrappedValue = capturedValue; } if (possiblyUnwrappedValue != null) { if (testConversion.IsIdentity) { convertedTestExpression = possiblyUnwrappedValue; } else { convertedTestExpression = new ConversionOperation(possiblyUnwrappedValue, ((CoalesceOperation)operation).ValueConversionConvertible, isTryCast: false, isChecked: false, semanticModel: null, valueSyntax, operation.Type, constantValue: null, isImplicit: true); } } } if (convertedTestExpression == null) { convertedTestExpression = MakeInvalidOperation(operation.Type, capturedValue); } return convertedTestExpression; } public override IOperation VisitCoalesce(ICoalesceOperation operation, int? captureIdForResult) { SpillEvalStack(); var conversion = operation.WhenNull as IConversionOperation; bool alternativeThrows = conversion?.Operand.Kind == OperationKind.Throw; RegionBuilder resultCaptureRegion = CurrentRegionRequired; EvalStackFrame frame = PushStackFrame(); var whenNull = new BasicBlockBuilder(BasicBlockKind.Block); IOperation convertedTestExpression = NullCheckAndConvertCoalesceValue(operation, whenNull); IOperation result; var afterCoalesce = new BasicBlockBuilder(BasicBlockKind.Block); if (alternativeThrows) { // This is a special case with "throw" as an alternative. We don't need to create an additional // capture for the result because there won't be any result from the alternative branch. result = convertedTestExpression; UnconditionalBranch(afterCoalesce); PopStackFrame(frame); AppendNewBlock(whenNull); Debug.Assert(conversion is not null); IOperation? rewrittenThrow = base.Visit(conversion.Operand, null); Debug.Assert(rewrittenThrow != null); Debug.Assert(rewrittenThrow.Kind == OperationKind.None); Debug.Assert(rewrittenThrow.Children.IsEmpty()); } else { int resultCaptureId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Value.Syntax, convertedTestExpression)); result = GetCaptureReference(resultCaptureId, operation); UnconditionalBranch(afterCoalesce); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(whenNull); VisitAndCapture(operation.WhenNull, resultCaptureId); LeaveRegionsUpTo(resultCaptureRegion); } AppendNewBlock(afterCoalesce); return result; } public override IOperation? VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, int? captureIdForResult) { SpillEvalStack(); // If we're in a statement context, we elide the capture of the result of the assignment, as it will // just be wrapped in an expression statement that isn't used anywhere and isn't observed by anything. Debug.Assert(operation.Parent != null); bool isStatement = _currentStatement == operation || operation.Parent.Kind == OperationKind.ExpressionStatement; Debug.Assert(captureIdForResult == null || !isStatement); RegionBuilder resultCaptureRegion = CurrentRegionRequired; EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.Target)); SpillEvalStack(); IOperation locationCapture = PopOperand(); // Capture the value, as it will only be evaluated once. The location will be used separately later for // the null case EvalStackFrame valueFrame = PushStackFrame(); SpillEvalStack(); Debug.Assert(valueFrame.RegionBuilderOpt != null); int valueCaptureId = GetNextCaptureId(valueFrame.RegionBuilderOpt); AddStatement(new FlowCaptureOperation(valueCaptureId, locationCapture.Syntax, locationCapture)); IOperation valueCapture = GetCaptureReference(valueCaptureId, locationCapture); var whenNull = new BasicBlockBuilder(BasicBlockKind.Block); var afterCoalesce = new BasicBlockBuilder(BasicBlockKind.Block); int resultCaptureId = isStatement ? -1 : captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); if (operation.Target?.Type?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T && ((INamedTypeSymbol)operation.Target.Type!).TypeArguments[0].Equals(operation.Type)) { nullableValueTypeReturn(); } else { standardReturn(); } PopStackFrame(frame); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(afterCoalesce); return isStatement ? null : GetCaptureReference(resultCaptureId, operation); void nullableValueTypeReturn() { // We'll transform this into one of two possibilities, depending on whether we're using // this as an expression or a statement. // // Expression Form: // intermediate1 = valueCapture.GetValueOrDefault(); // branch if false to whenNull: valueCapture.HasValue() // result = intermediate // branch to after // // whenNull: // intermediate2 = rightValue // result = intermediate2 // locationCapture = Convert(intermediate2) // // after: // result // // Statement Form // branch if false to whenNull: valueCapture.HasValue() // branch to after // // whenNull: // locationCapture = Convert(rightValue) // // after: int intermediateResult = -1; EvalStackFrame? intermediateFrame = null; if (!isStatement) { intermediateFrame = PushStackFrame(); SpillEvalStack(); Debug.Assert(intermediateFrame.RegionBuilderOpt != null); intermediateResult = GetNextCaptureId(intermediateFrame.RegionBuilderOpt); AddStatement( new FlowCaptureOperation(intermediateResult, operation.Target.Syntax, CallNullableMember(valueCapture, SpecialMember.System_Nullable_T_GetValueOrDefault))); } ConditionalBranch( CallNullableMember(OperationCloner.CloneOperation(valueCapture), SpecialMember.System_Nullable_T_get_HasValue), jumpIfTrue: false, whenNull); if (!isStatement) { Debug.Assert(intermediateFrame != null); _currentBasicBlock = null; AddStatement( new FlowCaptureOperation(resultCaptureId, operation.Syntax, GetCaptureReference(intermediateResult, operation.Target))); PopStackFrame(intermediateFrame); } PopStackFrame(valueFrame); UnconditionalBranch(afterCoalesce); AppendNewBlock(whenNull); EvalStackFrame whenNullFrame = PushStackFrame(); SpillEvalStack(); IOperation whenNullValue = VisitRequired(operation.Value); if (!isStatement) { Debug.Assert(whenNullFrame.RegionBuilderOpt != null); int intermediateValueCaptureId = GetNextCaptureId(whenNullFrame.RegionBuilderOpt); AddStatement(new FlowCaptureOperation(intermediateValueCaptureId, whenNullValue.Syntax, whenNullValue)); whenNullValue = GetCaptureReference(intermediateValueCaptureId, whenNullValue); AddStatement( new FlowCaptureOperation( resultCaptureId, operation.Syntax, GetCaptureReference(intermediateValueCaptureId, whenNullValue))); } AddStatement( new SimpleAssignmentOperation( isRef: false, target: OperationCloner.CloneOperation(locationCapture), value: CreateConversion(whenNullValue, operation.Target.Type), semanticModel: null, syntax: operation.Syntax, type: operation.Target.Type, constantValue: operation.GetConstantValue(), isImplicit: true)); PopStackFrameAndLeaveRegion(whenNullFrame); } void standardReturn() { ConditionalBranch(MakeIsNullOperation(valueCapture), jumpIfTrue: true, whenNull); if (!isStatement) { _currentBasicBlock = null; AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Syntax, OperationCloner.CloneOperation(valueCapture))); } PopStackFrameAndLeaveRegion(valueFrame); UnconditionalBranch(afterCoalesce); AppendNewBlock(whenNull); // The return of Visit(operation.WhenNull) can be a flow capture that wasn't used in the non-null branch. We want to create a // region around it to ensure that the scope of the flow capture is as narrow as possible. If there was no flow capture, region // packing will take care of removing the empty region. EvalStackFrame whenNullFrame = PushStackFrame(); IOperation whenNullValue = VisitRequired(operation.Value); IOperation whenNullAssignment = new SimpleAssignmentOperation(isRef: false, OperationCloner.CloneOperation(locationCapture), whenNullValue, semanticModel: null, operation.Syntax, operation.Type, constantValue: operation.GetConstantValue(), isImplicit: true); if (isStatement) { AddStatement(whenNullAssignment); } else { AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Syntax, whenNullAssignment)); } PopStackFrameAndLeaveRegion(whenNullFrame); } } private static BasicBlockBuilder.Branch RegularBranch(BasicBlockBuilder destination) { return new BasicBlockBuilder.Branch() { Destination = destination, Kind = ControlFlowBranchSemantics.Regular }; } private static IOperation MakeInvalidOperation(ITypeSymbol? type, IOperation child) { return new InvalidOperation(ImmutableArray.Create<IOperation>(child), semanticModel: null, child.Syntax, type, constantValue: null, isImplicit: true); } private static IOperation MakeInvalidOperation(SyntaxNode syntax, ITypeSymbol? type, IOperation child1, IOperation child2) { return MakeInvalidOperation(syntax, type, ImmutableArray.Create<IOperation>(child1, child2)); } private static IOperation MakeInvalidOperation(SyntaxNode syntax, ITypeSymbol? type, ImmutableArray<IOperation> children) { return new InvalidOperation(children, semanticModel: null, syntax, type, constantValue: null, isImplicit: true); } private IsNullOperation MakeIsNullOperation(IOperation operand) { return MakeIsNullOperation(operand, _compilation.GetSpecialType(SpecialType.System_Boolean)); } private static IsNullOperation MakeIsNullOperation(IOperation operand, ITypeSymbol booleanType) { Debug.Assert(ITypeSymbolHelpers.IsBooleanType(booleanType)); ConstantValue? constantValue = operand.GetConstantValue() is { IsNull: var isNull } ? ConstantValue.Create(isNull) : null; return new IsNullOperation(operand.Syntax, operand, booleanType, constantValue); } private IOperation? TryCallNullableMember(IOperation value, SpecialMember nullableMember) { Debug.Assert(nullableMember == SpecialMember.System_Nullable_T_GetValueOrDefault || nullableMember == SpecialMember.System_Nullable_T_get_HasValue || nullableMember == SpecialMember.System_Nullable_T_get_Value || nullableMember == SpecialMember.System_Nullable_T__op_Explicit_ToT || nullableMember == SpecialMember.System_Nullable_T__op_Implicit_FromT); ITypeSymbol? valueType = value.Type; Debug.Assert(ITypeSymbolHelpers.IsNullableType(valueType)); var method = (IMethodSymbol?)_compilation.CommonGetSpecialTypeMember(nullableMember)?.GetISymbol(); if (method != null) { foreach (ISymbol candidate in valueType.GetMembers(method.Name)) { if (candidate.OriginalDefinition.Equals(method)) { method = (IMethodSymbol)candidate; return new InvocationOperation(method, value, isVirtual: false, ImmutableArray<IArgumentOperation>.Empty, semanticModel: null, value.Syntax, method.ReturnType, isImplicit: true); } } } return null; } private IOperation CallNullableMember(IOperation value, SpecialMember nullableMember) { Debug.Assert(ITypeSymbolHelpers.IsNullableType(value.Type)); return TryCallNullableMember(value, nullableMember) ?? MakeInvalidOperation(ITypeSymbolHelpers.GetNullableUnderlyingType(value.Type), value); } public override IOperation? VisitConditionalAccess(IConditionalAccessOperation operation, int? captureIdForResult) { SpillEvalStack(); RegionBuilder resultCaptureRegion = CurrentRegionRequired; // Avoid creation of default values and FlowCapture for conditional access on a statement level. bool isOnStatementLevel = _currentStatement == operation || (_currentStatement == operation.Parent && _currentStatement?.Kind == OperationKind.ExpressionStatement); EvalStackFrame? expressionFrame = null; var operations = ArrayBuilder<IOperation>.GetInstance(); if (!isOnStatementLevel) { expressionFrame = PushStackFrame(); } IConditionalAccessOperation currentConditionalAccess = operation; IOperation testExpression; var whenNull = new BasicBlockBuilder(BasicBlockKind.Block); var previousTracker = _currentConditionalAccessTracker; _currentConditionalAccessTracker = new ConditionalAccessOperationTracker(operations, whenNull); while (true) { testExpression = currentConditionalAccess.Operation; if (!isConditionalAccessInstancePresentInChildren(currentConditionalAccess.WhenNotNull)) { // https://github.com/dotnet/roslyn/issues/27564: It looks like there is a bug in IOperation tree around XmlMemberAccessExpressionSyntax, // a None operation is created and all children are dropped. // See Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests.ExpressionCompilerTests.ConditionalAccessExpressionType // Because of this, the recursion to visit the child operations will never occur if we visit the WhenNull of the current // conditional access, so we need to manually visit the Operation of the conditional access now. _ = VisitConditionalAccessTestExpression(testExpression); break; } operations.Push(testExpression); if (currentConditionalAccess.WhenNotNull is not IConditionalAccessOperation nested) { break; } currentConditionalAccess = nested; } if (isOnStatementLevel) { Debug.Assert(captureIdForResult == null); IOperation result = VisitRequired(currentConditionalAccess.WhenNotNull); resetConditionalAccessTracker(); if (_currentStatement != operation) { Debug.Assert(_currentStatement is not null); var expressionStatement = (IExpressionStatementOperation)_currentStatement; result = new ExpressionStatementOperation(result, semanticModel: null, expressionStatement.Syntax, IsImplicit(expressionStatement)); } AddStatement(result); AppendNewBlock(whenNull); return null; } else { Debug.Assert(expressionFrame != null); int resultCaptureId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); if (ITypeSymbolHelpers.IsNullableType(operation.Type) && !ITypeSymbolHelpers.IsNullableType(currentConditionalAccess.WhenNotNull.Type)) { IOperation access = VisitRequired(currentConditionalAccess.WhenNotNull); AddStatement(new FlowCaptureOperation(resultCaptureId, currentConditionalAccess.WhenNotNull.Syntax, MakeNullable(access, operation.Type))); } else { CaptureResultIfNotAlready(currentConditionalAccess.WhenNotNull.Syntax, resultCaptureId, VisitRequired(currentConditionalAccess.WhenNotNull, resultCaptureId)); } PopStackFrame(expressionFrame); LeaveRegionsUpTo(resultCaptureRegion); resetConditionalAccessTracker(); var afterAccess = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(afterAccess); AppendNewBlock(whenNull); SyntaxNode defaultValueSyntax = (operation.Operation == testExpression ? testExpression : operation).Syntax; Debug.Assert(operation.Type is not null); AddStatement(new FlowCaptureOperation(resultCaptureId, defaultValueSyntax, new DefaultValueOperation(semanticModel: null, defaultValueSyntax, operation.Type, (operation.Type.IsReferenceType && !ITypeSymbolHelpers.IsNullableType(operation.Type)) ? ConstantValue.Null : null, isImplicit: true))); AppendNewBlock(afterAccess); return GetCaptureReference(resultCaptureId, operation); } void resetConditionalAccessTracker() { Debug.Assert(!_currentConditionalAccessTracker.IsDefault); Debug.Assert(_currentConditionalAccessTracker.Operations.Count == 0); _currentConditionalAccessTracker.Free(); _currentConditionalAccessTracker = previousTracker; } static bool isConditionalAccessInstancePresentInChildren(IOperation operation) { if (operation is InvalidOperation invalidOperation) { return checkInvalidChildren(invalidOperation); } // The conditional access should always be first leaf node in the subtree when performing a depth-first search. Visit the first child recursively // until we either reach the bottom, or find the conditional access. Operation currentOperation = (Operation)operation; while (currentOperation.ChildOperations.GetEnumerator() is var enumerator && enumerator.MoveNext()) { if (enumerator.Current is IConditionalAccessInstanceOperation) { return true; } else if (enumerator.Current is InvalidOperation invalidChild) { return checkInvalidChildren(invalidChild); } currentOperation = (Operation)enumerator.Current; } return false; } static bool checkInvalidChildren(InvalidOperation operation) { // Invalid operations can have children ordering that doesn't put the conditional access instance first. For these cases, // use a recursive check foreach (var child in operation.ChildOperations) { if (child is IConditionalAccessInstanceOperation || isConditionalAccessInstancePresentInChildren(child)) { return true; } } return false; } } public override IOperation VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, int? captureIdForResult) { Debug.Assert(!_currentConditionalAccessTracker.IsDefault && _currentConditionalAccessTracker.Operations.Count > 0); IOperation testExpression = _currentConditionalAccessTracker.Operations.Pop(); return VisitConditionalAccessTestExpression(testExpression); } private IOperation VisitConditionalAccessTestExpression(IOperation testExpression) { Debug.Assert(!_currentConditionalAccessTracker.IsDefault); SyntaxNode testExpressionSyntax = testExpression.Syntax; ITypeSymbol? testExpressionType = testExpression.Type; var frame = PushStackFrame(); PushOperand(VisitRequired(testExpression)); SpillEvalStack(); IOperation spilledTestExpression = PopOperand(); PopStackFrame(frame); ConditionalBranch(MakeIsNullOperation(spilledTestExpression), jumpIfTrue: true, _currentConditionalAccessTracker.WhenNull); _currentBasicBlock = null; IOperation receiver = OperationCloner.CloneOperation(spilledTestExpression); if (ITypeSymbolHelpers.IsNullableType(testExpressionType)) { receiver = CallNullableMember(receiver, SpecialMember.System_Nullable_T_GetValueOrDefault); } return receiver; } public override IOperation? VisitExpressionStatement(IExpressionStatementOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); IOperation? underlying = Visit(operation.Operation); if (underlying == null) { Debug.Assert(operation.Operation.Kind == OperationKind.ConditionalAccess || operation.Operation.Kind == OperationKind.CoalesceAssignment); return FinishVisitingStatement(operation); } else if (operation.Operation.Kind == OperationKind.Throw) { return FinishVisitingStatement(operation); } return FinishVisitingStatement(operation, new ExpressionStatementOperation(underlying, semanticModel: null, operation.Syntax, IsImplicit(operation))); } public override IOperation? VisitWhileLoop(IWhileLoopOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); var locals = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals); var @continue = GetLabeledOrNewBlock(operation.ContinueLabel); var @break = GetLabeledOrNewBlock(operation.ExitLabel); if (operation.ConditionIsTop) { // while (condition) // body; // // becomes // // continue: // { // GotoIfFalse condition break; // body // goto continue; // } // break: AppendNewBlock(@continue); EnterRegion(locals); Debug.Assert(operation.Condition is not null); VisitConditionalBranch(operation.Condition, ref @break, jumpIfTrue: operation.ConditionIsUntil); VisitStatement(operation.Body); UnconditionalBranch(@continue); } else { // do // body // while (condition); // // becomes // // start: // { // body // continue: // GotoIfTrue condition start; // } // break: var start = new BasicBlockBuilder(BasicBlockKind.Block); AppendNewBlock(start); EnterRegion(locals); VisitStatement(operation.Body); AppendNewBlock(@continue); if (operation.Condition != null) { VisitConditionalBranch(operation.Condition, ref start, jumpIfTrue: !operation.ConditionIsUntil); } else { UnconditionalBranch(start); } } Debug.Assert(_currentRegion == locals); LeaveRegion(); AppendNewBlock(@break); return FinishVisitingStatement(operation); } public override IOperation? VisitTry(ITryOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); var afterTryCatchFinally = GetLabeledOrNewBlock(operation.ExitLabel); if (operation.Catches.IsEmpty && operation.Finally == null) { // Malformed node without handlers // It looks like we can get here for VB only. Let's recover the same way C# does, i.e. // pretend that there is no Try. Just visit body. VisitStatement(operation.Body); AppendNewBlock(afterTryCatchFinally); return FinishVisitingStatement(operation); } RegionBuilder? tryAndFinallyRegion = null; bool haveFinally = operation.Finally != null; if (haveFinally) { tryAndFinallyRegion = new RegionBuilder(ControlFlowRegionKind.TryAndFinally); EnterRegion(tryAndFinallyRegion); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); } bool haveCatches = !operation.Catches.IsEmpty; if (haveCatches) { EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndCatch)); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); } Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.Try); VisitStatement(operation.Body); UnconditionalBranch(afterTryCatchFinally); if (haveCatches) { LeaveRegion(); foreach (ICatchClauseOperation catchClause in operation.Catches) { RegionBuilder? filterAndHandlerRegion = null; IOperation? exceptionDeclarationOrExpression = catchClause.ExceptionDeclarationOrExpression; IOperation? filter = catchClause.Filter; bool haveFilter = filter != null; var catchBlock = new BasicBlockBuilder(BasicBlockKind.Block); if (haveFilter) { filterAndHandlerRegion = new RegionBuilder(ControlFlowRegionKind.FilterAndHandler, catchClause.ExceptionType, catchClause.Locals); EnterRegion(filterAndHandlerRegion); var filterRegion = new RegionBuilder(ControlFlowRegionKind.Filter, catchClause.ExceptionType); EnterRegion(filterRegion); AddExceptionStore(catchClause.ExceptionType, exceptionDeclarationOrExpression); VisitConditionalBranch(filter!, ref catchBlock, jumpIfTrue: true); var continueDispatchBlock = new BasicBlockBuilder(BasicBlockKind.Block); AppendNewBlock(continueDispatchBlock); continueDispatchBlock.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; LeaveRegion(); Debug.Assert(!filterRegion.IsEmpty); Debug.Assert(filterRegion.LastBlock.FallThrough.Destination == null); Debug.Assert(!filterRegion.FirstBlock.HasPredecessors); } var handlerRegion = new RegionBuilder(ControlFlowRegionKind.Catch, catchClause.ExceptionType, haveFilter ? default : catchClause.Locals); EnterRegion(handlerRegion); AppendNewBlock(catchBlock, linkToPrevious: false); if (!haveFilter) { AddExceptionStore(catchClause.ExceptionType, exceptionDeclarationOrExpression); } VisitStatement(catchClause.Handler); UnconditionalBranch(afterTryCatchFinally); LeaveRegion(); Debug.Assert(!handlerRegion.IsEmpty); if (haveFilter) { Debug.Assert(CurrentRegionRequired == filterAndHandlerRegion); LeaveRegion(); #if DEBUG Debug.Assert(filterAndHandlerRegion.Regions![0].LastBlock!.FallThrough.Destination == null); if (handlerRegion.FirstBlock.HasPredecessors) { var predecessors = ArrayBuilder<BasicBlockBuilder>.GetInstance(); handlerRegion.FirstBlock.GetPredecessors(predecessors); Debug.Assert(predecessors.All(p => filterAndHandlerRegion.Regions[0].FirstBlock!.Ordinal <= p.Ordinal && filterAndHandlerRegion.Regions[0].LastBlock!.Ordinal >= p.Ordinal)); predecessors.Free(); } #endif } else { Debug.Assert(!handlerRegion.FirstBlock.HasPredecessors); } } Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.TryAndCatch); LeaveRegion(); } if (haveFinally) { Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.Try); LeaveRegion(); var finallyRegion = new RegionBuilder(ControlFlowRegionKind.Finally); EnterRegion(finallyRegion); AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); VisitStatement(operation.Finally); var continueDispatchBlock = new BasicBlockBuilder(BasicBlockKind.Block); AppendNewBlock(continueDispatchBlock); continueDispatchBlock.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; LeaveRegion(); Debug.Assert(_currentRegion == tryAndFinallyRegion); LeaveRegion(); Debug.Assert(!finallyRegion.IsEmpty); Debug.Assert(finallyRegion.LastBlock.FallThrough.Destination == null); Debug.Assert(!finallyRegion.FirstBlock.HasPredecessors); } AppendNewBlock(afterTryCatchFinally, linkToPrevious: false); Debug.Assert(tryAndFinallyRegion?.Regions![1].LastBlock!.FallThrough.Destination == null); return FinishVisitingStatement(operation); } private void AddExceptionStore(ITypeSymbol exceptionType, IOperation? exceptionDeclarationOrExpression) { if (exceptionDeclarationOrExpression != null) { IOperation exceptionTarget; SyntaxNode syntax = exceptionDeclarationOrExpression.Syntax; if (exceptionDeclarationOrExpression.Kind == OperationKind.VariableDeclarator) { ILocalSymbol local = ((IVariableDeclaratorOperation)exceptionDeclarationOrExpression).Symbol; exceptionTarget = new LocalReferenceOperation(local, isDeclaration: true, semanticModel: null, syntax, local.Type, constantValue: null, isImplicit: true); } else { exceptionTarget = VisitRequired(exceptionDeclarationOrExpression); } if (exceptionTarget != null) { AddStatement(new SimpleAssignmentOperation( isRef: false, target: exceptionTarget, value: new CaughtExceptionOperation(syntax, exceptionType), semanticModel: null, syntax: syntax, type: null, constantValue: null, isImplicit: true)); } } } public override IOperation VisitCatchClause(ICatchClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation? VisitReturn(IReturnOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); IOperation? returnedValue = Visit(operation.ReturnedValue); switch (operation.Kind) { case OperationKind.YieldReturn: AddStatement(new ReturnOperation(returnedValue, OperationKind.YieldReturn, semanticModel: null, operation.Syntax, IsImplicit(operation))); break; case OperationKind.YieldBreak: case OperationKind.Return: BasicBlockBuilder current = CurrentBasicBlock; LinkBlocks(CurrentBasicBlock, _exit, returnedValue is null ? ControlFlowBranchSemantics.Regular : ControlFlowBranchSemantics.Return); Debug.Assert(current.BranchValue == null); Debug.Assert(!current.HasCondition); current.BranchValue = Operation.SetParentOperation(returnedValue, null); _currentBasicBlock = null; break; default: throw ExceptionUtilities.UnexpectedValue(operation.Kind); } return FinishVisitingStatement(operation); } public override IOperation? VisitLabeled(ILabeledOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); VisitLabel(operation.Label); VisitStatement(operation.Operation); return FinishVisitingStatement(operation); } public void VisitLabel(ILabelSymbol operation) { BasicBlockBuilder labeled = GetLabeledOrNewBlock(operation); if (labeled.Ordinal != -1) { // Must be a duplicate label. Recover by simply allocating a new block. labeled = new BasicBlockBuilder(BasicBlockKind.Block); } AppendNewBlock(labeled); } private BasicBlockBuilder GetLabeledOrNewBlock(ILabelSymbol? labelOpt) { if (labelOpt == null) { return new BasicBlockBuilder(BasicBlockKind.Block); } BasicBlockBuilder? labeledBlock; if (_labeledBlocks == null) { _labeledBlocks = PooledDictionary<ILabelSymbol, BasicBlockBuilder>.GetInstance(); } else if (_labeledBlocks.TryGetValue(labelOpt, out labeledBlock)) { return labeledBlock; } labeledBlock = new BasicBlockBuilder(BasicBlockKind.Block); _labeledBlocks.Add(labelOpt, labeledBlock); return labeledBlock; } public override IOperation? VisitBranch(IBranchOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); UnconditionalBranch(GetLabeledOrNewBlock(operation.Target)); return FinishVisitingStatement(operation); } public override IOperation? VisitEmpty(IEmptyOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); return FinishVisitingStatement(operation); } public override IOperation? VisitThrow(IThrowOperation operation, int? captureIdForResult) { bool isStatement = (_currentStatement == operation); if (!isStatement) { SpillEvalStack(); } EvalStackFrame frame = PushStackFrame(); LinkThrowStatement(Visit(operation.Exception)); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block), linkToPrevious: false); if (isStatement) { return null; } else { return new NoneOperation(children: ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Syntax, constantValue: null, isImplicit: true, type: null); } } private void LinkThrowStatement(IOperation? exception) { BasicBlockBuilder current = CurrentBasicBlock; Debug.Assert(current.BranchValue == null); Debug.Assert(!current.HasCondition); Debug.Assert(current.FallThrough.Destination == null); Debug.Assert(current.FallThrough.Kind == ControlFlowBranchSemantics.None); current.BranchValue = Operation.SetParentOperation(exception, null); current.FallThrough.Kind = exception == null ? ControlFlowBranchSemantics.Rethrow : ControlFlowBranchSemantics.Throw; } public override IOperation? VisitUsing(IUsingOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); DisposeOperationInfo disposeInfo = ((UsingOperation)operation).DisposeInfo; HandleUsingOperationParts(operation.Resources, operation.Body, disposeInfo.DisposeMethod, disposeInfo.DisposeArguments, operation.Locals, operation.IsAsynchronous); return FinishVisitingStatement(operation); } private void HandleUsingOperationParts(IOperation resources, IOperation body, IMethodSymbol? disposeMethod, ImmutableArray<IArgumentOperation> disposeArguments, ImmutableArray<ILocalSymbol> locals, bool isAsynchronous) { var usingRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: locals); EnterRegion(usingRegion); ITypeSymbol iDisposable = isAsynchronous ? _compilation.CommonGetWellKnownType(WellKnownType.System_IAsyncDisposable).GetITypeSymbol() : _compilation.GetSpecialType(SpecialType.System_IDisposable); if (resources is IVariableDeclarationGroupOperation declarationGroup) { var resourceQueue = ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>.GetInstance(declarationGroup.Declarations.Length); foreach (IVariableDeclarationOperation declaration in declarationGroup.Declarations) { foreach (IVariableDeclaratorOperation declarator in declaration.Declarators) { resourceQueue.Add((declaration, declarator)); } } resourceQueue.ReverseContents(); processQueue(resourceQueue); } else { Debug.Assert(resources.Kind != OperationKind.VariableDeclaration); Debug.Assert(resources.Kind != OperationKind.VariableDeclarator); EvalStackFrame frame = PushStackFrame(); IOperation resource = VisitRequired(resources); if (shouldConvertToIDisposableBeforeTry(resource)) { resource = ConvertToIDisposable(resource, iDisposable); } PushOperand(resource); SpillEvalStack(); resource = PopOperand(); PopStackFrame(frame); processResource(resource, resourceQueueOpt: null); LeaveRegionIfAny(frame); } Debug.Assert(_currentRegion == usingRegion); LeaveRegion(); void processQueue(ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>? resourceQueueOpt) { if (resourceQueueOpt == null || resourceQueueOpt.Count == 0) { VisitStatement(body); } else { (IVariableDeclarationOperation declaration, IVariableDeclaratorOperation declarator) = resourceQueueOpt.Pop(); HandleVariableDeclarator(declaration, declarator); ILocalSymbol localSymbol = declarator.Symbol; processResource(new LocalReferenceOperation(localSymbol, isDeclaration: false, semanticModel: null, declarator.Syntax, localSymbol.Type, constantValue: null, isImplicit: true), resourceQueueOpt); } } bool shouldConvertToIDisposableBeforeTry(IOperation resource) { return resource.Type == null || resource.Type.Kind == SymbolKind.DynamicType; } void processResource(IOperation resource, ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>? resourceQueueOpt) { // When ResourceType is a non-nullable value type that implements IDisposable, the expansion is: // // { // ResourceType resource = expr; // try { statement; } // finally { ((IDisposable)resource).Dispose(); } // } // // Otherwise, when ResourceType is a non-nullable value type that implements // disposal via pattern, the expansion is: // // { // try { statement; } // finally { resource.Dispose(); } // } // Otherwise, when Resource type is a nullable value type or // a reference type other than dynamic that implements IDisposable, the expansion is: // // { // ResourceType resource = expr; // try { statement; } // finally { if (resource != null) ((IDisposable)resource).Dispose(); } // } // // Otherwise, when Resource type is a reference type other than dynamic // that implements disposal via pattern, the expansion is: // // { // ResourceType resource = expr; // try { statement; } // finally { if (resource != null) resource.Dispose(); } // } // // Otherwise, when ResourceType is dynamic, the expansion is: // { // dynamic resource = expr; // IDisposable d = (IDisposable)resource; // try { statement; } // finally { if (d != null) d.Dispose(); } // } RegionBuilder? resourceRegion = null; if (shouldConvertToIDisposableBeforeTry(resource)) { resourceRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); EnterRegion(resourceRegion); resource = ConvertToIDisposable(resource, iDisposable); int captureId = GetNextCaptureId(resourceRegion); AddStatement(new FlowCaptureOperation(captureId, resource.Syntax, resource)); resource = GetCaptureReference(captureId, resource); } var afterTryFinally = new BasicBlockBuilder(BasicBlockKind.Block); EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); processQueue(resourceQueueOpt); Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.Try); UnconditionalBranch(afterTryFinally); LeaveRegion(); AddDisposingFinally(resource, requiresRuntimeConversion: false, iDisposable, disposeMethod, disposeArguments, isAsynchronous); Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.TryAndFinally); LeaveRegion(); if (resourceRegion != null) { Debug.Assert(_currentRegion == resourceRegion); LeaveRegion(); } AppendNewBlock(afterTryFinally, linkToPrevious: false); } } private void AddDisposingFinally(IOperation resource, bool requiresRuntimeConversion, ITypeSymbol iDisposable, IMethodSymbol? disposeMethod, ImmutableArray<IArgumentOperation> disposeArguments, bool isAsynchronous) { Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.TryAndFinally); var endOfFinally = new BasicBlockBuilder(BasicBlockKind.Block); endOfFinally.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; var finallyRegion = new RegionBuilder(ControlFlowRegionKind.Finally); EnterRegion(finallyRegion); AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); if (requiresRuntimeConversion) { Debug.Assert(!isNotNullableValueType(resource.Type)); resource = ConvertToIDisposable(resource, iDisposable, isTryCast: true); int captureId = GetNextCaptureId(finallyRegion); AddStatement(new FlowCaptureOperation(captureId, resource.Syntax, resource)); resource = GetCaptureReference(captureId, resource); } if (requiresRuntimeConversion || !isNotNullableValueType(resource.Type)) { IOperation condition = MakeIsNullOperation(OperationCloner.CloneOperation(resource)); ConditionalBranch(condition, jumpIfTrue: true, endOfFinally); _currentBasicBlock = null; } if (!iDisposable.Equals(resource.Type) && disposeMethod is null) { resource = ConvertToIDisposable(resource, iDisposable); } EvalStackFrame disposeFrame = PushStackFrame(); AddStatement(tryDispose(resource) ?? MakeInvalidOperation(type: null, resource)); PopStackFrameAndLeaveRegion(disposeFrame); AppendNewBlock(endOfFinally); Debug.Assert(_currentRegion == finallyRegion); LeaveRegion(); return; IOperation? tryDispose(IOperation value) { Debug.Assert((disposeMethod is object && !disposeArguments.IsDefault) || (value.Type!.Equals(iDisposable) && disposeArguments.IsDefaultOrEmpty)); var method = disposeMethod ?? (isAsynchronous ? (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_IAsyncDisposable__DisposeAsync)?.GetISymbol() : (IMethodSymbol?)_compilation.CommonGetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose)?.GetISymbol()); if (method != null) { var args = disposeMethod is object ? VisitArguments(disposeArguments) : ImmutableArray<IArgumentOperation>.Empty; var invocation = new InvocationOperation(method, value, isVirtual: disposeMethod?.IsVirtual ?? true, args, semanticModel: null, value.Syntax, method.ReturnType, isImplicit: true); if (isAsynchronous) { return new AwaitOperation(invocation, semanticModel: null, value.Syntax, _compilation.GetSpecialType(SpecialType.System_Void), isImplicit: true); } return invocation; } return null; } bool isNotNullableValueType([NotNullWhen(true)] ITypeSymbol? type) { return type?.IsValueType == true && !ITypeSymbolHelpers.IsNullableType(type); } } private IOperation ConvertToIDisposable(IOperation operand, ITypeSymbol iDisposable, bool isTryCast = false) { Debug.Assert(iDisposable.SpecialType == SpecialType.System_IDisposable || iDisposable.Equals(_compilation.CommonGetWellKnownType(WellKnownType.System_IAsyncDisposable)?.GetITypeSymbol())); return new ConversionOperation(operand, _compilation.ClassifyConvertibleConversion(operand, iDisposable, out var constantValue), isTryCast, isChecked: false, semanticModel: null, operand.Syntax, iDisposable, constantValue, isImplicit: true); } public override IOperation? VisitLock(ILockOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); ITypeSymbol objectType = _compilation.GetSpecialType(SpecialType.System_Object); // If Monitor.Enter(object, ref bool) is available: // // L $lock = `LockedValue`; // bool $lockTaken = false; // try // { // Monitor.Enter($lock, ref $lockTaken); // `body` // } // finally // { // if ($lockTaken) Monitor.Exit($lock); // } // If Monitor.Enter(object, ref bool) is not available: // // L $lock = `LockedValue`; // Monitor.Enter($lock); // NB: before try-finally so we don't Exit if an exception prevents us from acquiring the lock. // try // { // `body` // } // finally // { // Monitor.Exit($lock); // } // If original type of the LockedValue object is System.Object, VB calls runtime helper (if one is available) // Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType to ensure no value type is // used. // For simplicity, we will not synthesize this call because its presence is unlikely to affect graph analysis. var lockStatement = (LockOperation)operation; var lockRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: lockStatement.LockTakenSymbol != null ? ImmutableArray.Create(lockStatement.LockTakenSymbol) : ImmutableArray<ILocalSymbol>.Empty); EnterRegion(lockRegion); EvalStackFrame frame = PushStackFrame(); IOperation lockedValue = VisitRequired(operation.LockedValue); if (!objectType.Equals(lockedValue.Type)) { lockedValue = CreateConversion(lockedValue, objectType); } PushOperand(lockedValue); SpillEvalStack(); lockedValue = PopOperand(); PopStackFrame(frame); var enterMethod = (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2)?.GetISymbol(); bool legacyMode = (enterMethod == null); if (legacyMode) { Debug.Assert(lockStatement.LockTakenSymbol == null); enterMethod = (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter)?.GetISymbol(); // Monitor.Enter($lock); if (enterMethod == null) { AddStatement(MakeInvalidOperation(type: null, lockedValue)); } else { AddStatement(new InvocationOperation(enterMethod, instance: null, isVirtual: false, ImmutableArray.Create<IArgumentOperation>( new ArgumentOperation(ArgumentKind.Explicit, enterMethod.Parameters[0], lockedValue, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, lockedValue.Syntax, isImplicit: true)), semanticModel: null, lockedValue.Syntax, enterMethod.ReturnType, isImplicit: true)); } } var afterTryFinally = new BasicBlockBuilder(BasicBlockKind.Block); EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); IOperation? lockTaken = null; if (!legacyMode) { // Monitor.Enter($lock, ref $lockTaken); Debug.Assert(lockStatement.LockTakenSymbol is not null); Debug.Assert(enterMethod is not null); lockTaken = new LocalReferenceOperation(lockStatement.LockTakenSymbol, isDeclaration: true, semanticModel: null, lockedValue.Syntax, lockStatement.LockTakenSymbol.Type, constantValue: null, isImplicit: true); AddStatement(new InvocationOperation(enterMethod, instance: null, isVirtual: false, ImmutableArray.Create<IArgumentOperation>( new ArgumentOperation(ArgumentKind.Explicit, enterMethod.Parameters[0], lockedValue, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, lockedValue.Syntax, isImplicit: true), new ArgumentOperation(ArgumentKind.Explicit, enterMethod.Parameters[1], lockTaken, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, lockedValue.Syntax, isImplicit: true)), semanticModel: null, lockedValue.Syntax, enterMethod.ReturnType, isImplicit: true)); } VisitStatement(operation.Body); Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.Try); UnconditionalBranch(afterTryFinally); LeaveRegion(); var endOfFinally = new BasicBlockBuilder(BasicBlockKind.Block); endOfFinally.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; EnterRegion(new RegionBuilder(ControlFlowRegionKind.Finally)); AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); if (!legacyMode) { // if ($lockTaken) Debug.Assert(lockStatement.LockTakenSymbol is not null); IOperation condition = new LocalReferenceOperation(lockStatement.LockTakenSymbol, isDeclaration: false, semanticModel: null, lockedValue.Syntax, lockStatement.LockTakenSymbol.Type, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, endOfFinally); _currentBasicBlock = null; } // Monitor.Exit($lock); var exitMethod = (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Exit)?.GetISymbol(); lockedValue = OperationCloner.CloneOperation(lockedValue); if (exitMethod == null) { AddStatement(MakeInvalidOperation(type: null, lockedValue)); } else { AddStatement(new InvocationOperation(exitMethod, instance: null, isVirtual: false, ImmutableArray.Create<IArgumentOperation>( new ArgumentOperation(ArgumentKind.Explicit, exitMethod.Parameters[0], lockedValue, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, lockedValue.Syntax, isImplicit: true)), semanticModel: null, lockedValue.Syntax, exitMethod.ReturnType, isImplicit: true)); } AppendNewBlock(endOfFinally); LeaveRegion(); Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.TryAndFinally); LeaveRegion(); LeaveRegionsUpTo(lockRegion); LeaveRegion(); AppendNewBlock(afterTryFinally, linkToPrevious: false); return FinishVisitingStatement(operation); } public override IOperation? VisitForEachLoop(IForEachLoopOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); var enumeratorCaptureRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); EnterRegion(enumeratorCaptureRegion); ForEachLoopOperationInfo? info = ((ForEachLoopOperation)operation).Info; RegionBuilder? regionForCollection = null; if (!operation.Locals.IsEmpty && operation.LoopControlVariable.Kind == OperationKind.VariableDeclarator) { // VB has rather interesting scoping rules for control variable. // It is in scope in the collection expression. However, it is considered to be // "a different" version of that local. Effectively when the code is emitted, // there are two distinct locals, one is used in the collection expression and the // other is used as a loop control variable. This is done to have proper hoisting // and lifetime in presence of lambdas. // Rather than introducing a separate local symbol, we will simply add another // lifetime region for that local around the collection expression. var declarator = (IVariableDeclaratorOperation)operation.LoopControlVariable; ILocalSymbol local = declarator.Symbol; foreach (IOperation op in operation.Collection.DescendantsAndSelf()) { if (op is ILocalReferenceOperation l && l.Local.Equals(local)) { regionForCollection = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: ImmutableArray.Create(local)); EnterRegion(regionForCollection); break; } } } IOperation enumerator = getEnumerator(); if (regionForCollection != null) { Debug.Assert(regionForCollection == _currentRegion); LeaveRegion(); } if (info?.NeedsDispose == true) { EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); } var @continue = GetLabeledOrNewBlock(operation.ContinueLabel); var @break = GetLabeledOrNewBlock(operation.ExitLabel); AppendNewBlock(@continue); EvalStackFrame frame = PushStackFrame(); ConditionalBranch(getCondition(enumerator), jumpIfTrue: false, @break); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); var localsRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals); EnterRegion(localsRegion); frame = PushStackFrame(); AddStatement(getLoopControlVariableAssignment(applyConversion(info?.CurrentConversion, getCurrent(OperationCloner.CloneOperation(enumerator)), info?.ElementType))); PopStackFrameAndLeaveRegion(frame); VisitStatement(operation.Body); Debug.Assert(localsRegion == _currentRegion); UnconditionalBranch(@continue); LeaveRegion(); AppendNewBlock(@break); if (info?.NeedsDispose == true) { var afterTryFinally = new BasicBlockBuilder(BasicBlockKind.Block); Debug.Assert(_currentRegion.Kind == ControlFlowRegionKind.Try); UnconditionalBranch(afterTryFinally); LeaveRegion(); bool isAsynchronous = info.IsAsynchronous; var iDisposable = isAsynchronous ? _compilation.CommonGetWellKnownType(WellKnownType.System_IAsyncDisposable).GetITypeSymbol() : _compilation.GetSpecialType(SpecialType.System_IDisposable); AddDisposingFinally(OperationCloner.CloneOperation(enumerator), requiresRuntimeConversion: !info.KnownToImplementIDisposable && info.PatternDisposeMethod == null, iDisposable, info.PatternDisposeMethod, info.DisposeArguments, isAsynchronous); Debug.Assert(_currentRegion.Kind == ControlFlowRegionKind.TryAndFinally); LeaveRegion(); AppendNewBlock(afterTryFinally, linkToPrevious: false); } Debug.Assert(_currentRegion == enumeratorCaptureRegion); LeaveRegion(); return FinishVisitingStatement(operation); IOperation applyConversion(IConvertibleConversion? conversionOpt, IOperation operand, ITypeSymbol? targetType) { if (conversionOpt?.ToCommonConversion().IsIdentity == false) { operand = new ConversionOperation(operand, conversionOpt, isTryCast: false, isChecked: false, semanticModel: null, operand.Syntax, targetType, constantValue: null, isImplicit: true); } return operand; } IOperation getEnumerator() { IOperation result; EvalStackFrame getEnumeratorFrame = PushStackFrame(); if (info?.GetEnumeratorMethod != null) { IOperation invocation = makeInvocation(operation.Collection.Syntax, info.GetEnumeratorMethod, info.GetEnumeratorMethod.IsStatic ? null : Visit(operation.Collection), info.GetEnumeratorArguments); int enumeratorCaptureId = GetNextCaptureId(enumeratorCaptureRegion); AddStatement(new FlowCaptureOperation(enumeratorCaptureId, operation.Collection.Syntax, invocation)); result = new FlowCaptureReferenceOperation(enumeratorCaptureId, operation.Collection.Syntax, info.GetEnumeratorMethod.ReturnType, constantValue: null); } else { // This must be an error case AddStatement(MakeInvalidOperation(type: null, VisitRequired(operation.Collection))); result = new InvalidOperation(ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Collection.Syntax, type: null, constantValue: null, isImplicit: true); } PopStackFrameAndLeaveRegion(getEnumeratorFrame); return result; } IOperation getCondition(IOperation enumeratorRef) { if (info?.MoveNextMethod != null) { var moveNext = makeInvocationDroppingInstanceForStaticMethods(info.MoveNextMethod, enumeratorRef, info.MoveNextArguments); if (operation.IsAsynchronous) { return new AwaitOperation(moveNext, semanticModel: null, operation.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), isImplicit: true); } return moveNext; } else { // This must be an error case return MakeInvalidOperation(_compilation.GetSpecialType(SpecialType.System_Boolean), enumeratorRef); } } IOperation getCurrent(IOperation enumeratorRef) { if (info?.CurrentProperty != null) { return new PropertyReferenceOperation(info.CurrentProperty, makeArguments(info.CurrentArguments), info.CurrentProperty.IsStatic ? null : enumeratorRef, semanticModel: null, operation.LoopControlVariable.Syntax, info.CurrentProperty.Type, isImplicit: true); } else { // This must be an error case return MakeInvalidOperation(type: null, enumeratorRef); } } IOperation getLoopControlVariableAssignment(IOperation current) { switch (operation.LoopControlVariable.Kind) { case OperationKind.VariableDeclarator: var declarator = (IVariableDeclaratorOperation)operation.LoopControlVariable; ILocalSymbol local = declarator.Symbol; current = applyConversion(info?.ElementConversion, current, local.Type); return new SimpleAssignmentOperation(isRef: local.RefKind != RefKind.None, new LocalReferenceOperation(local, isDeclaration: true, semanticModel: null, declarator.Syntax, local.Type, constantValue: null, isImplicit: true), current, semanticModel: null, declarator.Syntax, type: null, constantValue: null, isImplicit: true); case OperationKind.Tuple: case OperationKind.DeclarationExpression: Debug.Assert(info?.ElementConversion?.ToCommonConversion().IsIdentity != false); return new DeconstructionAssignmentOperation(VisitPreservingTupleOperations(operation.LoopControlVariable), current, semanticModel: null, operation.LoopControlVariable.Syntax, operation.LoopControlVariable.Type, isImplicit: true); default: return new SimpleAssignmentOperation(isRef: false, // In C# this is an error case and VB doesn't support ref locals VisitRequired(operation.LoopControlVariable), current, semanticModel: null, operation.LoopControlVariable.Syntax, operation.LoopControlVariable.Type, constantValue: null, isImplicit: true); } } InvocationOperation makeInvocationDroppingInstanceForStaticMethods(IMethodSymbol method, IOperation instance, ImmutableArray<IArgumentOperation> arguments) { return makeInvocation(instance.Syntax, method, method.IsStatic ? null : instance, arguments); } InvocationOperation makeInvocation(SyntaxNode syntax, IMethodSymbol method, IOperation? instanceOpt, ImmutableArray<IArgumentOperation> arguments) { Debug.Assert(method.IsStatic == (instanceOpt == null)); return new InvocationOperation(method, instanceOpt, isVirtual: method.IsVirtual || method.IsAbstract || method.IsOverride, makeArguments(arguments), semanticModel: null, syntax, method.ReturnType, isImplicit: true); } ImmutableArray<IArgumentOperation> makeArguments(ImmutableArray<IArgumentOperation> arguments) { if (arguments != null) { return VisitArguments(arguments); } return ImmutableArray<IArgumentOperation>.Empty; } } public override IOperation? VisitForToLoop(IForToLoopOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; bool isObjectLoop = (loopObject != null); ImmutableArray<ILocalSymbol> locals = operation.Locals; if (isObjectLoop) { locals = locals.Insert(0, loopObject!); } ITypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); BasicBlockBuilder @continue = GetLabeledOrNewBlock(operation.ContinueLabel); BasicBlockBuilder? @break = GetLabeledOrNewBlock(operation.ExitLabel); BasicBlockBuilder checkConditionBlock = new BasicBlockBuilder(BasicBlockKind.Block); BasicBlockBuilder bodyBlock = new BasicBlockBuilder(BasicBlockKind.Block); var loopRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: locals); EnterRegion(loopRegion); // Handle loop initialization int limitValueId = -1; int stepValueId = -1; IFlowCaptureReferenceOperation? positiveFlag = null; ITypeSymbol? stepEnumUnderlyingTypeOrSelf = ITypeSymbolHelpers.GetEnumUnderlyingTypeOrSelf(operation.StepValue.Type); initializeLoop(); // Now check condition AppendNewBlock(checkConditionBlock); checkLoopCondition(); // Handle body AppendNewBlock(bodyBlock); VisitStatement(operation.Body); // Increment AppendNewBlock(@continue); incrementLoopControlVariable(); UnconditionalBranch(checkConditionBlock); LeaveRegion(); AppendNewBlock(@break); return FinishVisitingStatement(operation); IOperation tryCallObjectForLoopControlHelper(SyntaxNode syntax, WellKnownMember helper) { Debug.Assert(isObjectLoop && loopObject is not null); bool isInitialization = (helper == WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj); var loopObjectReference = new LocalReferenceOperation(loopObject, isDeclaration: isInitialization, semanticModel: null, operation.LoopControlVariable.Syntax, loopObject.Type, constantValue: null, isImplicit: true); var method = (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(helper)?.GetISymbol(); int parametersCount = WellKnownMembers.GetDescriptor(helper).ParametersCount; if (method is null) { var builder = ArrayBuilder<IOperation>.GetInstance(--parametersCount, fillWithValue: null!); builder[--parametersCount] = loopObjectReference; do { builder[--parametersCount] = PopOperand(); } while (parametersCount != 0); Debug.Assert(builder.All(o => o != null)); return MakeInvalidOperation(operation.LimitValue.Syntax, booleanType, builder.ToImmutableAndFree()); } else { var builder = ArrayBuilder<IArgumentOperation>.GetInstance(parametersCount, fillWithValue: null!); builder[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, method.Parameters[parametersCount], visitLoopControlVariableReference(forceImplicit: true), // Yes we are going to evaluate it again inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, syntax, isImplicit: true); builder[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, method.Parameters[parametersCount], loopObjectReference, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, syntax, isImplicit: true); do { IOperation value = PopOperand(); builder[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, method.Parameters[parametersCount], value, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, isInitialization ? value.Syntax : syntax, isImplicit: true); } while (parametersCount != 0); Debug.Assert(builder.All(op => op is not null)); return new InvocationOperation(method, instance: null, isVirtual: false, builder.ToImmutableAndFree(), semanticModel: null, operation.LimitValue.Syntax, method.ReturnType, isImplicit: true); } } void initializeLoop() { EvalStackFrame frame = PushStackFrame(); PushOperand(visitLoopControlVariableReference(forceImplicit: false)); PushOperand(VisitRequired(operation.InitialValue)); if (isObjectLoop) { // For i as Object = 3 To 6 step 2 // body // Next // // becomes ==> // // { // Dim loopObj ' mysterious object that holds the loop state // // ' helper does internal initialization and tells if we need to do any iterations // if Not ObjectFlowControl.ForLoopControl.ForLoopInitObj(ctrl, init, limit, step, ref loopObj, ref ctrl) // goto exit: // start: // body // // continue: // ' helper updates loop state and tells if we need to do another iteration. // if ObjectFlowControl.ForLoopControl.ForNextCheckObj(ctrl, loopObj, ref ctrl) // GoTo start // } // exit: PushOperand(VisitRequired(operation.LimitValue)); PushOperand(VisitRequired(operation.StepValue)); IOperation condition = tryCallObjectForLoopControlHelper(operation.LoopControlVariable.Syntax, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); } else { SpillEvalStack(); RegionBuilder currentRegion = CurrentRegionRequired; limitValueId = GetNextCaptureId(loopRegion); VisitAndCapture(operation.LimitValue, limitValueId); stepValueId = GetNextCaptureId(loopRegion); VisitAndCapture(operation.StepValue, stepValueId); IOperation stepValue = GetCaptureReference(stepValueId, operation.StepValue); if (userDefinedInfo != null) { Debug.Assert(_forToLoopBinaryOperatorLeftOperand == null); Debug.Assert(_forToLoopBinaryOperatorRightOperand == null); // calculate and cache result of a positive check := step >= (step - step). _forToLoopBinaryOperatorLeftOperand = GetCaptureReference(stepValueId, operation.StepValue); _forToLoopBinaryOperatorRightOperand = GetCaptureReference(stepValueId, operation.StepValue); IOperation subtraction = VisitRequired(userDefinedInfo.Subtraction); _forToLoopBinaryOperatorLeftOperand = stepValue; _forToLoopBinaryOperatorRightOperand = subtraction; int positiveFlagId = GetNextCaptureId(loopRegion); VisitAndCapture(userDefinedInfo.GreaterThanOrEqual, positiveFlagId); positiveFlag = GetCaptureReference(positiveFlagId, userDefinedInfo.GreaterThanOrEqual); _forToLoopBinaryOperatorLeftOperand = null; _forToLoopBinaryOperatorRightOperand = null; } else if (!(operation.StepValue.GetConstantValue() is { IsBad: false }) && !ITypeSymbolHelpers.IsSignedIntegralType(stepEnumUnderlyingTypeOrSelf) && !ITypeSymbolHelpers.IsUnsignedIntegralType(stepEnumUnderlyingTypeOrSelf)) { IOperation? stepValueIsNull = null; if (ITypeSymbolHelpers.IsNullableType(stepValue.Type)) { stepValueIsNull = MakeIsNullOperation(GetCaptureReference(stepValueId, operation.StepValue), booleanType); stepValue = CallNullableMember(stepValue, SpecialMember.System_Nullable_T_GetValueOrDefault); } ITypeSymbol? stepValueEnumUnderlyingTypeOrSelf = ITypeSymbolHelpers.GetEnumUnderlyingTypeOrSelf(stepValue.Type); if (ITypeSymbolHelpers.IsNumericType(stepValueEnumUnderlyingTypeOrSelf)) { // this one is tricky. // step value is not used directly in the loop condition // however its value determines the iteration direction // isUp = IsTrue(step >= step - step) // which implies that "step = null" ==> "isUp = false" IOperation isUp; int positiveFlagId = GetNextCaptureId(loopRegion); var afterPositiveCheck = new BasicBlockBuilder(BasicBlockKind.Block); if (stepValueIsNull != null) { var whenNotNull = new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(stepValueIsNull, jumpIfTrue: false, whenNotNull); _currentBasicBlock = null; // "isUp = false" isUp = new LiteralOperation(semanticModel: null, stepValue.Syntax, booleanType, constantValue: ConstantValue.Create(false), isImplicit: true); AddStatement(new FlowCaptureOperation(positiveFlagId, isUp.Syntax, isUp)); UnconditionalBranch(afterPositiveCheck); AppendNewBlock(whenNotNull); } IOperation literal = new LiteralOperation(semanticModel: null, stepValue.Syntax, stepValue.Type, constantValue: ConstantValue.Default(stepValueEnumUnderlyingTypeOrSelf.SpecialType), isImplicit: true); isUp = new BinaryOperation(BinaryOperatorKind.GreaterThanOrEqual, stepValue, literal, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, stepValue.Syntax, booleanType, constantValue: null, isImplicit: true); AddStatement(new FlowCaptureOperation(positiveFlagId, isUp.Syntax, isUp)); AppendNewBlock(afterPositiveCheck); positiveFlag = GetCaptureReference(positiveFlagId, isUp); } else { // This must be an error case. // It is fine to do nothing in this case, we are in recovery mode. } } IOperation initialValue = PopOperand(); AddStatement(new SimpleAssignmentOperation(isRef: false, // Loop control variable PopOperand(), initialValue, semanticModel: null, operation.InitialValue.Syntax, type: null, constantValue: null, isImplicit: true)); } PopStackFrameAndLeaveRegion(frame); } void checkLoopCondition() { if (isObjectLoop) { // For i as Object = 3 To 6 step 2 // body // Next // // becomes ==> // // { // Dim loopObj ' mysterious object that holds the loop state // // ' helper does internal initialization and tells if we need to do any iterations // if Not ObjectFlowControl.ForLoopControl.ForLoopInitObj(ctrl, init, limit, step, ref loopObj, ref ctrl) // goto exit: // start: // body // // continue: // ' helper updates loop state and tells if we need to do another iteration. // if ObjectFlowControl.ForLoopControl.ForNextCheckObj(ctrl, loopObj, ref ctrl) // GoTo start // } // exit: EvalStackFrame frame = PushStackFrame(); PushOperand(visitLoopControlVariableReference(forceImplicit: true)); IOperation condition = tryCallObjectForLoopControlHelper(operation.LimitValue.Syntax, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); return; } else if (userDefinedInfo != null) { Debug.Assert(_forToLoopBinaryOperatorLeftOperand == null); Debug.Assert(_forToLoopBinaryOperatorRightOperand == null); // Generate If(positiveFlag, controlVariable <= limit, controlVariable >= limit) EvalStackFrame frame = PushStackFrame(); // Spill control variable reference, we are going to have branches here. PushOperand(visitLoopControlVariableReference(forceImplicit: true)); // Yes we are going to evaluate it again SpillEvalStack(); IOperation controlVariableReferenceForCondition = PopOperand(); var notPositive = new BasicBlockBuilder(BasicBlockKind.Block); Debug.Assert(positiveFlag is not null); ConditionalBranch(positiveFlag, jumpIfTrue: false, notPositive); _currentBasicBlock = null; _forToLoopBinaryOperatorLeftOperand = controlVariableReferenceForCondition; _forToLoopBinaryOperatorRightOperand = GetCaptureReference(limitValueId, operation.LimitValue); VisitConditionalBranch(userDefinedInfo.LessThanOrEqual, ref @break, jumpIfTrue: false); UnconditionalBranch(bodyBlock); AppendNewBlock(notPositive); _forToLoopBinaryOperatorLeftOperand = OperationCloner.CloneOperation(_forToLoopBinaryOperatorLeftOperand); _forToLoopBinaryOperatorRightOperand = OperationCloner.CloneOperation(_forToLoopBinaryOperatorRightOperand); VisitConditionalBranch(userDefinedInfo.GreaterThanOrEqual, ref @break, jumpIfTrue: false); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); _forToLoopBinaryOperatorLeftOperand = null; _forToLoopBinaryOperatorRightOperand = null; return; } else { EvalStackFrame frame = PushStackFrame(); PushOperand(visitLoopControlVariableReference(forceImplicit: true)); // Yes we are going to evaluate it again IOperation limitReference = GetCaptureReference(limitValueId, operation.LimitValue); var comparisonKind = BinaryOperatorKind.None; // unsigned step is always Up if (ITypeSymbolHelpers.IsUnsignedIntegralType(stepEnumUnderlyingTypeOrSelf)) { comparisonKind = BinaryOperatorKind.LessThanOrEqual; } else if (operation.StepValue.GetConstantValue() is { IsBad: false } value) { Debug.Assert(value.Discriminator != ConstantValueTypeDiscriminator.Bad); if (value.IsNegativeNumeric) { comparisonKind = BinaryOperatorKind.GreaterThanOrEqual; } else if (value.IsNumeric) { comparisonKind = BinaryOperatorKind.LessThanOrEqual; } } // for signed integral steps not known at compile time // we do " (val Xor (step >> 31)) <= (limit Xor (step >> 31)) " // where 31 is actually the size-1 if (comparisonKind == BinaryOperatorKind.None && ITypeSymbolHelpers.IsSignedIntegralType(stepEnumUnderlyingTypeOrSelf)) { comparisonKind = BinaryOperatorKind.LessThanOrEqual; PushOperand(negateIfStepNegative(PopOperand())); limitReference = negateIfStepNegative(limitReference); } IOperation condition; if (comparisonKind != BinaryOperatorKind.None) { condition = new BinaryOperation(comparisonKind, PopOperand(), limitReference, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.LimitValue.Syntax, booleanType, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); return; } if (positiveFlag == null) { // Must be an error case. condition = MakeInvalidOperation(operation.LimitValue.Syntax, booleanType, PopOperand(), limitReference); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); return; } IOperation? eitherLimitOrControlVariableIsNull = null; if (ITypeSymbolHelpers.IsNullableType(operation.LimitValue.Type)) { eitherLimitOrControlVariableIsNull = new BinaryOperation(BinaryOperatorKind.Or, MakeIsNullOperation(limitReference, booleanType), MakeIsNullOperation(PopOperand(), booleanType), isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.StepValue.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), constantValue: null, isImplicit: true); // if either limit or control variable is null, we exit the loop var whenBothNotNull = new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(eitherLimitOrControlVariableIsNull, jumpIfTrue: false, whenBothNotNull); UnconditionalBranch(@break); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(whenBothNotNull); frame = PushStackFrame(); PushOperand(CallNullableMember(visitLoopControlVariableReference(forceImplicit: true), SpecialMember.System_Nullable_T_GetValueOrDefault)); // Yes we are going to evaluate it again limitReference = CallNullableMember(GetCaptureReference(limitValueId, operation.LimitValue), SpecialMember.System_Nullable_T_GetValueOrDefault); } // If (positiveFlag, ctrl <= limit, ctrl >= limit) SpillEvalStack(); IOperation controlVariableReferenceforCondition = PopOperand(); var notPositive = new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(positiveFlag, jumpIfTrue: false, notPositive); _currentBasicBlock = null; condition = new BinaryOperation(BinaryOperatorKind.LessThanOrEqual, controlVariableReferenceforCondition, limitReference, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.LimitValue.Syntax, booleanType, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); AppendNewBlock(notPositive); condition = new BinaryOperation(BinaryOperatorKind.GreaterThanOrEqual, OperationCloner.CloneOperation(controlVariableReferenceforCondition), OperationCloner.CloneOperation(limitReference), isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.LimitValue.Syntax, booleanType, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); return; } throw ExceptionUtilities.Unreachable; } // Produce "(operand Xor (step >> 31))" // where 31 is actually the size-1 IOperation negateIfStepNegative(IOperation operand) { int bits = stepEnumUnderlyingTypeOrSelf.SpecialType.VBForToShiftBits(); var shiftConst = new LiteralOperation(semanticModel: null, operand.Syntax, _compilation.GetSpecialType(SpecialType.System_Int32), constantValue: ConstantValue.Create(bits), isImplicit: true); var shiftedStep = new BinaryOperation(BinaryOperatorKind.RightShift, GetCaptureReference(stepValueId, operation.StepValue), shiftConst, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operand.Syntax, operation.StepValue.Type, constantValue: null, isImplicit: true); return new BinaryOperation(BinaryOperatorKind.ExclusiveOr, shiftedStep, operand, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operand.Syntax, operand.Type, constantValue: null, isImplicit: true); } void incrementLoopControlVariable() { if (isObjectLoop) { // there is nothing interesting to do here, increment is folded into the condition check return; } else if (userDefinedInfo != null) { Debug.Assert(_forToLoopBinaryOperatorLeftOperand == null); Debug.Assert(_forToLoopBinaryOperatorRightOperand == null); EvalStackFrame frame = PushStackFrame(); IOperation controlVariableReferenceForAssignment = visitLoopControlVariableReference(forceImplicit: true); // Yes we are going to evaluate it again // We are going to evaluate control variable again and that might require branches PushOperand(controlVariableReferenceForAssignment); // Generate: controlVariable + stepValue _forToLoopBinaryOperatorLeftOperand = visitLoopControlVariableReference(forceImplicit: true); // Yes we are going to evaluate it again _forToLoopBinaryOperatorRightOperand = GetCaptureReference(stepValueId, operation.StepValue); IOperation increment = VisitRequired(userDefinedInfo.Addition); _forToLoopBinaryOperatorLeftOperand = null; _forToLoopBinaryOperatorRightOperand = null; controlVariableReferenceForAssignment = PopOperand(); AddStatement(new SimpleAssignmentOperation(isRef: false, controlVariableReferenceForAssignment, increment, semanticModel: null, controlVariableReferenceForAssignment.Syntax, type: null, constantValue: null, isImplicit: true)); PopStackFrameAndLeaveRegion(frame); } else { BasicBlockBuilder afterIncrement = new BasicBlockBuilder(BasicBlockKind.Block); IOperation controlVariableReferenceForAssignment; bool isNullable = ITypeSymbolHelpers.IsNullableType(operation.StepValue.Type); EvalStackFrame frame = PushStackFrame(); PushOperand(visitLoopControlVariableReference(forceImplicit: true)); // Yes we are going to evaluate it again if (isNullable) { // Spill control variable reference, we are going to have branches here. SpillEvalStack(); BasicBlockBuilder whenNotNull = new BasicBlockBuilder(BasicBlockKind.Block); EvalStackFrame nullCheckFrame = PushStackFrame(); IOperation condition = new BinaryOperation(BinaryOperatorKind.Or, MakeIsNullOperation(GetCaptureReference(stepValueId, operation.StepValue), booleanType), MakeIsNullOperation(visitLoopControlVariableReference(forceImplicit: true), // Yes we are going to evaluate it again booleanType), isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.StepValue.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, whenNotNull); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(nullCheckFrame); controlVariableReferenceForAssignment = OperationCloner.CloneOperation(PeekOperand()); Debug.Assert(controlVariableReferenceForAssignment.Kind == OperationKind.FlowCaptureReference); AddStatement(new SimpleAssignmentOperation(isRef: false, controlVariableReferenceForAssignment, new DefaultValueOperation(semanticModel: null, controlVariableReferenceForAssignment.Syntax, controlVariableReferenceForAssignment.Type, constantValue: null, isImplicit: true), semanticModel: null, controlVariableReferenceForAssignment.Syntax, type: null, constantValue: null, isImplicit: true)); UnconditionalBranch(afterIncrement); AppendNewBlock(whenNotNull); } IOperation controlVariableReferenceForIncrement = visitLoopControlVariableReference(forceImplicit: true); // Yes we are going to evaluate it again IOperation stepValueForIncrement = GetCaptureReference(stepValueId, operation.StepValue); if (isNullable) { Debug.Assert(ITypeSymbolHelpers.IsNullableType(controlVariableReferenceForIncrement.Type)); controlVariableReferenceForIncrement = CallNullableMember(controlVariableReferenceForIncrement, SpecialMember.System_Nullable_T_GetValueOrDefault); stepValueForIncrement = CallNullableMember(stepValueForIncrement, SpecialMember.System_Nullable_T_GetValueOrDefault); } IOperation increment = new BinaryOperation(BinaryOperatorKind.Add, controlVariableReferenceForIncrement, stepValueForIncrement, isLifted: false, isChecked: operation.IsChecked, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.StepValue.Syntax, controlVariableReferenceForIncrement.Type, constantValue: null, isImplicit: true); controlVariableReferenceForAssignment = PopOperand(); if (isNullable) { Debug.Assert(controlVariableReferenceForAssignment.Type != null); increment = MakeNullable(increment, controlVariableReferenceForAssignment.Type); } AddStatement(new SimpleAssignmentOperation(isRef: false, controlVariableReferenceForAssignment, increment, semanticModel: null, controlVariableReferenceForAssignment.Syntax, type: null, constantValue: null, isImplicit: true)); PopStackFrame(frame, mergeNestedRegions: !isNullable); // We have a branch out in between when nullable is involved LeaveRegionIfAny(frame); AppendNewBlock(afterIncrement); } } IOperation visitLoopControlVariableReference(bool forceImplicit) { switch (operation.LoopControlVariable.Kind) { case OperationKind.VariableDeclarator: var declarator = (IVariableDeclaratorOperation)operation.LoopControlVariable; ILocalSymbol local = declarator.Symbol; return new LocalReferenceOperation(local, isDeclaration: true, semanticModel: null, declarator.Syntax, local.Type, constantValue: null, isImplicit: true); default: Debug.Assert(!_forceImplicit); _forceImplicit = forceImplicit; IOperation result = VisitRequired(operation.LoopControlVariable); _forceImplicit = false; return result; } } } private static FlowCaptureReferenceOperation GetCaptureReference(int id, IOperation underlying) { return new FlowCaptureReferenceOperation(id, underlying.Syntax, underlying.Type, underlying.GetConstantValue()); } internal override IOperation VisitAggregateQuery(IAggregateQueryOperation operation, int? captureIdForResult) { SpillEvalStack(); IOperation? previousAggregationGroup = _currentAggregationGroup; _currentAggregationGroup = VisitAndCapture(operation.Group); IOperation result = VisitRequired(operation.Aggregation); _currentAggregationGroup = previousAggregationGroup; return result; } public override IOperation? VisitSwitch(ISwitchOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); IOperation switchValue = VisitAndCapture(operation.Value); ImmutableArray<ILocalSymbol> locals = getLocals(); var switchRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: locals); EnterRegion(switchRegion); BasicBlockBuilder? defaultBody = null; // Adjusted in handleSection BasicBlockBuilder @break = GetLabeledOrNewBlock(operation.ExitLabel); foreach (ISwitchCaseOperation section in operation.Cases) { handleSection(section); } Debug.Assert(_currentRegion == switchRegion); if (defaultBody != null) { UnconditionalBranch(defaultBody); } LeaveRegion(); AppendNewBlock(@break); return FinishVisitingStatement(operation); ImmutableArray<ILocalSymbol> getLocals() { ImmutableArray<ILocalSymbol> l = operation.Locals; foreach (ISwitchCaseOperation section in operation.Cases) { l = l.Concat(section.Locals); } return l; } void handleSection(ISwitchCaseOperation section) { var body = new BasicBlockBuilder(BasicBlockKind.Block); var nextSection = new BasicBlockBuilder(BasicBlockKind.Block); IOperation? condition = ((SwitchCaseOperation)section).Condition; if (condition != null) { Debug.Assert(section.Clauses.All(c => c.Label == null)); Debug.Assert(_currentSwitchOperationExpression == null); _currentSwitchOperationExpression = switchValue; VisitConditionalBranch(condition, ref nextSection, jumpIfTrue: false); _currentSwitchOperationExpression = null; } else { foreach (ICaseClauseOperation caseClause in section.Clauses) { var nextCase = new BasicBlockBuilder(BasicBlockKind.Block); handleCase(caseClause, body, nextCase); AppendNewBlock(nextCase); } UnconditionalBranch(nextSection); } AppendNewBlock(body); VisitStatements(section.Body); UnconditionalBranch(@break); AppendNewBlock(nextSection); } void handleCase(ICaseClauseOperation caseClause, BasicBlockBuilder body, [DisallowNull] BasicBlockBuilder? nextCase) { IOperation condition; BasicBlockBuilder labeled = GetLabeledOrNewBlock(caseClause.Label); LinkBlocks(labeled, body); switch (caseClause.CaseKind) { case CaseKind.SingleValue: handleEqualityCheck(((ISingleValueCaseClauseOperation)caseClause).Value); break; void handleEqualityCheck(IOperation compareWith) { bool leftIsNullable = ITypeSymbolHelpers.IsNullableType(operation.Value.Type); bool rightIsNullable = ITypeSymbolHelpers.IsNullableType(compareWith.Type); bool isLifted = leftIsNullable || rightIsNullable; EvalStackFrame frame = PushStackFrame(); PushOperand(OperationCloner.CloneOperation(switchValue)); IOperation rightOperand = VisitRequired(compareWith); IOperation leftOperand = PopOperand(); if (isLifted) { if (!leftIsNullable) { if (leftOperand.Type != null) { Debug.Assert(compareWith.Type != null); leftOperand = MakeNullable(leftOperand, compareWith.Type); } } else if (!rightIsNullable && rightOperand.Type != null) { Debug.Assert(operation.Value.Type != null); rightOperand = MakeNullable(rightOperand, operation.Value.Type); } } condition = new BinaryOperation(BinaryOperatorKind.Equals, leftOperand, rightOperand, isLifted, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, compareWith.Syntax, booleanType, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, nextCase); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(labeled); _currentBasicBlock = null; } case CaseKind.Pattern: { var patternClause = (IPatternCaseClauseOperation)caseClause; EvalStackFrame frame = PushStackFrame(); PushOperand(OperationCloner.CloneOperation(switchValue)); var pattern = (IPatternOperation)VisitRequired(patternClause.Pattern); condition = new IsPatternOperation(PopOperand(), pattern, semanticModel: null, patternClause.Pattern.Syntax, booleanType, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, nextCase); PopStackFrameAndLeaveRegion(frame); if (patternClause.Guard != null) { AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); VisitConditionalBranch(patternClause.Guard, ref nextCase, jumpIfTrue: false); } AppendNewBlock(labeled); _currentBasicBlock = null; } break; case CaseKind.Relational: var relationalValueClause = (IRelationalCaseClauseOperation)caseClause; if (relationalValueClause.Relation == BinaryOperatorKind.Equals) { handleEqualityCheck(relationalValueClause.Value); break; } // A switch section with a relational case other than an equality must have // a condition associated with it. This point should not be reachable. throw ExceptionUtilities.UnexpectedValue(relationalValueClause.Relation); case CaseKind.Default: var defaultClause = (IDefaultCaseClauseOperation)caseClause; if (defaultBody == null) { defaultBody = labeled; } // 'default' clause is never entered from the top, we'll jump back to it after all // sections are processed. UnconditionalBranch(nextCase); AppendNewBlock(labeled); _currentBasicBlock = null; break; case CaseKind.Range: // A switch section with a range case must have a condition associated with it. // This point should not be reachable. default: throw ExceptionUtilities.UnexpectedValue(caseClause.CaseKind); } } } private IOperation MakeNullable(IOperation operand, ITypeSymbol type) { Debug.Assert(ITypeSymbolHelpers.IsNullableType(type)); Debug.Assert(ITypeSymbolHelpers.GetNullableUnderlyingType(type).Equals(operand.Type)); return CreateConversion(operand, type); } public override IOperation VisitSwitchCase(ISwitchCaseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitRangeCaseClause(IRangeCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitPatternCaseClause(IPatternCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation? VisitEnd(IEndOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); BasicBlockBuilder current = CurrentBasicBlock; AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block), linkToPrevious: false); Debug.Assert(current.BranchValue == null); Debug.Assert(!current.HasCondition); Debug.Assert(current.FallThrough.Destination == null); Debug.Assert(current.FallThrough.Kind == ControlFlowBranchSemantics.None); current.FallThrough.Kind = ControlFlowBranchSemantics.ProgramTermination; return FinishVisitingStatement(operation); } public override IOperation? VisitForLoop(IForLoopOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); // for (initializer; condition; increment) // body; // // becomes the following (with block added for locals) // // { // initializer; // start: // { // GotoIfFalse condition break; // body; // continue: // increment; // goto start; // } // } // break: EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals)); ImmutableArray<IOperation> initialization = operation.Before; if (initialization.Length == 1 && initialization[0].Kind == OperationKind.VariableDeclarationGroup) { HandleVariableDeclarations((VariableDeclarationGroupOperation)initialization.Single()); } else { VisitStatements(initialization); } var start = new BasicBlockBuilder(BasicBlockKind.Block); AppendNewBlock(start); EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.ConditionLocals)); var @break = GetLabeledOrNewBlock(operation.ExitLabel); if (operation.Condition != null) { VisitConditionalBranch(operation.Condition, ref @break, jumpIfTrue: false); } VisitStatement(operation.Body); var @continue = GetLabeledOrNewBlock(operation.ContinueLabel); AppendNewBlock(@continue); VisitStatements(operation.AtLoopBottom); UnconditionalBranch(start); LeaveRegion(); // ConditionLocals LeaveRegion(); // Locals AppendNewBlock(@break); return FinishVisitingStatement(operation); } internal override IOperation? VisitFixed(IFixedOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals)); HandleVariableDeclarations(operation.Variables); VisitStatement(operation.Body); LeaveRegion(); return FinishVisitingStatement(operation); } public override IOperation? VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, int? captureIdForResult) { // Anything that has a declaration group (such as for loops) needs to handle them directly itself, // this should only be encountered by the visitor for declaration statements. StartVisitingStatement(operation); HandleVariableDeclarations(operation); return FinishVisitingStatement(operation); } private void HandleVariableDeclarations(IVariableDeclarationGroupOperation operation) { // We erase variable declarations from the control flow graph, as variable lifetime information is // contained in a parallel data structure. foreach (var declaration in operation.Declarations) { HandleVariableDeclaration(declaration); } } private void HandleVariableDeclaration(IVariableDeclarationOperation operation) { foreach (IVariableDeclaratorOperation declarator in operation.Declarators) { HandleVariableDeclarator(operation, declarator); } } private void HandleVariableDeclarator(IVariableDeclarationOperation declaration, IVariableDeclaratorOperation declarator) { if (declarator.Initializer == null && declaration.Initializer == null) { return; } ILocalSymbol localSymbol = declarator.Symbol; // If the local is a static (possible in VB), then we create a semaphore for conditional execution of the initializer. BasicBlockBuilder? afterInitialization = null; if (localSymbol.IsStatic) { afterInitialization = new BasicBlockBuilder(BasicBlockKind.Block); ITypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); var initializationSemaphore = new StaticLocalInitializationSemaphoreOperation(localSymbol, declarator.Syntax, booleanType); ConditionalBranch(initializationSemaphore, jumpIfTrue: false, afterInitialization); _currentBasicBlock = null; EnterRegion(new RegionBuilder(ControlFlowRegionKind.StaticLocalInitializer)); } EvalStackFrame frame = PushStackFrame(); IOperation? initializer = null; SyntaxNode? assignmentSyntax = null; if (declarator.Initializer != null) { initializer = Visit(declarator.Initializer.Value); assignmentSyntax = declarator.Syntax; } if (declaration.Initializer != null) { IOperation operationInitializer = VisitRequired(declaration.Initializer.Value); assignmentSyntax = declaration.Syntax; if (initializer != null) { initializer = new InvalidOperation(ImmutableArray.Create(initializer, operationInitializer), semanticModel: null, declaration.Syntax, type: localSymbol.Type, constantValue: null, isImplicit: true); } else { initializer = operationInitializer; } } Debug.Assert(initializer != null && assignmentSyntax != null); // If we have an afterInitialization, then we must have static local and an initializer to ensure we don't create empty regions that can't be cleaned up. Debug.Assert((afterInitialization, localSymbol.IsStatic) is (null, false) or (not null, true)); // We can't use the IdentifierToken as the syntax for the local reference, so we use the // entire declarator as the node var localRef = new LocalReferenceOperation(localSymbol, isDeclaration: true, semanticModel: null, declarator.Syntax, localSymbol.Type, constantValue: null, isImplicit: true); var assignment = new SimpleAssignmentOperation(isRef: localSymbol.IsRef, localRef, initializer, semanticModel: null, assignmentSyntax, localRef.Type, constantValue: null, isImplicit: true); AddStatement(assignment); PopStackFrameAndLeaveRegion(frame); if (localSymbol.IsStatic) { LeaveRegion(); AppendNewBlock(afterInitialization!); } } public override IOperation VisitVariableDeclaration(IVariableDeclarationOperation operation, int? captureIdForResult) { // All variable declarators should be handled by VisitVariableDeclarationGroup. throw ExceptionUtilities.Unreachable; } public override IOperation VisitVariableDeclarator(IVariableDeclaratorOperation operation, int? captureIdForResult) { // All variable declarators should be handled by VisitVariableDeclaration. throw ExceptionUtilities.Unreachable; } public override IOperation VisitVariableInitializer(IVariableInitializerOperation operation, int? captureIdForResult) { // All variable initializers should be removed from the tree by VisitVariableDeclaration. throw ExceptionUtilities.Unreachable; } public override IOperation VisitFlowCapture(IFlowCaptureOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitIsNull(IIsNullOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitCaughtException(ICaughtExceptionOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitInvocation(IInvocationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); IOperation? instance = operation.TargetMethod.IsStatic ? null : operation.Instance; (IOperation? visitedInstance, ImmutableArray<IArgumentOperation> visitedArguments) = VisitInstanceWithArguments(instance, operation.Arguments); PopStackFrame(frame); return new InvocationOperation(operation.TargetMethod, visitedInstance, operation.IsVirtual, visitedArguments, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } private (IOperation? visitedInstance, ImmutableArray<IArgumentOperation> visitedArguments) VisitInstanceWithArguments(IOperation? instance, ImmutableArray<IArgumentOperation> arguments) { if (instance != null) { PushOperand(VisitRequired(instance)); } ImmutableArray<IArgumentOperation> visitedArguments = VisitArguments(arguments); IOperation? visitedInstance = instance == null ? null : PopOperand(); return (visitedInstance, visitedArguments); } internal override IOperation VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, int? argument) { EvalStackFrame frame = PushStackFrame(); // Initializer is removed from the tree and turned into a series of statements that assign to the created instance IOperation initializedInstance = new NoPiaObjectCreationOperation(initializer: null, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, initializedInstance)); } public override IOperation VisitObjectCreation(IObjectCreationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); EvalStackFrame argumentsFrame = PushStackFrame(); ImmutableArray<IArgumentOperation> visitedArgs = VisitArguments(operation.Arguments); PopStackFrame(argumentsFrame); // Initializer is removed from the tree and turned into a series of statements that assign to the created instance IOperation initializedInstance = new ObjectCreationOperation(operation.Constructor, initializer: null, visitedArgs, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, initializedInstance)); } public override IOperation VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); var initializedInstance = new TypeParameterObjectCreationOperation(initializer: null, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, initializedInstance)); } public override IOperation VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); EvalStackFrame argumentsFrame = PushStackFrame(); ImmutableArray<IOperation> visitedArguments = VisitArray(operation.Arguments); PopStackFrame(argumentsFrame); var hasDynamicArguments = (HasDynamicArgumentsExpression)operation; IOperation initializedInstance = new DynamicObjectCreationOperation(initializer: null, visitedArguments, hasDynamicArguments.ArgumentNames, hasDynamicArguments.ArgumentRefKinds, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, initializedInstance)); } private IOperation HandleObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation? initializer, IOperation objectCreation) { // If the initializer is null, nothing to spill. Just return the original instance. if (initializer == null || initializer.Initializers.IsEmpty) { return objectCreation; } // Initializer wasn't null, so spill the stack and capture the initialized instance. Returns a reference to the captured instance. PushOperand(objectCreation); SpillEvalStack(); objectCreation = PopOperand(); visitInitializer(initializer, objectCreation); return objectCreation; void visitInitializer(IObjectOrCollectionInitializerOperation initializerOperation, IOperation initializedInstance) { ImplicitInstanceInfo previousInitializedInstance = _currentImplicitInstance; _currentImplicitInstance = new ImplicitInstanceInfo(initializedInstance); foreach (IOperation innerInitializer in initializerOperation.Initializers) { handleInitializer(innerInitializer); } _currentImplicitInstance = previousInitializedInstance; } void handleInitializer(IOperation innerInitializer) { switch (innerInitializer.Kind) { case OperationKind.MemberInitializer: handleMemberInitializer((IMemberInitializerOperation)innerInitializer); return; case OperationKind.SimpleAssignment: handleSimpleAssignment((ISimpleAssignmentOperation)innerInitializer); return; default: // This assert is to document the list of things we know are possible to go through the default handler. It's possible there // are other nodes that will go through here, and if a new test triggers this assert, it will likely be fine to just add // the node type to the assert. It's here merely to ensure that we think about whether that node type actually does need // special handling in the context of a collection or object initializer before just assuming that it's fine. #if DEBUG var validKinds = ImmutableArray.Create(OperationKind.Invocation, OperationKind.DynamicInvocation, OperationKind.Increment, OperationKind.Literal, OperationKind.LocalReference, OperationKind.Binary, OperationKind.FieldReference, OperationKind.Invalid); Debug.Assert(validKinds.Contains(innerInitializer.Kind)); #endif EvalStackFrame frame = PushStackFrame(); AddStatement(Visit(innerInitializer)); PopStackFrameAndLeaveRegion(frame); return; } } void handleSimpleAssignment(ISimpleAssignmentOperation assignmentOperation) { EvalStackFrame frame = PushStackFrame(); bool pushSuccess = tryPushTarget(assignmentOperation.Target); IOperation result; if (!pushSuccess) { // Error case. We don't try any error recovery here, just return whatever the default visit would. result = VisitRequired(assignmentOperation); } else { // We push the target, which effectively pushes individual components of the target (ie the instance, and arguments if present). // After that has been pushed, we visit the value of the assignment, to ensure that the instance is captured if // needed. Finally, we reassemble the target, which will pull the potentially captured instance from the stack // and reassemble the member reference from the parts. IOperation right = VisitRequired(assignmentOperation.Value); IOperation left = popTarget(assignmentOperation.Target); result = new SimpleAssignmentOperation(assignmentOperation.IsRef, left, right, semanticModel: null, assignmentOperation.Syntax, assignmentOperation.Type, assignmentOperation.GetConstantValue(), IsImplicit(assignmentOperation)); } AddStatement(result); PopStackFrameAndLeaveRegion(frame); } void handleMemberInitializer(IMemberInitializerOperation memberInitializer) { // We explicitly do not push the initialized member onto the stack here. We visit the initialized member to get the implicit receiver that will be substituted in when an // IInstanceReferenceOperation with InstanceReferenceKind.ImplicitReceiver is encountered. If that receiver needs to be pushed onto the stack, its parent will handle it. // In member initializers, the code generated will evaluate InitializedMember multiple times. For example, if you have the following: // // class C1 // { // public C2 C2 { get; set; } = new C2(); // public void M() // { // var x = new C1 { C2 = { P1 = 1, P2 = 2 } }; // } // } // class C2 // { // public int P1 { get; set; } // public int P2 { get; set; } // } // // We generate the following code for C1.M(). Note the multiple calls to C1::get_C2(). // IL_0000: nop // IL_0001: newobj instance void C1::.ctor() // IL_0006: dup // IL_0007: callvirt instance class C2 C1::get_C2() // IL_000c: ldc.i4.1 // IL_000d: callvirt instance void C2::set_P1(int32) // IL_0012: nop // IL_0013: dup // IL_0014: callvirt instance class C2 C1::get_C2() // IL_0019: ldc.i4.2 // IL_001a: callvirt instance void C2::set_P2(int32) // IL_001f: nop // IL_0020: stloc.0 // IL_0021: ret // // We therefore visit the InitializedMember to get the implicit receiver for the contained initializer, and that implicit receiver will be cloned everywhere it encounters // an IInstanceReferenceOperation with ReferenceKind InstanceReferenceKind.ImplicitReceiver EvalStackFrame frame = PushStackFrame(); bool pushSuccess = tryPushTarget(memberInitializer.InitializedMember); IOperation instance = pushSuccess ? popTarget(memberInitializer.InitializedMember) : VisitRequired(memberInitializer.InitializedMember); visitInitializer(memberInitializer.Initializer, instance); PopStackFrameAndLeaveRegion(frame); } bool tryPushTarget(IOperation instance) { switch (instance.Kind) { case OperationKind.FieldReference: case OperationKind.EventReference: case OperationKind.PropertyReference: var memberReference = (IMemberReferenceOperation)instance; if (memberReference.Kind == OperationKind.PropertyReference) { // We assume all arguments have side effects and spill them. We only avoid recapturing things that have already been captured once. VisitAndPushArray(((IPropertyReferenceOperation)memberReference).Arguments, UnwrapArgument); SpillEvalStack(); } // If there is control flow in the value being assigned, we want to make sure that // the instance is captured appropriately, but the setter/field load in the reference will only be evaluated after // the value has been evaluated. So we assemble the reference after visiting the value. if (!memberReference.Member.IsStatic && memberReference.Instance != null) { PushOperand(VisitRequired(memberReference.Instance)); } return true; case OperationKind.ArrayElementReference: var arrayReference = (IArrayElementReferenceOperation)instance; VisitAndPushArray(arrayReference.Indices); SpillEvalStack(); PushOperand(VisitRequired(arrayReference.ArrayReference)); return true; case OperationKind.DynamicIndexerAccess: var dynamicIndexer = (IDynamicIndexerAccessOperation)instance; VisitAndPushArray(dynamicIndexer.Arguments); SpillEvalStack(); PushOperand(VisitRequired(dynamicIndexer.Operation)); return true; case OperationKind.DynamicMemberReference: var dynamicReference = (IDynamicMemberReferenceOperation)instance; if (dynamicReference.Instance != null) { PushOperand(VisitRequired(dynamicReference.Instance)); } return true; default: // As in the assert in handleInitializer, this assert documents the operation kinds that we know go through this path, // and it is possible others go through here as well. If they are encountered, we simply need to ensure // that they don't have any interesting semantics in object or collection initialization contexts and add them to the // assert. Debug.Assert(instance.Kind == OperationKind.Invalid || instance.Kind == OperationKind.None); return false; } } IOperation popTarget(IOperation originalTarget) { IOperation? instance; switch (originalTarget.Kind) { case OperationKind.FieldReference: var fieldReference = (IFieldReferenceOperation)originalTarget; instance = (!fieldReference.Member.IsStatic && fieldReference.Instance != null) ? PopOperand() : null; return new FieldReferenceOperation(fieldReference.Field, fieldReference.IsDeclaration, instance, semanticModel: null, fieldReference.Syntax, fieldReference.Type, fieldReference.GetConstantValue(), IsImplicit(fieldReference)); case OperationKind.EventReference: var eventReference = (IEventReferenceOperation)originalTarget; instance = (!eventReference.Member.IsStatic && eventReference.Instance != null) ? PopOperand() : null; return new EventReferenceOperation(eventReference.Event, instance, semanticModel: null, eventReference.Syntax, eventReference.Type, IsImplicit(eventReference)); case OperationKind.PropertyReference: var propertyReference = (IPropertyReferenceOperation)originalTarget; instance = (!propertyReference.Member.IsStatic && propertyReference.Instance != null) ? PopOperand() : null; ImmutableArray<IArgumentOperation> propertyArguments = PopArray(propertyReference.Arguments, RewriteArgumentFromArray); return new PropertyReferenceOperation(propertyReference.Property, propertyArguments, instance, semanticModel: null, propertyReference.Syntax, propertyReference.Type, IsImplicit(propertyReference)); case OperationKind.ArrayElementReference: var arrayElementReference = (IArrayElementReferenceOperation)originalTarget; instance = PopOperand(); ImmutableArray<IOperation> indices = PopArray(arrayElementReference.Indices); return new ArrayElementReferenceOperation(instance, indices, semanticModel: null, originalTarget.Syntax, originalTarget.Type, IsImplicit(originalTarget)); case OperationKind.DynamicIndexerAccess: var dynamicAccess = (DynamicIndexerAccessOperation)originalTarget; instance = PopOperand(); ImmutableArray<IOperation> arguments = PopArray(dynamicAccess.Arguments); return new DynamicIndexerAccessOperation(instance, arguments, dynamicAccess.ArgumentNames, dynamicAccess.ArgumentRefKinds, semanticModel: null, dynamicAccess.Syntax, dynamicAccess.Type, IsImplicit(dynamicAccess)); case OperationKind.DynamicMemberReference: var dynamicReference = (IDynamicMemberReferenceOperation)originalTarget; instance = dynamicReference.Instance != null ? PopOperand() : null; return new DynamicMemberReferenceOperation(instance, dynamicReference.MemberName, dynamicReference.TypeArguments, dynamicReference.ContainingType, semanticModel: null, dynamicReference.Syntax, dynamicReference.Type, IsImplicit(dynamicReference)); default: // Unlike in tryPushTarget, we assume that if this method is called, we were successful in pushing, so // this must be one of the explicitly handled kinds throw ExceptionUtilities.UnexpectedValue(originalTarget.Kind); } } } public override IOperation VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, int? captureIdForResult) { Debug.Fail("This code path should not be reachable."); return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray<IOperation>.Empty); } public override IOperation VisitMemberInitializer(IMemberInitializerOperation operation, int? captureIdForResult) { Debug.Fail("This code path should not be reachable."); return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray<IOperation>.Empty); } public override IOperation VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, int? captureIdForResult) { if (operation.Initializers.IsEmpty) { return new AnonymousObjectCreationOperation(initializers: ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } ImplicitInstanceInfo savedCurrentImplicitInstance = _currentImplicitInstance; Debug.Assert(operation.Type is not null); _currentImplicitInstance = new ImplicitInstanceInfo((INamedTypeSymbol)operation.Type); Debug.Assert(_currentImplicitInstance.AnonymousTypePropertyValues is not null); SpillEvalStack(); EvalStackFrame frame = PushStackFrame(); var initializerBuilder = ArrayBuilder<IOperation>.GetInstance(operation.Initializers.Length); for (int i = 0; i < operation.Initializers.Length; i++) { var simpleAssignment = (ISimpleAssignmentOperation)operation.Initializers[i]; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Debug.Assert(propertyReference != null); Debug.Assert(propertyReference.Arguments.IsEmpty); Debug.Assert(propertyReference.Instance != null); Debug.Assert(propertyReference.Instance.Kind == OperationKind.InstanceReference); Debug.Assert(((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind == InstanceReferenceKind.ImplicitReceiver); var visitedPropertyInstance = new InstanceReferenceOperation(InstanceReferenceKind.ImplicitReceiver, semanticModel: null, propertyReference.Instance.Syntax, propertyReference.Instance.Type, IsImplicit(propertyReference.Instance)); IOperation visitedTarget = new PropertyReferenceOperation(propertyReference.Property, ImmutableArray<IArgumentOperation>.Empty, visitedPropertyInstance, semanticModel: null, propertyReference.Syntax, propertyReference.Type, IsImplicit(propertyReference)); IOperation visitedValue = visitAndCaptureInitializer(propertyReference.Property, simpleAssignment.Value); var visitedAssignment = new SimpleAssignmentOperation(isRef: simpleAssignment.IsRef, visitedTarget, visitedValue, semanticModel: null, simpleAssignment.Syntax, simpleAssignment.Type, simpleAssignment.GetConstantValue(), IsImplicit(simpleAssignment)); initializerBuilder.Add(visitedAssignment); } _currentImplicitInstance.Free(); _currentImplicitInstance = savedCurrentImplicitInstance; for (int i = 0; i < initializerBuilder.Count; i++) { PopOperand(); } PopStackFrame(frame); return new AnonymousObjectCreationOperation(initializerBuilder.ToImmutableAndFree(), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); IOperation visitAndCaptureInitializer(IPropertySymbol initializedProperty, IOperation initializer) { PushOperand(VisitRequired(initializer)); SpillEvalStack(); IOperation captured = PeekOperand(); // Keep it on the stack so that we know it is still used. // For VB, previously initialized properties can be referenced in subsequent initializers. // We store the capture Id for the property for such property references. // Note that for VB error cases with duplicate property names, all the property symbols are considered equal. // We use the last duplicate property's capture id and use it in subsequent property references. _currentImplicitInstance.AnonymousTypePropertyValues[initializedProperty] = captured; return captured; } } public override IOperation? VisitLocalFunction(ILocalFunctionOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); RegionBuilder owner = CurrentRegionRequired; while (owner.IsStackSpillRegion) { Debug.Assert(owner.Enclosing != null); owner = owner.Enclosing; } owner.Add(operation.Symbol, operation); return FinishVisitingStatement(operation); } private IOperation? VisitLocalFunctionAsRoot(ILocalFunctionOperation operation) { Debug.Assert(_currentStatement == null); VisitMethodBodies(operation.Body, operation.IgnoredBody); return null; } public override IOperation VisitAnonymousFunction(IAnonymousFunctionOperation operation, int? captureIdForResult) { _haveAnonymousFunction = true; return new FlowAnonymousFunctionOperation(GetCurrentContext(), operation, IsImplicit(operation)); } public override IOperation VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitArrayCreation(IArrayCreationOperation operation, int? captureIdForResult) { // We have couple of options on how to rewrite an array creation with an initializer: // 1) Retain the original tree shape so the visited IArrayCreationOperation still has an IArrayInitializerOperation child node. // 2) Lower the IArrayCreationOperation so it always has a null initializer, followed by explicit assignments // of the form "IArrayElementReference = value" for the array initializer values. // There will be no IArrayInitializerOperation in the tree with approach. // // We are going ahead with approach #1 for couple of reasons: // 1. Simplicity: The implementation is much simpler, and has a lot lower risk associated with it. // 2. Lack of array instance access in the initializer: Unlike the object/collection initializer scenario, // where the initializer can access the instance being initialized, array initializer does not have access // to the array instance being initialized, and hence it does not matter if the array allocation is done // before visiting the initializers or not. // // In future, based on the customer feedback, we can consider switching to approach #2 and lower the initializer into assignment(s). EvalStackFrame frame = PushStackFrame(); VisitAndPushArray(operation.DimensionSizes); var visitedInitializer = (IArrayInitializerOperation?)Visit(operation.Initializer); ImmutableArray<IOperation> visitedDimensions = PopArray(operation.DimensionSizes); PopStackFrame(frame); return new ArrayCreationOperation(visitedDimensions, visitedInitializer, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitArrayInitializer(IArrayInitializerOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); visitAndPushArrayInitializerValues(operation); return PopStackFrame(frame, popAndAssembleArrayInitializerValues(operation)); void visitAndPushArrayInitializerValues(IArrayInitializerOperation initializer) { foreach (IOperation elementValue in initializer.ElementValues) { // We need to retain the tree shape for nested array initializer. if (elementValue.Kind == OperationKind.ArrayInitializer) { visitAndPushArrayInitializerValues((IArrayInitializerOperation)elementValue); } else { PushOperand(VisitRequired(elementValue)); } } } IArrayInitializerOperation popAndAssembleArrayInitializerValues(IArrayInitializerOperation initializer) { var builder = ArrayBuilder<IOperation>.GetInstance(initializer.ElementValues.Length); for (int i = initializer.ElementValues.Length - 1; i >= 0; i--) { IOperation elementValue = initializer.ElementValues[i]; IOperation visitedElementValue; if (elementValue.Kind == OperationKind.ArrayInitializer) { visitedElementValue = popAndAssembleArrayInitializerValues((IArrayInitializerOperation)elementValue); } else { visitedElementValue = PopOperand(); } builder.Add(visitedElementValue); } builder.ReverseContents(); return new ArrayInitializerOperation(builder.ToImmutableAndFree(), semanticModel: null, initializer.Syntax, IsImplicit(initializer)); } } public override IOperation VisitInstanceReference(IInstanceReferenceOperation operation, int? captureIdForResult) { if (operation.ReferenceKind == InstanceReferenceKind.ImplicitReceiver) { // When we're in an object or collection initializer, we need to replace the instance reference with a reference to the object being initialized Debug.Assert(operation.IsImplicit); if (_currentImplicitInstance.ImplicitInstance != null) { return OperationCloner.CloneOperation(_currentImplicitInstance.ImplicitInstance); } else { Debug.Fail("This code path should not be reachable."); return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray<IOperation>.Empty); } } else { return new InstanceReferenceOperation(operation.ReferenceKind, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } } public override IOperation VisitDynamicInvocation(IDynamicInvocationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); if (operation.Operation.Kind == OperationKind.DynamicMemberReference) { var instance = ((IDynamicMemberReferenceOperation)operation.Operation).Instance; if (instance != null) { PushOperand(VisitRequired(instance)); } } else { PushOperand(VisitRequired(operation.Operation)); } ImmutableArray<IOperation> rewrittenArguments = VisitArray(operation.Arguments); IOperation rewrittenOperation; if (operation.Operation.Kind == OperationKind.DynamicMemberReference) { var dynamicMemberReference = (IDynamicMemberReferenceOperation)operation.Operation; IOperation? rewrittenInstance = dynamicMemberReference.Instance != null ? PopOperand() : null; rewrittenOperation = new DynamicMemberReferenceOperation(rewrittenInstance, dynamicMemberReference.MemberName, dynamicMemberReference.TypeArguments, dynamicMemberReference.ContainingType, semanticModel: null, dynamicMemberReference.Syntax, dynamicMemberReference.Type, IsImplicit(dynamicMemberReference)); } else { rewrittenOperation = PopOperand(); } PopStackFrame(frame); return new DynamicInvocationOperation(rewrittenOperation, rewrittenArguments, ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation, int? captureIdForResult) { PushOperand(VisitRequired(operation.Operation)); ImmutableArray<IOperation> rewrittenArguments = VisitArray(operation.Arguments); IOperation rewrittenOperation = PopOperand(); return new DynamicIndexerAccessOperation(rewrittenOperation, rewrittenArguments, ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, int? captureIdForResult) { return new DynamicMemberReferenceOperation(Visit(operation.Instance), operation.MemberName, operation.TypeArguments, operation.ContainingType, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, int? captureIdForResult) { (IOperation visitedTarget, IOperation visitedValue) = VisitPreservingTupleOperations(operation.Target, operation.Value); return new DeconstructionAssignmentOperation(visitedTarget, visitedValue, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } /// <summary> /// Recursively push nexted values onto the stack for visiting /// </summary> private void PushTargetAndUnwrapTupleIfNecessary(IOperation value) { if (value.Kind == OperationKind.Tuple) { var tuple = (ITupleOperation)value; foreach (IOperation element in tuple.Elements) { PushTargetAndUnwrapTupleIfNecessary(element); } } else { PushOperand(VisitRequired(value)); } } /// <summary> /// Recursively pop nested tuple values off the stack after visiting /// </summary> private IOperation PopTargetAndWrapTupleIfNecessary(IOperation value) { if (value.Kind == OperationKind.Tuple) { var tuple = (ITupleOperation)value; var numElements = tuple.Elements.Length; var elementBuilder = ArrayBuilder<IOperation>.GetInstance(numElements); for (int i = numElements - 1; i >= 0; i--) { elementBuilder.Add(PopTargetAndWrapTupleIfNecessary(tuple.Elements[i])); } elementBuilder.ReverseContents(); return new TupleOperation(elementBuilder.ToImmutableAndFree(), tuple.NaturalType, semanticModel: null, tuple.Syntax, tuple.Type, IsImplicit(tuple)); } else { return PopOperand(); } } public override IOperation VisitDeclarationExpression(IDeclarationExpressionOperation operation, int? captureIdForResult) { return new DeclarationExpressionOperation(VisitPreservingTupleOperations(operation.Expression), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } private IOperation VisitPreservingTupleOperations(IOperation operation) { EvalStackFrame frame = PushStackFrame(); PushTargetAndUnwrapTupleIfNecessary(operation); return PopStackFrame(frame, PopTargetAndWrapTupleIfNecessary(operation)); } private (IOperation visitedLeft, IOperation visitedRight) VisitPreservingTupleOperations(IOperation left, IOperation right) { Debug.Assert(left != null); Debug.Assert(right != null); // If the left is a tuple, we want to decompose the tuple and push each element back onto the stack, so that if the right // has control flow the individual elements are captured. Then we can recompose the tuple after the right has been visited. // We do this to keep the graph sane, so that users don't have to track a tuple captured via flow control when it's not really // the tuple that's been captured, it's the operands to the tuple. EvalStackFrame frame = PushStackFrame(); PushTargetAndUnwrapTupleIfNecessary(left); IOperation visitedRight = VisitRequired(right); IOperation visitedLeft = PopTargetAndWrapTupleIfNecessary(left); PopStackFrame(frame); return (visitedLeft, visitedRight); } public override IOperation VisitTuple(ITupleOperation operation, int? captureIdForResult) { return VisitPreservingTupleOperations(operation); } internal override IOperation VisitNoneOperation(IOperation operation, int? captureIdForResult) { if (_currentStatement == operation) { return VisitNoneOperationStatement(operation); } else { return VisitNoneOperationExpression(operation); } } private IOperation VisitNoneOperationStatement(IOperation operation) { Debug.Assert(_currentStatement == operation); VisitStatements(((Operation)operation).ChildOperations.ToImmutableArray()); return new NoneOperation(ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } private IOperation VisitNoneOperationExpression(IOperation operation) { return PopStackFrame(PushStackFrame(), new NoneOperation(VisitArray(((Operation)operation).ChildOperations.ToImmutableArray()), semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); } public override IOperation VisitInterpolatedString(IInterpolatedStringOperation operation, int? captureIdForResult) { // We visit and rewrite the interpolation parts in two phases: // 1. Visit all the non-literal parts of the interpolation and push them onto the eval stack. // 2. Traverse the parts in reverse order, popping the non-literal values from the eval stack and visiting the literal values. EvalStackFrame frame = PushStackFrame(); foreach (IInterpolatedStringContentOperation element in operation.Parts) { if (element.Kind == OperationKind.Interpolation) { var interpolation = (IInterpolationOperation)element; PushOperand(VisitRequired(interpolation.Expression)); if (interpolation.Alignment != null) { PushOperand(VisitRequired(interpolation.Alignment)); } } } var partsBuilder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(operation.Parts.Length); for (int i = operation.Parts.Length - 1; i >= 0; i--) { IInterpolatedStringContentOperation element = operation.Parts[i]; IInterpolatedStringContentOperation rewrittenElement; if (element.Kind == OperationKind.Interpolation) { var interpolation = (IInterpolationOperation)element; IOperation? rewrittenFormatString; if (interpolation.FormatString != null) { Debug.Assert(interpolation.FormatString is ILiteralOperation or IConversionOperation { Operand: ILiteralOperation }); rewrittenFormatString = VisitRequired(interpolation.FormatString, argument: null); } else { rewrittenFormatString = null; } var rewrittenAlignment = interpolation.Alignment != null ? PopOperand() : null; var rewrittenExpression = PopOperand(); rewrittenElement = new InterpolationOperation(rewrittenExpression, rewrittenAlignment, rewrittenFormatString, semanticModel: null, element.Syntax, IsImplicit(element)); } else { var interpolatedStringText = (IInterpolatedStringTextOperation)element; Debug.Assert(interpolatedStringText.Text is ILiteralOperation or IConversionOperation { Operand: ILiteralOperation }); var rewrittenInterpolationText = VisitRequired(interpolatedStringText.Text, argument: null); rewrittenElement = new InterpolatedStringTextOperation(rewrittenInterpolationText, semanticModel: null, element.Syntax, IsImplicit(element)); } partsBuilder.Add(rewrittenElement); } partsBuilder.ReverseContents(); PopStackFrame(frame); return new InterpolatedStringOperation(partsBuilder.ToImmutableAndFree(), semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitInterpolation(IInterpolationOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitNameOf(INameOfOperation operation, int? captureIdForResult) { Debug.Assert(operation.GetConstantValue() != null); return new LiteralOperation(semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitLiteral(ILiteralOperation operation, int? captureIdForResult) { return new LiteralOperation(semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitLocalReference(ILocalReferenceOperation operation, int? captureIdForResult) { return new LocalReferenceOperation(operation.Local, operation.IsDeclaration, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitParameterReference(IParameterReferenceOperation operation, int? captureIdForResult) { return new ParameterReferenceOperation(operation.Parameter, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitFieldReference(IFieldReferenceOperation operation, int? captureIdForResult) { IOperation? visitedInstance = operation.Field.IsStatic ? null : Visit(operation.Instance); return new FieldReferenceOperation(operation.Field, operation.IsDeclaration, visitedInstance, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitMethodReference(IMethodReferenceOperation operation, int? captureIdForResult) { IOperation? visitedInstance = operation.Method.IsStatic ? null : Visit(operation.Instance); return new MethodReferenceOperation(operation.Method, operation.IsVirtual, visitedInstance, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitPropertyReference(IPropertyReferenceOperation operation, int? captureIdForResult) { // Check if this is an anonymous type property reference with an implicit receiver within an anonymous object initializer. if (operation.Instance is IInstanceReferenceOperation instanceReference && instanceReference.ReferenceKind == InstanceReferenceKind.ImplicitReceiver && operation.Property.ContainingType.IsAnonymousType && operation.Property.ContainingType == _currentImplicitInstance.AnonymousType) { Debug.Assert(_currentImplicitInstance.AnonymousTypePropertyValues is not null); if (_currentImplicitInstance.AnonymousTypePropertyValues.TryGetValue(operation.Property, out IOperation? captured)) { return captured is IFlowCaptureReferenceOperation reference ? GetCaptureReference(reference.Id.Value, operation) : OperationCloner.CloneOperation(captured); } else { return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray<IOperation>.Empty); } } EvalStackFrame frame = PushStackFrame(); IOperation? instance = operation.Property.IsStatic ? null : operation.Instance; (IOperation? visitedInstance, ImmutableArray<IArgumentOperation> visitedArguments) = VisitInstanceWithArguments(instance, operation.Arguments); PopStackFrame(frame); return new PropertyReferenceOperation(operation.Property, visitedArguments, visitedInstance, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitEventReference(IEventReferenceOperation operation, int? captureIdForResult) { IOperation? visitedInstance = operation.Event.IsStatic ? null : Visit(operation.Instance); return new EventReferenceOperation(operation.Event, visitedInstance, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitTypeOf(ITypeOfOperation operation, int? captureIdForResult) { return new TypeOfOperation(operation.TypeOperand, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitParenthesized(IParenthesizedOperation operation, int? captureIdForResult) { return new ParenthesizedOperation(VisitRequired(operation.Operand), semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitAwait(IAwaitOperation operation, int? captureIdForResult) { return new AwaitOperation(VisitRequired(operation.Operation), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitSizeOf(ISizeOfOperation operation, int? captureIdForResult) { return new SizeOfOperation(operation.TypeOperand, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitStop(IStopOperation operation, int? captureIdForResult) { return new StopOperation(semanticModel: null, operation.Syntax, IsImplicit(operation)); } public override IOperation VisitIsType(IIsTypeOperation operation, int? captureIdForResult) { return new IsTypeOperation(VisitRequired(operation.ValueOperand), operation.TypeOperand, operation.IsNegated, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation? VisitParameterInitializer(IParameterInitializerOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); var parameterRef = new ParameterReferenceOperation(operation.Parameter, semanticModel: null, operation.Syntax, operation.Parameter.Type, isImplicit: true); VisitInitializer(rewrittenTarget: parameterRef, initializer: operation); return FinishVisitingStatement(operation); } public override IOperation? VisitFieldInitializer(IFieldInitializerOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); foreach (IFieldSymbol fieldSymbol in operation.InitializedFields) { IInstanceReferenceOperation? instance = fieldSymbol.IsStatic ? null : new InstanceReferenceOperation(InstanceReferenceKind.ContainingTypeInstance, semanticModel: null, operation.Syntax, fieldSymbol.ContainingType, isImplicit: true); var fieldRef = new FieldReferenceOperation(fieldSymbol, isDeclaration: false, instance, semanticModel: null, operation.Syntax, fieldSymbol.Type, constantValue: null, isImplicit: true); VisitInitializer(rewrittenTarget: fieldRef, initializer: operation); } return FinishVisitingStatement(operation); } public override IOperation? VisitPropertyInitializer(IPropertyInitializerOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); foreach (IPropertySymbol propertySymbol in operation.InitializedProperties) { var instance = propertySymbol.IsStatic ? null : new InstanceReferenceOperation(InstanceReferenceKind.ContainingTypeInstance, semanticModel: null, operation.Syntax, propertySymbol.ContainingType, isImplicit: true); ImmutableArray<IArgumentOperation> arguments; if (!propertySymbol.Parameters.IsEmpty) { // Must be an error case of initializing a property with parameters. var builder = ArrayBuilder<IArgumentOperation>.GetInstance(propertySymbol.Parameters.Length); foreach (var parameter in propertySymbol.Parameters) { var value = new InvalidOperation(ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Syntax, parameter.Type, constantValue: null, isImplicit: true); var argument = new ArgumentOperation(ArgumentKind.Explicit, parameter, value, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, operation.Syntax, isImplicit: true); builder.Add(argument); } arguments = builder.ToImmutableAndFree(); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } IOperation propertyRef = new PropertyReferenceOperation(propertySymbol, arguments, instance, semanticModel: null, operation.Syntax, propertySymbol.Type, isImplicit: true); VisitInitializer(rewrittenTarget: propertyRef, initializer: operation); } return FinishVisitingStatement(operation); } private void VisitInitializer(IOperation rewrittenTarget, ISymbolInitializerOperation initializer) { EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: initializer.Locals)); EvalStackFrame frame = PushStackFrame(); var assignment = new SimpleAssignmentOperation(isRef: false, rewrittenTarget, VisitRequired(initializer.Value), semanticModel: null, initializer.Syntax, rewrittenTarget.Type, constantValue: null, isImplicit: true); AddStatement(assignment); PopStackFrameAndLeaveRegion(frame); LeaveRegion(); } public override IOperation VisitEventAssignment(IEventAssignmentOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); IOperation visitedEventReference, visitedHandler; // Get the IEventReferenceOperation, digging through IParenthesizedOperation. // Note that for error cases, the event reference might be an IInvalidOperation. IEventReferenceOperation? eventReference = getEventReference(); if (eventReference != null) { // Preserve the IEventReferenceOperation. var eventReferenceInstance = eventReference.Event.IsStatic ? null : eventReference.Instance; if (eventReferenceInstance != null) { PushOperand(VisitRequired(eventReferenceInstance)); } visitedHandler = VisitRequired(operation.HandlerValue); IOperation? visitedInstance = eventReferenceInstance == null ? null : PopOperand(); visitedEventReference = new EventReferenceOperation(eventReference.Event, visitedInstance, semanticModel: null, operation.EventReference.Syntax, operation.EventReference.Type, IsImplicit(operation.EventReference)); } else { Debug.Assert(operation.EventReference != null); PushOperand(VisitRequired(operation.EventReference)); visitedHandler = VisitRequired(operation.HandlerValue); visitedEventReference = PopOperand(); } PopStackFrame(frame); return new EventAssignmentOperation(visitedEventReference, visitedHandler, operation.Adds, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); IEventReferenceOperation? getEventReference() { IOperation current = operation.EventReference; while (true) { switch (current.Kind) { case OperationKind.EventReference: return (IEventReferenceOperation)current; case OperationKind.Parenthesized: current = ((IParenthesizedOperation)current).Operand; continue; default: return null; } } } } public override IOperation VisitRaiseEvent(IRaiseEventOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); EvalStackFrame frame = PushStackFrame(); var instance = operation.EventReference.Event.IsStatic ? null : operation.EventReference.Instance; if (instance != null) { PushOperand(VisitRequired(instance)); } ImmutableArray<IArgumentOperation> visitedArguments = VisitArguments(operation.Arguments); IOperation? visitedInstance = instance == null ? null : PopOperand(); var visitedEventReference = new EventReferenceOperation(operation.EventReference.Event, visitedInstance, semanticModel: null, operation.EventReference.Syntax, operation.EventReference.Type, IsImplicit(operation.EventReference)); PopStackFrame(frame); return FinishVisitingStatement(operation, new RaiseEventOperation(visitedEventReference, visitedArguments, semanticModel: null, operation.Syntax, IsImplicit(operation))); } public override IOperation VisitAddressOf(IAddressOfOperation operation, int? captureIdForResult) { return new AddressOfOperation(VisitRequired(operation.Reference), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, int? captureIdForResult) { return new IncrementOrDecrementOperation(operation.IsPostfix, operation.IsLifted, operation.IsChecked, VisitRequired(operation.Target), operation.OperatorMethod, operation.Kind, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDiscardOperation(IDiscardOperation operation, int? captureIdForResult) { return new DiscardOperation(operation.DiscardSymbol, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDiscardPattern(IDiscardPatternOperation pat, int? captureIdForResult) { return new DiscardPatternOperation(pat.InputType, pat.NarrowedType, semanticModel: null, pat.Syntax, IsImplicit(pat)); } public override IOperation VisitOmittedArgument(IOmittedArgumentOperation operation, int? captureIdForResult) { return new OmittedArgumentOperation(semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } internal override IOperation VisitPlaceholder(IPlaceholderOperation operation, int? captureIdForResult) { switch (operation.PlaceholderKind) { case PlaceholderKind.SwitchOperationExpression: if (_currentSwitchOperationExpression != null) { return OperationCloner.CloneOperation(_currentSwitchOperationExpression); } break; case PlaceholderKind.ForToLoopBinaryOperatorLeftOperand: if (_forToLoopBinaryOperatorLeftOperand != null) { return _forToLoopBinaryOperatorLeftOperand; } break; case PlaceholderKind.ForToLoopBinaryOperatorRightOperand: if (_forToLoopBinaryOperatorRightOperand != null) { return _forToLoopBinaryOperatorRightOperand; } break; case PlaceholderKind.AggregationGroup: if (_currentAggregationGroup != null) { return OperationCloner.CloneOperation(_currentAggregationGroup); } break; } Debug.Fail("All placeholders should be handled above. Have we introduced a new scenario where placeholders are used?"); return new PlaceholderOperation(operation.PlaceholderKind, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitConversion(IConversionOperation operation, int? captureIdForResult) { return new ConversionOperation(VisitRequired(operation.Operand), ((ConversionOperation)operation).ConversionConvertible, operation.IsTryCast, operation.IsChecked, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitDefaultValue(IDefaultValueOperation operation, int? captureIdForResult) { return new DefaultValueOperation(semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitIsPattern(IIsPatternOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.Value)); var visitedPattern = (IPatternOperation)VisitRequired(operation.Pattern); IOperation visitedValue = PopOperand(); PopStackFrame(frame); return new IsPatternOperation(visitedValue, visitedPattern, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitInvalid(IInvalidOperation operation, int? captureIdForResult) { var children = ArrayBuilder<IOperation>.GetInstance(); children.AddRange(((InvalidOperation)operation).Children); if (children.Count != 0 && children.Last().Kind == OperationKind.ObjectOrCollectionInitializer) { // We are dealing with erroneous object creation. All children, but the last one are arguments for the constructor, // but overload resolution failed. SpillEvalStack(); EvalStackFrame frame = PushStackFrame(); var initializer = (IObjectOrCollectionInitializerOperation)children.Last(); children.RemoveLast(); EvalStackFrame argumentsFrame = PushStackFrame(); foreach (var argument in children) { PushOperand(VisitRequired(argument)); } for (int i = children.Count - 1; i >= 0; i--) { children[i] = PopOperand(); } PopStackFrame(argumentsFrame); IOperation initializedInstance = new InvalidOperation(children.ToImmutableAndFree(), semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); initializedInstance = HandleObjectOrCollectionInitializer(initializer, initializedInstance); PopStackFrame(frame); return initializedInstance; } IOperation result; if (_currentStatement == operation) { result = visitInvalidOperationStatement(operation); } else { result = visitInvalidOperationExpression(operation); } return result; IOperation visitInvalidOperationStatement(IInvalidOperation invalidOperation) { Debug.Assert(_currentStatement == invalidOperation); VisitStatements(children.ToImmutableAndFree()); return new InvalidOperation(ImmutableArray<IOperation>.Empty, semanticModel: null, invalidOperation.Syntax, invalidOperation.Type, invalidOperation.GetConstantValue(), IsImplicit(invalidOperation)); } IOperation visitInvalidOperationExpression(IInvalidOperation invalidOperation) { return PopStackFrame(PushStackFrame(), new InvalidOperation(VisitArray(children.ToImmutableAndFree()), semanticModel: null, invalidOperation.Syntax, invalidOperation.Type, invalidOperation.GetConstantValue(), IsImplicit(operation))); } } public override IOperation? VisitReDim(IReDimOperation operation, int? argument) { StartVisitingStatement(operation); // We split the ReDim clauses into separate ReDim operations to ensure that we preserve the evaluation order, // i.e. each ReDim clause operand is re-allocated prior to evaluating the next clause. // Mark the split ReDim operations as implicit if we have more than one ReDim clause. bool isImplicit = operation.Clauses.Length > 1 || IsImplicit(operation); foreach (var clause in operation.Clauses) { EvalStackFrame frame = PushStackFrame(); var visitedReDimClause = visitReDimClause(clause); var visitedReDimOperation = new ReDimOperation(ImmutableArray.Create(visitedReDimClause), operation.Preserve, semanticModel: null, operation.Syntax, isImplicit); AddStatement(visitedReDimOperation); PopStackFrameAndLeaveRegion(frame); } return FinishVisitingStatement(operation); IReDimClauseOperation visitReDimClause(IReDimClauseOperation clause) { PushOperand(VisitRequired(clause.Operand)); var visitedDimensionSizes = VisitArray(clause.DimensionSizes); var visitedOperand = PopOperand(); return new ReDimClauseOperation(visitedOperand, visitedDimensionSizes, semanticModel: null, clause.Syntax, IsImplicit(clause)); } } public override IOperation VisitReDimClause(IReDimClauseOperation operation, int? argument) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitTranslatedQuery(ITranslatedQueryOperation operation, int? captureIdForResult) { return new TranslatedQueryOperation(VisitRequired(operation.Operation), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitConstantPattern(IConstantPatternOperation operation, int? captureIdForResult) { return new ConstantPatternOperation(VisitRequired(operation.Value), operation.InputType, operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitRelationalPattern(IRelationalPatternOperation operation, int? argument) { return new RelationalPatternOperation( operatorKind: operation.OperatorKind, value: VisitRequired(operation.Value), inputType: operation.InputType, narrowedType: operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitBinaryPattern(IBinaryPatternOperation operation, int? argument) { return new BinaryPatternOperation( operatorKind: operation.OperatorKind, leftPattern: (IPatternOperation)VisitRequired(operation.LeftPattern), rightPattern: (IPatternOperation)VisitRequired(operation.RightPattern), inputType: operation.InputType, narrowedType: operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitNegatedPattern(INegatedPatternOperation operation, int? argument) { return new NegatedPatternOperation( pattern: (IPatternOperation)VisitRequired(operation.Pattern), inputType: operation.InputType, narrowedType: operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitTypePattern(ITypePatternOperation operation, int? argument) { return new TypePatternOperation( matchedType: operation.MatchedType, inputType: operation.InputType, narrowedType: operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitDeclarationPattern(IDeclarationPatternOperation operation, int? captureIdForResult) { return new DeclarationPatternOperation( operation.MatchedType, operation.MatchesNull, operation.DeclaredSymbol, operation.InputType, operation.NarrowedType, semanticModel: null, operation.Syntax, IsImplicit(operation)); } public override IOperation VisitRecursivePattern(IRecursivePatternOperation operation, int? argument) { return new RecursivePatternOperation( operation.MatchedType, operation.DeconstructSymbol, operation.DeconstructionSubpatterns.SelectAsArray((p, @this) => (IPatternOperation)@this.VisitRequired(p), this), operation.PropertySubpatterns.SelectAsArray((p, @this) => (IPropertySubpatternOperation)@this.VisitRequired(p), this), operation.DeclaredSymbol, operation.InputType, operation.NarrowedType, semanticModel: null, operation.Syntax, IsImplicit(operation)); } public override IOperation VisitPropertySubpattern(IPropertySubpatternOperation operation, int? argument) { return new PropertySubpatternOperation( VisitRequired(operation.Member), (IPatternOperation)VisitRequired(operation.Pattern), semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitDelegateCreation(IDelegateCreationOperation operation, int? captureIdForResult) { return new DelegateCreationOperation(VisitRequired(operation.Target), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitRangeOperation(IRangeOperation operation, int? argument) { if (operation.LeftOperand is object) { PushOperand(VisitRequired(operation.LeftOperand)); } IOperation? visitedRightOperand = null; if (operation.RightOperand is object) { visitedRightOperand = Visit(operation.RightOperand); } IOperation? visitedLeftOperand = operation.LeftOperand is null ? null : PopOperand(); return new RangeOperation(visitedLeftOperand, visitedRightOperand, operation.IsLifted, operation.Method, semanticModel: null, operation.Syntax, operation.Type, isImplicit: IsImplicit(operation)); } public override IOperation VisitSwitchExpression(ISwitchExpressionOperation operation, int? captureIdForResult) { // expression switch { pat1 when g1 => e1, pat2 when g2 => e2 } // // becomes // // captureInput = expression // START scope 1 (arm1 locals) // GotoIfFalse (captureInput is pat1 && g1) label1; // captureOutput = e1 // goto afterSwitch // label1: // END scope 1 // START scope 2 // GotoIfFalse (captureInput is pat2 && g2) label2; // captureOutput = e2 // goto afterSwitch // label2: // END scope 2 // throw new switch failure // afterSwitch: // result = captureOutput INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); SpillEvalStack(); RegionBuilder resultCaptureRegion = CurrentRegionRequired; int captureOutput = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); var capturedInput = VisitAndCapture(operation.Value); var afterSwitch = new BasicBlockBuilder(BasicBlockKind.Block); foreach (var arm in operation.Arms) { // START scope (arm locals) var armScopeRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: arm.Locals); EnterRegion(armScopeRegion); var afterArm = new BasicBlockBuilder(BasicBlockKind.Block); // GotoIfFalse (captureInput is pat1) label; { EvalStackFrame frame = PushStackFrame(); var visitedPattern = (IPatternOperation)VisitRequired(arm.Pattern); var patternTest = new IsPatternOperation( OperationCloner.CloneOperation(capturedInput), visitedPattern, semanticModel: null, arm.Syntax, booleanType, IsImplicit(arm)); ConditionalBranch(patternTest, jumpIfTrue: false, afterArm); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); } // GotoIfFalse (guard) afterArm; if (arm.Guard != null) { EvalStackFrame frame = PushStackFrame(); VisitConditionalBranch(arm.Guard, ref afterArm, jumpIfTrue: false); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); } // captureOutput = e VisitAndCapture(arm.Value, captureOutput); // goto afterSwitch UnconditionalBranch(afterSwitch); // afterArm: AppendNewBlock(afterArm); // END scope 1 LeaveRegion(); // armScopeRegion } LeaveRegionsUpTo(resultCaptureRegion); // throw new SwitchExpressionException var matchFailureCtor = (IMethodSymbol?)(_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor) ?? _compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_InvalidOperationException__ctor))?.GetISymbol(); var makeException = (matchFailureCtor is null) ? MakeInvalidOperation(operation.Syntax, type: _compilation.GetSpecialType(SpecialType.System_Object), ImmutableArray<IOperation>.Empty) : new ObjectCreationOperation( matchFailureCtor, initializer: null, ImmutableArray<IArgumentOperation>.Empty, semanticModel: null, operation.Syntax, type: matchFailureCtor.ContainingType, constantValue: null, isImplicit: true); LinkThrowStatement(makeException); _currentBasicBlock = null; // afterSwitch: AppendNewBlock(afterSwitch, linkToPrevious: false); // result = captureOutput return GetCaptureReference(captureOutput, operation); } private void VisitUsingVariableDeclarationOperation(IUsingDeclarationOperation operation, ReadOnlySpan<IOperation> statements) { IOperation? saveCurrentStatement = _currentStatement; _currentStatement = operation; StartVisitingStatement(operation); // a using statement introduces a 'logical' block after declaration, we synthesize one here in order to analyze it like a regular using. Don't include // local functions in this block: they still belong in the containing block. We'll visit any local functions in the list after we visit the statements // in this block. ArrayBuilder<IOperation> statementsBuilder = ArrayBuilder<IOperation>.GetInstance(statements.Length); ArrayBuilder<IOperation>? localFunctionsBuilder = null; foreach (var statement in statements) { if (statement.Kind == OperationKind.LocalFunction) { (localFunctionsBuilder ??= ArrayBuilder<IOperation>.GetInstance()).Add(statement); } else { statementsBuilder.Add(statement); } } BlockOperation logicalBlock = BlockOperation.CreateTemporaryBlock(statementsBuilder.ToImmutableAndFree(), ((Operation)operation).OwningSemanticModel!, operation.Syntax); DisposeOperationInfo disposeInfo = ((UsingDeclarationOperation)operation).DisposeInfo; HandleUsingOperationParts( resources: operation.DeclarationGroup, body: logicalBlock, disposeInfo.DisposeMethod, disposeInfo.DisposeArguments, locals: ImmutableArray<ILocalSymbol>.Empty, isAsynchronous: operation.IsAsynchronous); FinishVisitingStatement(operation); _currentStatement = saveCurrentStatement; if (localFunctionsBuilder != null) { VisitStatements(localFunctionsBuilder.ToImmutableAndFree()); } } public IOperation? Visit(IOperation? operation) { // We should never be revisiting nodes we've already visited, and we don't set SemanticModel in this builder. Debug.Assert(operation == null || ((Operation)operation).OwningSemanticModel!.Compilation == _compilation); return Visit(operation, argument: null); } [return: NotNullIfNotNull("operation")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public IOperation? VisitRequired(IOperation? operation, int? argument = null) { Debug.Assert(operation == null || ((Operation)operation).OwningSemanticModel!.Compilation == _compilation); var result = Visit(operation, argument); Debug.Assert((result == null) == (operation == null)); return result; } [return: NotNullIfNotNull("operation")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public IOperation? BaseVisitRequired(IOperation? operation, int? argument) { var result = base.Visit(operation, argument); Debug.Assert((result == null) == (operation == null)); return result; } public override IOperation? Visit(IOperation? operation, int? argument) { if (operation == null) { return null; } return PopStackFrame(PushStackFrame(), base.Visit(operation, argument)); } public override IOperation DefaultVisit(IOperation operation, int? captureIdForResult) { // this should never reach, otherwise, there is missing override for IOperation type throw ExceptionUtilities.Unreachable; } public override IOperation VisitArgument(IArgumentOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitUsingDeclaration(IUsingDeclarationOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitWith(IWithOperation operation, int? captureIdForResult) { if (operation.Type!.IsAnonymousType) { return handleAnonymousTypeWithExpression((WithOperation)operation, captureIdForResult); } EvalStackFrame frame = PushStackFrame(); // Initializer is removed from the tree and turned into a series of statements that assign to the cloned instance IOperation visitedInstance = VisitRequired(operation.Operand); IOperation cloned; if (operation.Type.IsValueType) { cloned = visitedInstance; } else { cloned = operation.CloneMethod is null ? MakeInvalidOperation(visitedInstance.Type, visitedInstance) : new InvocationOperation(operation.CloneMethod, visitedInstance, isVirtual: true, arguments: ImmutableArray<IArgumentOperation>.Empty, semanticModel: null, operation.Syntax, operation.Type, isImplicit: true); } return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, cloned)); // For `old with { Property = ... }` we're going to do the same as `new { Property = ..., OtherProperty = old.OtherProperty }` IOperation handleAnonymousTypeWithExpression(WithOperation operation, int? captureIdForResult) { Debug.Assert(operation.Type!.IsAnonymousType); SpillEvalStack(); // before entering a new region, we ensure that anything that needs spilling was spilled // The outer region holds captures for all the values for the anonymous object creation var outerCaptureRegion = CurrentRegionRequired; // The inner region holds the capture for the operand (ie. old value) var innerCaptureRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); EnterRegion(innerCaptureRegion); var initializers = operation.Initializer.Initializers; var properties = operation.Type.GetMembers() .Where(m => m.Kind == SymbolKind.Property) .Select(m => (IPropertySymbol)m); int oldValueCaptureId; if (setsAllProperties(initializers, properties)) { // Avoid capturing the old value since we won't need it oldValueCaptureId = -1; AddStatement(VisitRequired(operation.Operand)); } else { oldValueCaptureId = GetNextCaptureId(innerCaptureRegion); VisitAndCapture(operation.Operand, oldValueCaptureId); } // calls to Visit may enter regions, so we reset things LeaveRegionsUpTo(innerCaptureRegion); var explicitProperties = new Dictionary<IPropertySymbol, IOperation>(SymbolEqualityComparer.IgnoreAll); var initializerBuilder = ArrayBuilder<IOperation>.GetInstance(initializers.Length); // Visit and capture all the values, and construct assignments using capture references foreach (IOperation initializer in initializers) { if (initializer is not ISimpleAssignmentOperation simpleAssignment) { AddStatement(VisitRequired(initializer)); continue; } if (simpleAssignment.Target.Kind != OperationKind.PropertyReference) { Debug.Assert(simpleAssignment.Target is InvalidOperation); AddStatement(VisitRequired(simpleAssignment.Value)); continue; } var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Debug.Assert(propertyReference != null); Debug.Assert(propertyReference.Arguments.IsEmpty); Debug.Assert(propertyReference.Instance != null); Debug.Assert(propertyReference.Instance.Kind == OperationKind.InstanceReference); Debug.Assert(((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind == InstanceReferenceKind.ImplicitReceiver); var property = propertyReference.Property; if (explicitProperties.ContainsKey(property)) { AddStatement(VisitRequired(simpleAssignment.Value)); continue; } int valueCaptureId = GetNextCaptureId(outerCaptureRegion); VisitAndCapture(simpleAssignment.Value, valueCaptureId); LeaveRegionsUpTo(innerCaptureRegion); var valueCaptureRef = new FlowCaptureReferenceOperation(valueCaptureId, operation.Operand.Syntax, operation.Operand.Type, constantValue: operation.Operand.GetConstantValue()); var assignment = makeAssignment(property, valueCaptureRef, operation); explicitProperties.Add(property, assignment); } // Make a sequence for all properties (in order), constructing assignments for the implicitly set properties var type = (INamedTypeSymbol)operation.Type; foreach (IPropertySymbol property in properties) { if (explicitProperties.TryGetValue(property, out var assignment)) { initializerBuilder.Add(assignment); } else { Debug.Assert(oldValueCaptureId >= 0); // `oldInstance` var oldInstance = new FlowCaptureReferenceOperation(oldValueCaptureId, operation.Operand.Syntax, operation.Operand.Type, constantValue: operation.Operand.GetConstantValue()); // `oldInstance.Property` var visitedValue = new PropertyReferenceOperation(property, ImmutableArray<IArgumentOperation>.Empty, oldInstance, semanticModel: null, operation.Syntax, property.Type, isImplicit: true); int extraValueCaptureId = GetNextCaptureId(outerCaptureRegion); AddStatement(new FlowCaptureOperation(extraValueCaptureId, operation.Syntax, visitedValue)); var extraValueCaptureRef = new FlowCaptureReferenceOperation(extraValueCaptureId, operation.Operand.Syntax, operation.Operand.Type, constantValue: operation.Operand.GetConstantValue()); assignment = makeAssignment(property, extraValueCaptureRef, operation); initializerBuilder.Add(assignment); } } LeaveRegionsUpTo(outerCaptureRegion); return new AnonymousObjectCreationOperation(initializerBuilder.ToImmutableAndFree(), semanticModel: null, operation.Syntax, operation.Type, operation.IsImplicit); } // Build an operation for `<implicitReceiver>.Property = <capturedValue>` SimpleAssignmentOperation makeAssignment(IPropertySymbol property, IOperation capturedValue, WithOperation operation) { // <implicitReceiver> var implicitReceiver = new InstanceReferenceOperation(InstanceReferenceKind.ImplicitReceiver, semanticModel: null, operation.Syntax, operation.Type, isImplicit: true); // <implicitReceiver>.Property var target = new PropertyReferenceOperation(property, ImmutableArray<IArgumentOperation>.Empty, implicitReceiver, semanticModel: null, operation.Syntax, property.Type, isImplicit: true); // <implicitReceiver>.Property = <capturedValue> return new SimpleAssignmentOperation(isRef: false, target, capturedValue, semanticModel: null, operation.Syntax, property.Type, constantValue: null, isImplicit: true); } static bool setsAllProperties(ImmutableArray<IOperation> initializers, IEnumerable<IPropertySymbol> properties) { var set = new HashSet<IPropertySymbol>(SymbolEqualityComparer.IgnoreAll); foreach (var initializer in initializers) { if (initializer is not ISimpleAssignmentOperation simpleAssignment) { continue; } if (simpleAssignment.Target.Kind != OperationKind.PropertyReference) { Debug.Assert(simpleAssignment.Target is InvalidOperation); continue; } var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Debug.Assert(properties.Contains(propertyReference.Property, SymbolEqualityComparer.IgnoreAll)); set.Add(propertyReference.Property); } return set.Count == properties.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.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis { /// <summary> /// Some basic concepts: /// - Basic blocks are sequences of statements/operations with no branching. The only branching /// allowed is at the end of the basic block. /// - Regions group blocks together and represent the lifetime of locals and captures, loosely similar to scopes in C#. /// There are different kinds of regions, <see cref="ControlFlowRegionKind"/>. /// - <see cref="ControlFlowGraphBuilder.SpillEvalStack"/> converts values on the stack into captures. /// - Error scenarios from initial binding need to be handled. /// </summary> internal sealed partial class ControlFlowGraphBuilder : OperationVisitor<int?, IOperation> { private readonly Compilation _compilation; private readonly BasicBlockBuilder _entry = new BasicBlockBuilder(BasicBlockKind.Entry); private readonly BasicBlockBuilder _exit = new BasicBlockBuilder(BasicBlockKind.Exit); private readonly ArrayBuilder<BasicBlockBuilder> _blocks; private readonly PooledDictionary<BasicBlockBuilder, RegionBuilder> _regionMap; private BasicBlockBuilder? _currentBasicBlock; private RegionBuilder? _currentRegion; private PooledDictionary<ILabelSymbol, BasicBlockBuilder>? _labeledBlocks; private bool _haveAnonymousFunction; private IOperation? _currentStatement; private readonly ArrayBuilder<(EvalStackFrame? frameOpt, IOperation? operationOpt)> _evalStack; private int _startSpillingAt; private ConditionalAccessOperationTracker _currentConditionalAccessTracker; private IOperation? _currentSwitchOperationExpression; private IOperation? _forToLoopBinaryOperatorLeftOperand; private IOperation? _forToLoopBinaryOperatorRightOperand; private IOperation? _currentAggregationGroup; private bool _forceImplicit; // Force all rewritten nodes to be marked as implicit regardless of their original state. private readonly CaptureIdDispenser _captureIdDispenser; /// <summary> /// Holds the current object being initialized if we're visiting an object initializer. /// Or the current anonymous type object being initialized if we're visiting an anonymous type object initializer. /// Or the target of a VB With statement. /// </summary> private ImplicitInstanceInfo _currentImplicitInstance; private ControlFlowGraphBuilder(Compilation compilation, CaptureIdDispenser? captureIdDispenser, ArrayBuilder<BasicBlockBuilder> blocks) { Debug.Assert(compilation != null); _compilation = compilation; _captureIdDispenser = captureIdDispenser ?? new CaptureIdDispenser(); _blocks = blocks; _regionMap = PooledDictionary<BasicBlockBuilder, RegionBuilder>.GetInstance(); _evalStack = ArrayBuilder<(EvalStackFrame? frameOpt, IOperation? operationOpt)>.GetInstance(); } private RegionBuilder CurrentRegionRequired { get { Debug.Assert(_currentRegion != null); return _currentRegion; } } private bool IsImplicit(IOperation operation) { return _forceImplicit || operation.IsImplicit; } public static ControlFlowGraph Create(IOperation body, ControlFlowGraph? parent = null, ControlFlowRegion? enclosing = null, CaptureIdDispenser? captureIdDispenser = null, in Context context = default) { Debug.Assert(body != null); Debug.Assert(((Operation)body).OwningSemanticModel != null); #if DEBUG if (enclosing == null) { Debug.Assert(body.Parent == null); Debug.Assert(body.Kind == OperationKind.Block || body.Kind == OperationKind.MethodBody || body.Kind == OperationKind.ConstructorBody || body.Kind == OperationKind.FieldInitializer || body.Kind == OperationKind.PropertyInitializer || body.Kind == OperationKind.ParameterInitializer, $"Unexpected root operation kind: {body.Kind}"); Debug.Assert(parent == null); } else { Debug.Assert(body.Kind == OperationKind.LocalFunction || body.Kind == OperationKind.AnonymousFunction); Debug.Assert(parent != null); } #endif var blocks = ArrayBuilder<BasicBlockBuilder>.GetInstance(); var builder = new ControlFlowGraphBuilder(((Operation)body).OwningSemanticModel!.Compilation, captureIdDispenser, blocks); var root = new RegionBuilder(ControlFlowRegionKind.Root); builder.EnterRegion(root); builder.AppendNewBlock(builder._entry, linkToPrevious: false); builder._currentBasicBlock = null; builder.SetCurrentContext(context); builder.EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime)); switch (body.Kind) { case OperationKind.LocalFunction: Debug.Assert(captureIdDispenser != null); builder.VisitLocalFunctionAsRoot((ILocalFunctionOperation)body); break; case OperationKind.AnonymousFunction: Debug.Assert(captureIdDispenser != null); var anonymousFunction = (IAnonymousFunctionOperation)body; builder.VisitStatement(anonymousFunction.Body); break; default: builder.VisitStatement(body); break; } builder.LeaveRegion(); builder.AppendNewBlock(builder._exit); builder.LeaveRegion(); builder._currentImplicitInstance.Free(); Debug.Assert(builder._currentRegion == null); CheckUnresolvedBranches(blocks, builder._labeledBlocks); Pack(blocks, root, builder._regionMap); var localFunctions = ArrayBuilder<IMethodSymbol>.GetInstance(); var localFunctionsMap = ImmutableDictionary.CreateBuilder<IMethodSymbol, (ControlFlowRegion, ILocalFunctionOperation, int)>(); ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion, int)>.Builder? anonymousFunctionsMapOpt = null; if (builder._haveAnonymousFunction) { anonymousFunctionsMapOpt = ImmutableDictionary.CreateBuilder<IFlowAnonymousFunctionOperation, (ControlFlowRegion, int)>(); } ControlFlowRegion region = root.ToImmutableRegionAndFree(blocks, localFunctions, localFunctionsMap, anonymousFunctionsMapOpt, enclosing); root = null; MarkReachableBlocks(blocks); Debug.Assert(builder._evalStack.Count == 0); builder._evalStack.Free(); builder._regionMap.Free(); builder._labeledBlocks?.Free(); return new ControlFlowGraph(body, parent, builder._captureIdDispenser, ToImmutableBlocks(blocks), region, localFunctions.ToImmutableAndFree(), localFunctionsMap.ToImmutable(), anonymousFunctionsMapOpt?.ToImmutable() ?? ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion, int)>.Empty); } private static ImmutableArray<BasicBlock> ToImmutableBlocks(ArrayBuilder<BasicBlockBuilder> blockBuilders) { var builder = ArrayBuilder<BasicBlock>.GetInstance(blockBuilders.Count); // Pass 1: Iterate through blocksBuilder to create basic blocks. foreach (BasicBlockBuilder blockBuilder in blockBuilders) { builder.Add(blockBuilder.ToImmutable()); } // Pass 2: Create control flow branches with source and destination info and // update the branch information for the created basic blocks. foreach (BasicBlockBuilder blockBuilder in blockBuilders) { ControlFlowBranch? successor = getFallThroughSuccessor(blockBuilder); ControlFlowBranch? conditionalSuccessor = getConditionalSuccessor(blockBuilder); builder[blockBuilder.Ordinal].SetSuccessors(successor, conditionalSuccessor); } // Pass 3: Set the predecessors for the created basic blocks. foreach (BasicBlockBuilder blockBuilder in blockBuilders) { builder[blockBuilder.Ordinal].SetPredecessors(blockBuilder.ConvertPredecessorsToBranches(builder)); } return builder.ToImmutableAndFree(); ControlFlowBranch? getFallThroughSuccessor(BasicBlockBuilder blockBuilder) { return blockBuilder.Kind != BasicBlockKind.Exit ? getBranch(in blockBuilder.FallThrough, blockBuilder, isConditionalSuccessor: false) : null; } ControlFlowBranch? getConditionalSuccessor(BasicBlockBuilder blockBuilder) { return blockBuilder.HasCondition ? getBranch(in blockBuilder.Conditional, blockBuilder, isConditionalSuccessor: true) : null; } ControlFlowBranch getBranch(in BasicBlockBuilder.Branch branch, BasicBlockBuilder source, bool isConditionalSuccessor) { return new ControlFlowBranch( source: builder[source.Ordinal], destination: branch.Destination != null ? builder[branch.Destination.Ordinal] : null, branch.Kind, isConditionalSuccessor); } } private static void MarkReachableBlocks(ArrayBuilder<BasicBlockBuilder> blocks) { // NOTE: This flow graph walking algorithm has been forked into Workspaces layer's // implementation of "CustomDataFlowAnalysis", // we should keep them in sync as much as possible. var continueDispatchAfterFinally = PooledDictionary<ControlFlowRegion, bool>.GetInstance(); var dispatchedExceptionsFromRegions = PooledHashSet<ControlFlowRegion>.GetInstance(); MarkReachableBlocks(blocks, firstBlockOrdinal: 0, lastBlockOrdinal: blocks.Count - 1, outOfRangeBlocksToVisit: null, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, out _); continueDispatchAfterFinally.Free(); dispatchedExceptionsFromRegions.Free(); } private static BitVector MarkReachableBlocks( ArrayBuilder<BasicBlockBuilder> blocks, int firstBlockOrdinal, int lastBlockOrdinal, ArrayBuilder<BasicBlockBuilder>? outOfRangeBlocksToVisit, PooledDictionary<ControlFlowRegion, bool> continueDispatchAfterFinally, PooledHashSet<ControlFlowRegion> dispatchedExceptionsFromRegions, out bool fellThrough) { var visited = BitVector.Empty; var toVisit = ArrayBuilder<BasicBlockBuilder>.GetInstance(); fellThrough = false; toVisit.Push(blocks[firstBlockOrdinal]); do { BasicBlockBuilder current = toVisit.Pop(); if (current.Ordinal < firstBlockOrdinal || current.Ordinal > lastBlockOrdinal) { Debug.Assert(outOfRangeBlocksToVisit != null); outOfRangeBlocksToVisit.Push(current); continue; } if (visited[current.Ordinal]) { continue; } visited[current.Ordinal] = true; current.IsReachable = true; bool fallThrough = true; if (current.HasCondition) { if (current.BranchValue.GetConstantValue() is { IsBoolean: true, BooleanValue: bool constant }) { if (constant == (current.ConditionKind == ControlFlowConditionKind.WhenTrue)) { followBranch(current, in current.Conditional); fallThrough = false; } } else { followBranch(current, in current.Conditional); } } if (fallThrough) { BasicBlockBuilder.Branch branch = current.FallThrough; followBranch(current, in branch); if (current.Ordinal == lastBlockOrdinal && branch.Kind != ControlFlowBranchSemantics.Throw && branch.Kind != ControlFlowBranchSemantics.Rethrow) { fellThrough = true; } } // We are using very simple approach: // If try block is reachable, we should dispatch an exception from it, even if it is empty. // To simplify implementation, we dispatch exception from every reachable basic block and rely // on dispatchedExceptionsFromRegions cache to avoid doing duplicate work. Debug.Assert(current.Region != null); dispatchException(current.Region); } while (toVisit.Count != 0); toVisit.Free(); return visited; void followBranch(BasicBlockBuilder current, in BasicBlockBuilder.Branch branch) { switch (branch.Kind) { case ControlFlowBranchSemantics.None: case ControlFlowBranchSemantics.ProgramTermination: case ControlFlowBranchSemantics.StructuredExceptionHandling: case ControlFlowBranchSemantics.Throw: case ControlFlowBranchSemantics.Rethrow: case ControlFlowBranchSemantics.Error: Debug.Assert(branch.Destination == null); return; case ControlFlowBranchSemantics.Regular: case ControlFlowBranchSemantics.Return: Debug.Assert(branch.Destination != null); Debug.Assert(current.Region != null); if (stepThroughFinally(current.Region, branch.Destination)) { toVisit.Add(branch.Destination); } return; default: throw ExceptionUtilities.UnexpectedValue(branch.Kind); } } // Returns whether we should proceed to the destination after finallies were taken care of. bool stepThroughFinally(ControlFlowRegion region, BasicBlockBuilder destination) { int destinationOrdinal = destination.Ordinal; while (!region.ContainsBlock(destinationOrdinal)) { Debug.Assert(region.Kind != ControlFlowRegionKind.Root); Debug.Assert(region.EnclosingRegion != null); ControlFlowRegion enclosing = region.EnclosingRegion; if (region.Kind == ControlFlowRegionKind.Try && enclosing.Kind == ControlFlowRegionKind.TryAndFinally) { Debug.Assert(enclosing.NestedRegions[0] == region); Debug.Assert(enclosing.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); if (!stepThroughSingleFinally(enclosing.NestedRegions[1])) { // The point that continues dispatch is not reachable. Cancel the dispatch. return false; } } region = enclosing; } return true; } // Returns whether we should proceed with dispatch after finally was taken care of. bool stepThroughSingleFinally(ControlFlowRegion @finally) { Debug.Assert(@finally.Kind == ControlFlowRegionKind.Finally); if (!continueDispatchAfterFinally.TryGetValue(@finally, out bool continueDispatch)) { // For simplicity, we do a complete walk of the finally/filter region in isolation // to make sure that the resume dispatch point is reachable from its beginning. // It could also be reachable through invalid branches into the finally and we don't want to consider // these cases for regular finally handling. BitVector isolated = MarkReachableBlocks(blocks, @finally.FirstBlockOrdinal, @finally.LastBlockOrdinal, outOfRangeBlocksToVisit: toVisit, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, out bool isolatedFellThrough); visited.UnionWith(isolated); continueDispatch = isolatedFellThrough && blocks[@finally.LastBlockOrdinal].FallThrough.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling; continueDispatchAfterFinally.Add(@finally, continueDispatch); } return continueDispatch; } void dispatchException([DisallowNull] ControlFlowRegion? fromRegion) { do { if (!dispatchedExceptionsFromRegions.Add(fromRegion)) { return; } ControlFlowRegion? enclosing = fromRegion.Kind == ControlFlowRegionKind.Root ? null : fromRegion.EnclosingRegion; if (fromRegion.Kind == ControlFlowRegionKind.Try) { switch (enclosing!.Kind) { case ControlFlowRegionKind.TryAndFinally: Debug.Assert(enclosing.NestedRegions[0] == fromRegion); Debug.Assert(enclosing.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); if (!stepThroughSingleFinally(enclosing.NestedRegions[1])) { // The point that continues dispatch is not reachable. Cancel the dispatch. return; } break; case ControlFlowRegionKind.TryAndCatch: Debug.Assert(enclosing.NestedRegions[0] == fromRegion); dispatchExceptionThroughCatches(enclosing, startAt: 1); break; default: throw ExceptionUtilities.UnexpectedValue(enclosing.Kind); } } else if (fromRegion.Kind == ControlFlowRegionKind.Filter) { // If filter throws, dispatch is resumed at the next catch with an original exception Debug.Assert(enclosing!.Kind == ControlFlowRegionKind.FilterAndHandler); Debug.Assert(enclosing.EnclosingRegion != null); ControlFlowRegion tryAndCatch = enclosing.EnclosingRegion; Debug.Assert(tryAndCatch.Kind == ControlFlowRegionKind.TryAndCatch); int index = tryAndCatch.NestedRegions.IndexOf(enclosing, startIndex: 1); if (index > 0) { dispatchExceptionThroughCatches(tryAndCatch, startAt: index + 1); fromRegion = tryAndCatch; continue; } throw ExceptionUtilities.Unreachable; } fromRegion = enclosing; } while (fromRegion != null); } void dispatchExceptionThroughCatches(ControlFlowRegion tryAndCatch, int startAt) { // For simplicity, we do not try to figure out whether a catch clause definitely // handles all exceptions. Debug.Assert(tryAndCatch.Kind == ControlFlowRegionKind.TryAndCatch); Debug.Assert(startAt > 0); Debug.Assert(startAt <= tryAndCatch.NestedRegions.Length); for (int i = startAt; i < tryAndCatch.NestedRegions.Length; i++) { ControlFlowRegion @catch = tryAndCatch.NestedRegions[i]; switch (@catch.Kind) { case ControlFlowRegionKind.Catch: toVisit.Add(blocks[@catch.FirstBlockOrdinal]); break; case ControlFlowRegionKind.FilterAndHandler: BasicBlockBuilder entryBlock = blocks[@catch.FirstBlockOrdinal]; Debug.Assert(@catch.NestedRegions[0].Kind == ControlFlowRegionKind.Filter); Debug.Assert(entryBlock.Ordinal == @catch.NestedRegions[0].FirstBlockOrdinal); toVisit.Add(entryBlock); break; default: throw ExceptionUtilities.UnexpectedValue(@catch.Kind); } } } } /// <summary> /// Do a pass to eliminate blocks without statements that can be merged with predecessor(s) and /// to eliminate regions that can be merged with parents. /// </summary> private static void Pack(ArrayBuilder<BasicBlockBuilder> blocks, RegionBuilder root, PooledDictionary<BasicBlockBuilder, RegionBuilder> regionMap) { bool regionsChanged = true; while (true) { regionsChanged |= PackRegions(root, blocks, regionMap); if (!regionsChanged || !PackBlocks(blocks, regionMap)) { break; } regionsChanged = false; } } private static bool PackRegions(RegionBuilder root, ArrayBuilder<BasicBlockBuilder> blocks, PooledDictionary<BasicBlockBuilder, RegionBuilder> regionMap) { return PackRegion(root); bool PackRegion(RegionBuilder region) { Debug.Assert(!region.IsEmpty); bool result = false; if (region.HasRegions) { for (int i = region.Regions.Count - 1; i >= 0; i--) { RegionBuilder r = region.Regions[i]; if (PackRegion(r)) { result = true; } if (r.Kind == ControlFlowRegionKind.LocalLifetime && r.Locals.IsEmpty && !r.HasLocalFunctions && !r.HasCaptureIds) { MergeSubRegionAndFree(r, blocks, regionMap); result = true; } } } switch (region.Kind) { case ControlFlowRegionKind.Root: case ControlFlowRegionKind.Filter: case ControlFlowRegionKind.Try: case ControlFlowRegionKind.Catch: case ControlFlowRegionKind.Finally: case ControlFlowRegionKind.LocalLifetime: case ControlFlowRegionKind.StaticLocalInitializer: case ControlFlowRegionKind.ErroneousBody: if (region.Regions?.Count == 1) { RegionBuilder subRegion = region.Regions[0]; if (subRegion.Kind == ControlFlowRegionKind.LocalLifetime && subRegion.FirstBlock == region.FirstBlock && subRegion.LastBlock == region.LastBlock) { Debug.Assert(region.Kind != ControlFlowRegionKind.Root); // Transfer all content of the sub-region into the current region region.Locals = region.Locals.Concat(subRegion.Locals); region.AddRange(subRegion.LocalFunctions); region.AddCaptureIds(subRegion.CaptureIds); MergeSubRegionAndFree(subRegion, blocks, regionMap); result = true; break; } } if (region.HasRegions) { for (int i = region.Regions.Count - 1; i >= 0; i--) { RegionBuilder subRegion = region.Regions[i]; if (subRegion.Kind == ControlFlowRegionKind.LocalLifetime && !subRegion.HasLocalFunctions && !subRegion.HasRegions && subRegion.FirstBlock == subRegion.LastBlock) { Debug.Assert(subRegion.FirstBlock != null); BasicBlockBuilder block = subRegion.FirstBlock; if (!block.HasStatements && block.BranchValue == null) { Debug.Assert(!subRegion.HasCaptureIds); // This sub-region has no executable code, merge block into the parent and drop the sub-region Debug.Assert(regionMap[block] == subRegion); regionMap[block] = region; #if DEBUG subRegion.AboutToFree(); #endif subRegion.Free(); region.Regions.RemoveAt(i); result = true; } } } } break; case ControlFlowRegionKind.TryAndCatch: case ControlFlowRegionKind.TryAndFinally: case ControlFlowRegionKind.FilterAndHandler: break; default: throw ExceptionUtilities.UnexpectedValue(region.Kind); } return result; } } /// <summary> /// Merge content of <paramref name="subRegion"/> into its enclosing region and free it. /// </summary> private static void MergeSubRegionAndFree(RegionBuilder subRegion, ArrayBuilder<BasicBlockBuilder> blocks, PooledDictionary<BasicBlockBuilder, RegionBuilder> regionMap, bool canHaveEmptyRegion = false) { Debug.Assert(subRegion.Kind != ControlFlowRegionKind.Root); Debug.Assert(subRegion.Enclosing != null); RegionBuilder enclosing = subRegion.Enclosing; #if DEBUG subRegion.AboutToFree(); #endif if (subRegion.IsEmpty) { Debug.Assert(canHaveEmptyRegion); Debug.Assert(!subRegion.HasRegions); enclosing.Remove(subRegion); subRegion.Free(); return; } int firstBlockToMove = subRegion.FirstBlock.Ordinal; if (subRegion.HasRegions) { foreach (RegionBuilder r in subRegion.Regions) { Debug.Assert(!r.IsEmpty); for (int i = firstBlockToMove; i < r.FirstBlock.Ordinal; i++) { Debug.Assert(regionMap[blocks[i]] == subRegion); regionMap[blocks[i]] = enclosing; } firstBlockToMove = r.LastBlock.Ordinal + 1; } enclosing.ReplaceRegion(subRegion, subRegion.Regions); } else { enclosing.Remove(subRegion); } for (int i = firstBlockToMove; i <= subRegion.LastBlock.Ordinal; i++) { Debug.Assert(regionMap[blocks[i]] == subRegion); regionMap[blocks[i]] = enclosing; } subRegion.Free(); } /// <summary> /// Do a pass to eliminate blocks without statements that can be merged with predecessor(s). /// Returns true if any blocks were eliminated /// </summary> private static bool PackBlocks(ArrayBuilder<BasicBlockBuilder> blocks, PooledDictionary<BasicBlockBuilder, RegionBuilder> regionMap) { ArrayBuilder<RegionBuilder>? fromCurrent = null; ArrayBuilder<RegionBuilder>? fromDestination = null; ArrayBuilder<RegionBuilder>? fromPredecessor = null; ArrayBuilder<BasicBlockBuilder>? predecessorsBuilder = null; bool anyRemoved = false; bool retry; do { // We set this local to true during the loop below when we make some changes that might enable // transformations for basic blocks that were already looked at. We simply keep repeating the // pass until no such changes are made. retry = false; int count = blocks.Count - 1; for (int i = 1; i < count; i++) { BasicBlockBuilder block = blocks[i]; block.Ordinal = i; if (block.HasStatements) { // See if we can move all statements to the previous block BasicBlockBuilder? predecessor = block.GetSingletonPredecessorOrDefault(); if (predecessor != null && !predecessor.HasCondition && predecessor.Ordinal < block.Ordinal && predecessor.Kind != BasicBlockKind.Entry && predecessor.FallThrough.Destination == block && regionMap[predecessor] == regionMap[block]) { Debug.Assert(predecessor.BranchValue == null); Debug.Assert(predecessor.FallThrough.Kind == ControlFlowBranchSemantics.Regular); predecessor.MoveStatementsFrom(block); retry = true; } else { continue; } } ref BasicBlockBuilder.Branch next = ref block.FallThrough; Debug.Assert((block.BranchValue != null && !block.HasCondition) == (next.Kind == ControlFlowBranchSemantics.Return || next.Kind == ControlFlowBranchSemantics.Throw)); Debug.Assert((next.Destination == null) == (next.Kind == ControlFlowBranchSemantics.ProgramTermination || next.Kind == ControlFlowBranchSemantics.Throw || next.Kind == ControlFlowBranchSemantics.Rethrow || next.Kind == ControlFlowBranchSemantics.Error || next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling)); #if DEBUG if (next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling) { RegionBuilder currentRegion = regionMap[block]; Debug.Assert(currentRegion.Kind == ControlFlowRegionKind.Filter || currentRegion.Kind == ControlFlowRegionKind.Finally); Debug.Assert(block == currentRegion.LastBlock); } #endif if (!block.HasCondition) { if (next.Destination == block) { continue; } RegionBuilder currentRegion = regionMap[block]; // Is this the only block in the region if (currentRegion.FirstBlock == currentRegion.LastBlock) { Debug.Assert(currentRegion.FirstBlock == block); Debug.Assert(!currentRegion.HasRegions); // Remove Try/Finally if Finally is empty if (currentRegion.Kind == ControlFlowRegionKind.Finally && next.Destination == null && next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling && !block.HasPredecessors) { // Nothing useful is happening in this finally, let's remove it Debug.Assert(currentRegion.Enclosing != null); RegionBuilder tryAndFinally = currentRegion.Enclosing; Debug.Assert(tryAndFinally.Kind == ControlFlowRegionKind.TryAndFinally); Debug.Assert(tryAndFinally.Regions!.Count == 2); RegionBuilder @try = tryAndFinally.Regions.First(); Debug.Assert(@try.Kind == ControlFlowRegionKind.Try); Debug.Assert(tryAndFinally.Regions.Last() == currentRegion); // If .try region has locals or methods or captures, let's convert it to .locals, otherwise drop it if (@try.Locals.IsEmpty && [email protected] && [email protected]) { Debug.Assert(@try.FirstBlock != null); i = @try.FirstBlock.Ordinal - 1; // restart at the first block of removed .try region MergeSubRegionAndFree(@try, blocks, regionMap); } else { @try.Kind = ControlFlowRegionKind.LocalLifetime; i--; // restart at the block that was following the tryAndFinally } MergeSubRegionAndFree(currentRegion, blocks, regionMap); Debug.Assert(tryAndFinally.Enclosing != null); RegionBuilder tryAndFinallyEnclosing = tryAndFinally.Enclosing; MergeSubRegionAndFree(tryAndFinally, blocks, regionMap); count--; Debug.Assert(regionMap[block] == tryAndFinallyEnclosing); removeBlock(block, tryAndFinallyEnclosing); anyRemoved = true; retry = true; } continue; } if (next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling) { Debug.Assert(block.HasCondition || block.BranchValue == null); Debug.Assert(next.Destination == null); // It is safe to drop an unreachable empty basic block if (block.HasPredecessors) { BasicBlockBuilder? predecessor = block.GetSingletonPredecessorOrDefault(); if (predecessor == null) { continue; } if (predecessor.Ordinal != i - 1 || predecessor.FallThrough.Destination != block || predecessor.Conditional.Destination == block || regionMap[predecessor] != currentRegion) { // Do not merge StructuredExceptionHandling into the middle of the filter or finally, // Do not merge StructuredExceptionHandling into conditional branch // Do not merge StructuredExceptionHandling into a different region // It is much easier to walk the graph when we can rely on the fact that a StructuredExceptionHandling // branch is only in the last block in the region, if it is present. continue; } predecessor.FallThrough = block.FallThrough; } } else { Debug.Assert(next.Kind == ControlFlowBranchSemantics.Regular || next.Kind == ControlFlowBranchSemantics.Return || next.Kind == ControlFlowBranchSemantics.Throw || next.Kind == ControlFlowBranchSemantics.Rethrow || next.Kind == ControlFlowBranchSemantics.Error || next.Kind == ControlFlowBranchSemantics.ProgramTermination); Debug.Assert(!block.HasCondition); // This is ensured by an "if" above. IOperation? value = block.BranchValue; RegionBuilder? implicitEntryRegion = tryGetImplicitEntryRegion(block, currentRegion); if (implicitEntryRegion != null) { // First blocks in filter/catch/finally do not capture all possible predecessors // Do not try to merge them, unless they are simply linked to the next block if (value != null || next.Destination != blocks[i + 1]) { continue; } Debug.Assert(implicitEntryRegion.LastBlock!.Ordinal >= next.Destination.Ordinal); } if (value != null) { if (!block.HasPredecessors && next.Kind == ControlFlowBranchSemantics.Return) { // Let's drop an unreachable compiler generated return that VB optimistically adds at the end of a method body Debug.Assert(next.Destination != null); if (next.Destination.Kind != BasicBlockKind.Exit || !value.IsImplicit || value.Kind != OperationKind.LocalReference || !((ILocalReferenceOperation)value).Local.IsFunctionValue) { continue; } } else { BasicBlockBuilder? predecessor = block.GetSingletonPredecessorOrDefault(); if (predecessor == null || predecessor.BranchValue != null || predecessor.Kind == BasicBlockKind.Entry || regionMap[predecessor] != currentRegion) { // Do not merge return/throw with expression with more than one predecessor // Do not merge return/throw into a block with conditional branch // Do not merge return/throw with expression with an entry block // Do not merge return/throw with expression into a different region continue; } Debug.Assert(predecessor.FallThrough.Destination == block); } } // For throw/re-throw assume there is no specific destination region RegionBuilder? destinationRegionOpt = next.Destination == null ? null : regionMap[next.Destination]; if (block.HasPredecessors) { if (predecessorsBuilder == null) { predecessorsBuilder = ArrayBuilder<BasicBlockBuilder>.GetInstance(); } else { predecessorsBuilder.Clear(); } block.GetPredecessors(predecessorsBuilder); // If source and destination are in different regions, it might // be unsafe to merge branches. if (currentRegion != destinationRegionOpt) { fromCurrent?.Clear(); fromDestination?.Clear(); if (!checkBranchesFromPredecessors(predecessorsBuilder, currentRegion, destinationRegionOpt)) { continue; } } foreach (BasicBlockBuilder predecessor in predecessorsBuilder) { if (tryMergeBranch(predecessor, ref predecessor.FallThrough, block)) { if (value != null) { Debug.Assert(predecessor.BranchValue == null); predecessor.BranchValue = value; } } if (tryMergeBranch(predecessor, ref predecessor.Conditional, block)) { Debug.Assert(value == null); } } } next.Destination?.RemovePredecessor(block); } i--; count--; removeBlock(block, currentRegion); anyRemoved = true; retry = true; } else { if (next.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling) { continue; } Debug.Assert(next.Kind == ControlFlowBranchSemantics.Regular || next.Kind == ControlFlowBranchSemantics.Return || next.Kind == ControlFlowBranchSemantics.Throw || next.Kind == ControlFlowBranchSemantics.Rethrow || next.Kind == ControlFlowBranchSemantics.Error || next.Kind == ControlFlowBranchSemantics.ProgramTermination); BasicBlockBuilder? predecessor = block.GetSingletonPredecessorOrDefault(); if (predecessor == null) { continue; } RegionBuilder currentRegion = regionMap[block]; if (tryGetImplicitEntryRegion(block, currentRegion) != null) { // First blocks in filter/catch/finally do not capture all possible predecessors // Do not try to merge conditional branches in them continue; } if (predecessor.Kind != BasicBlockKind.Entry && predecessor.FallThrough.Destination == block && !predecessor.HasCondition && regionMap[predecessor] == currentRegion) { Debug.Assert(predecessor != block); Debug.Assert(predecessor.BranchValue == null); mergeBranch(predecessor, ref predecessor.FallThrough, ref next); next.Destination?.RemovePredecessor(block); predecessor.BranchValue = block.BranchValue; predecessor.ConditionKind = block.ConditionKind; predecessor.Conditional = block.Conditional; BasicBlockBuilder? destination = block.Conditional.Destination; if (destination != null) { destination.AddPredecessor(predecessor); destination.RemovePredecessor(block); } i--; count--; removeBlock(block, currentRegion); anyRemoved = true; retry = true; } } } blocks[0].Ordinal = 0; blocks[count].Ordinal = count; } while (retry); fromCurrent?.Free(); fromDestination?.Free(); fromPredecessor?.Free(); predecessorsBuilder?.Free(); return anyRemoved; RegionBuilder? tryGetImplicitEntryRegion(BasicBlockBuilder block, [DisallowNull] RegionBuilder? currentRegion) { do { if (currentRegion.FirstBlock != block) { return null; } switch (currentRegion.Kind) { case ControlFlowRegionKind.Filter: case ControlFlowRegionKind.Catch: case ControlFlowRegionKind.Finally: return currentRegion; } currentRegion = currentRegion.Enclosing; } while (currentRegion != null); return null; } void removeBlock(BasicBlockBuilder block, RegionBuilder region) { Debug.Assert(!region.IsEmpty); Debug.Assert(region.FirstBlock.Ordinal >= 0); Debug.Assert(region.FirstBlock.Ordinal <= region.LastBlock.Ordinal); Debug.Assert(region.FirstBlock.Ordinal <= block.Ordinal); Debug.Assert(block.Ordinal <= region.LastBlock.Ordinal); if (region.FirstBlock == block) { BasicBlockBuilder newFirst = blocks[block.Ordinal + 1]; region.FirstBlock = newFirst; Debug.Assert(region.Enclosing != null); RegionBuilder enclosing = region.Enclosing; while (enclosing != null && enclosing.FirstBlock == block) { enclosing.FirstBlock = newFirst; Debug.Assert(enclosing.Enclosing != null); enclosing = enclosing.Enclosing; } } else if (region.LastBlock == block) { BasicBlockBuilder newLast = blocks[block.Ordinal - 1]; region.LastBlock = newLast; Debug.Assert(region.Enclosing != null); RegionBuilder enclosing = region.Enclosing; while (enclosing != null && enclosing.LastBlock == block) { enclosing.LastBlock = newLast; Debug.Assert(enclosing.Enclosing != null); enclosing = enclosing.Enclosing; } } Debug.Assert(region.FirstBlock.Ordinal <= region.LastBlock.Ordinal); bool removed = regionMap.Remove(block); Debug.Assert(removed); Debug.Assert(blocks[block.Ordinal] == block); blocks.RemoveAt(block.Ordinal); block.Free(); } bool tryMergeBranch(BasicBlockBuilder predecessor, ref BasicBlockBuilder.Branch predecessorBranch, BasicBlockBuilder successor) { if (predecessorBranch.Destination == successor) { mergeBranch(predecessor, ref predecessorBranch, ref successor.FallThrough); return true; } return false; } void mergeBranch(BasicBlockBuilder predecessor, ref BasicBlockBuilder.Branch predecessorBranch, ref BasicBlockBuilder.Branch successorBranch) { predecessorBranch.Destination = successorBranch.Destination; successorBranch.Destination?.AddPredecessor(predecessor); Debug.Assert(predecessorBranch.Kind == ControlFlowBranchSemantics.Regular); predecessorBranch.Kind = successorBranch.Kind; } bool checkBranchesFromPredecessors(ArrayBuilder<BasicBlockBuilder> predecessors, RegionBuilder currentRegion, RegionBuilder? destinationRegionOpt) { foreach (BasicBlockBuilder predecessor in predecessors) { RegionBuilder predecessorRegion = regionMap[predecessor]; // If source and destination are in different regions, it might // be unsafe to merge branches. if (predecessorRegion != currentRegion) { if (destinationRegionOpt == null) { // destination is unknown and predecessor is in different region, do not merge return false; } fromPredecessor?.Clear(); collectAncestorsAndSelf(currentRegion, ref fromCurrent); collectAncestorsAndSelf(destinationRegionOpt, ref fromDestination); collectAncestorsAndSelf(predecessorRegion, ref fromPredecessor); // On the way from predecessor directly to the destination, are we going leave the same regions as on the way // from predecessor to the current block and then to the destination? int lastLeftRegionOnTheWayFromCurrentToDestination = getIndexOfLastLeftRegion(fromCurrent, fromDestination); int lastLeftRegionOnTheWayFromPredecessorToDestination = getIndexOfLastLeftRegion(fromPredecessor, fromDestination); int lastLeftRegionOnTheWayFromPredecessorToCurrentBlock = getIndexOfLastLeftRegion(fromPredecessor, fromCurrent); // Since we are navigating up and down the tree and only movements up are significant, if we made the same number // of movements up during direct and indirect transition, we must have made the same movements up. if ((fromPredecessor.Count - lastLeftRegionOnTheWayFromPredecessorToCurrentBlock + fromCurrent.Count - lastLeftRegionOnTheWayFromCurrentToDestination) != (fromPredecessor.Count - lastLeftRegionOnTheWayFromPredecessorToDestination)) { // We have different transitions return false; } } else if (predecessor.Kind == BasicBlockKind.Entry && destinationRegionOpt == null) { // Do not merge throw into an entry block return false; } } return true; } void collectAncestorsAndSelf([DisallowNull] RegionBuilder? from, [NotNull] ref ArrayBuilder<RegionBuilder>? builder) { if (builder == null) { builder = ArrayBuilder<RegionBuilder>.GetInstance(); } else if (builder.Count != 0) { return; } do { builder.Add(from); from = from.Enclosing; } while (from != null); builder.ReverseContents(); } // Can return index beyond bounds of "from" when no regions will be left. int getIndexOfLastLeftRegion(ArrayBuilder<RegionBuilder> from, ArrayBuilder<RegionBuilder> to) { int mismatch = 0; while (mismatch < from.Count && mismatch < to.Count && from[mismatch] == to[mismatch]) { mismatch++; } return mismatch; } } /// <summary> /// Deal with labeled blocks that were not added to the graph because labels were never found /// </summary> private static void CheckUnresolvedBranches(ArrayBuilder<BasicBlockBuilder> blocks, PooledDictionary<ILabelSymbol, BasicBlockBuilder>? labeledBlocks) { if (labeledBlocks == null) { return; } PooledHashSet<BasicBlockBuilder>? unresolved = null; foreach (BasicBlockBuilder labeled in labeledBlocks.Values) { if (labeled.Ordinal == -1) { if (unresolved == null) { unresolved = PooledHashSet<BasicBlockBuilder>.GetInstance(); } unresolved.Add(labeled); } } if (unresolved == null) { return; } // Mark branches using unresolved labels as errors. foreach (BasicBlockBuilder block in blocks) { fixupBranch(ref block.Conditional); fixupBranch(ref block.FallThrough); } unresolved.Free(); return; void fixupBranch(ref BasicBlockBuilder.Branch branch) { if (branch.Destination != null && unresolved.Contains(branch.Destination)) { Debug.Assert(branch.Kind == ControlFlowBranchSemantics.Regular); branch.Destination = null; branch.Kind = ControlFlowBranchSemantics.Error; } } } private void VisitStatement(IOperation? operation) { #if DEBUG int stackDepth = _evalStack.Count; Debug.Assert(stackDepth == 0 || _evalStack.Peek().frameOpt != null); #endif if (operation == null) { return; } IOperation? saveCurrentStatement = _currentStatement; _currentStatement = operation; EvalStackFrame frame = PushStackFrame(); AddStatement(base.Visit(operation, null)); PopStackFrameAndLeaveRegion(frame); #if DEBUG Debug.Assert(_evalStack.Count == stackDepth); Debug.Assert(stackDepth == 0 || _evalStack.Peek().frameOpt != null); #endif _currentStatement = saveCurrentStatement; } private BasicBlockBuilder CurrentBasicBlock { get { if (_currentBasicBlock == null) { AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); } return _currentBasicBlock; } } private void AddStatement( IOperation? statement #if DEBUG , bool spillingTheStack = false #endif ) { #if DEBUG Debug.Assert(spillingTheStack || _evalStack.All( slot => slot.operationOpt == null || slot.operationOpt.Kind == OperationKind.FlowCaptureReference || slot.operationOpt.Kind == OperationKind.DeclarationExpression || slot.operationOpt.Kind == OperationKind.Discard || slot.operationOpt.Kind == OperationKind.OmittedArgument)); #endif if (statement == null) { return; } Operation.SetParentOperation(statement, null); CurrentBasicBlock.AddStatement(statement); } [MemberNotNull(nameof(_currentBasicBlock))] private void AppendNewBlock(BasicBlockBuilder block, bool linkToPrevious = true) { Debug.Assert(block != null); Debug.Assert(_currentRegion != null); if (linkToPrevious) { BasicBlockBuilder prevBlock = _blocks.Last(); if (prevBlock.FallThrough.Destination == null) { LinkBlocks(prevBlock, block); } } if (block.Ordinal != -1) { throw ExceptionUtilities.Unreachable; } block.Ordinal = _blocks.Count; _blocks.Add(block); _currentBasicBlock = block; _currentRegion.ExtendToInclude(block); _regionMap.Add(block, _currentRegion); } private void EnterRegion(RegionBuilder region, bool spillingStack = false) { if (!spillingStack) { // Make sure all pending stack spilling regions are realised SpillEvalStack(); #if DEBUG Debug.Assert(_evalStack.Count == _startSpillingAt); VerifySpilledStackFrames(); #endif } _currentRegion?.Add(region); _currentRegion = region; _currentBasicBlock = null; } private void LeaveRegion() { // Ensure there is at least one block in the region Debug.Assert(_currentRegion != null); if (_currentRegion.IsEmpty) { AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); } RegionBuilder enclosed = _currentRegion; #if DEBUG // We shouldn't be leaving regions that are still associated with stack frames foreach ((EvalStackFrame? frameOpt, IOperation? operationOpt) in _evalStack) { Debug.Assert((frameOpt == null) != (operationOpt == null)); if (frameOpt != null) { Debug.Assert(enclosed != frameOpt.RegionBuilderOpt); } } #endif _currentRegion = _currentRegion.Enclosing; Debug.Assert(enclosed.LastBlock != null); _currentRegion?.ExtendToInclude(enclosed.LastBlock); _currentBasicBlock = null; } private static void LinkBlocks(BasicBlockBuilder prevBlock, BasicBlockBuilder nextBlock, ControlFlowBranchSemantics branchKind = ControlFlowBranchSemantics.Regular) { Debug.Assert(prevBlock.HasCondition || prevBlock.BranchValue == null); Debug.Assert(prevBlock.FallThrough.Destination == null); prevBlock.FallThrough.Destination = nextBlock; prevBlock.FallThrough.Kind = branchKind; nextBlock.AddPredecessor(prevBlock); } private void UnconditionalBranch(BasicBlockBuilder nextBlock) { LinkBlocks(CurrentBasicBlock, nextBlock); _currentBasicBlock = null; } public override IOperation? VisitBlock(IBlockOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals)); VisitStatements(operation.Operations); LeaveRegion(); return FinishVisitingStatement(operation); } private void StartVisitingStatement(IOperation operation) { Debug.Assert(_currentStatement == operation); Debug.Assert(_evalStack.Count == 0 || _evalStack.Peek().frameOpt != null); SpillEvalStack(); } [return: NotNullIfNotNull("result")] private IOperation? FinishVisitingStatement(IOperation originalOperation, IOperation? result = null) { Debug.Assert(((Operation)originalOperation).OwningSemanticModel != null, "Not an original node."); Debug.Assert(_currentStatement == originalOperation); Debug.Assert(_evalStack.Count == 0 || _evalStack.Peek().frameOpt != null); if (_currentStatement == originalOperation) { return result; } return result ?? MakeInvalidOperation(originalOperation.Syntax, originalOperation.Type, ImmutableArray<IOperation>.Empty); } private void VisitStatements(ImmutableArray<IOperation> statements) { for (int i = 0; i < statements.Length; i++) { if (VisitStatementsOneOrAll(statements[i], statements, i)) { break; } } } /// <summary> /// Either visits a single operation, or a using <see cref="IVariableDeclarationGroupOperation"/> and all subsequent statements /// </summary> /// <param name="operation">The statement to visit</param> /// <param name="statements">All statements in the block containing this node</param> /// <param name="startIndex">The current statement being visited in <paramref name="statements"/></param> /// <returns>True if this visited all of the statements</returns> /// <remarks> /// The operation being visited is not necessarily equal to statements[startIndex]. /// When traversing down a set of labels, we set operation to the label.Operation and recurse, but statements[startIndex] still refers to the original parent label /// as we haven't actually moved down the original statement list /// </remarks> private bool VisitStatementsOneOrAll(IOperation? operation, ImmutableArray<IOperation> statements, int startIndex) { switch (operation) { case IUsingDeclarationOperation usingDeclarationOperation: VisitUsingVariableDeclarationOperation(usingDeclarationOperation, statements.AsSpan()[(startIndex + 1)..]); return true; case ILabeledOperation { Operation: { } } labelOperation: return visitPossibleUsingDeclarationInLabel(labelOperation); default: VisitStatement(operation); return false; } bool visitPossibleUsingDeclarationInLabel(ILabeledOperation labelOperation) { var savedCurrentStatement = _currentStatement; _currentStatement = labelOperation; StartVisitingStatement(labelOperation); VisitLabel(labelOperation.Label); bool visitedAll = VisitStatementsOneOrAll(labelOperation.Operation, statements, startIndex); FinishVisitingStatement(labelOperation); _currentStatement = savedCurrentStatement; return visitedAll; } } internal override IOperation? VisitWithStatement(IWithStatementOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); ImplicitInstanceInfo previousInitializedInstance = _currentImplicitInstance; _currentImplicitInstance = new ImplicitInstanceInfo(VisitAndCapture(operation.Value)); VisitStatement(operation.Body); _currentImplicitInstance = previousInitializedInstance; return FinishVisitingStatement(operation); } public override IOperation? VisitConstructorBodyOperation(IConstructorBodyOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals)); if (operation.Initializer != null) { VisitStatement(operation.Initializer); } VisitMethodBodyBaseOperation(operation); LeaveRegion(); return FinishVisitingStatement(operation); } public override IOperation? VisitMethodBodyOperation(IMethodBodyOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); VisitMethodBodyBaseOperation(operation); return FinishVisitingStatement(operation); } private void VisitMethodBodyBaseOperation(IMethodBodyBaseOperation operation) { Debug.Assert(_currentStatement == operation); VisitMethodBodies(operation.BlockBody, operation.ExpressionBody); } private void VisitMethodBodies(IBlockOperation? blockBody, IBlockOperation? expressionBody) { if (blockBody != null) { VisitStatement(blockBody); // Check for error case with non-null BlockBody and non-null ExpressionBody. if (expressionBody != null) { // Link last block of visited BlockBody to the exit block. UnconditionalBranch(_exit); // Generate a special region for unreachable erroneous expression body. EnterRegion(new RegionBuilder(ControlFlowRegionKind.ErroneousBody)); VisitStatement(expressionBody); LeaveRegion(); } } else if (expressionBody != null) { VisitStatement(expressionBody); } } public override IOperation? VisitConditional(IConditionalOperation operation, int? captureIdForResult) { if (operation == _currentStatement) { if (operation.WhenFalse == null) { // if (condition) // consequence; // // becomes // // GotoIfFalse condition afterif; // consequence; // afterif: BasicBlockBuilder? afterIf = null; VisitConditionalBranch(operation.Condition, ref afterIf, jumpIfTrue: false); VisitStatement(operation.WhenTrue); AppendNewBlock(afterIf); } else { // if (condition) // consequence; // else // alternative // // becomes // // GotoIfFalse condition alt; // consequence // goto afterif; // alt: // alternative; // afterif: BasicBlockBuilder? whenFalse = null; VisitConditionalBranch(operation.Condition, ref whenFalse, jumpIfTrue: false); VisitStatement(operation.WhenTrue); var afterIf = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); VisitStatement(operation.WhenFalse); AppendNewBlock(afterIf); } return null; } else { // condition ? consequence : alternative // // becomes // // GotoIfFalse condition alt; // capture = consequence // goto afterif; // alt: // capture = alternative; // afterif: // result = capture Debug.Assert(operation is { WhenTrue: not null, WhenFalse: not null }); SpillEvalStack(); BasicBlockBuilder? whenFalse = null; VisitConditionalBranch(operation.Condition, ref whenFalse, jumpIfTrue: false); var afterIf = new BasicBlockBuilder(BasicBlockKind.Block); IOperation result; // Specially handle cases with "throw" as operation.WhenTrue or operation.WhenFalse. We don't need to create an additional // capture for the result because there won't be any result from the throwing branches. if (operation.WhenTrue is IConversionOperation whenTrueConversion && whenTrueConversion.Operand.Kind == OperationKind.Throw) { IOperation? rewrittenThrow = base.Visit(whenTrueConversion.Operand, null); Debug.Assert(rewrittenThrow!.Kind == OperationKind.None); Debug.Assert(rewrittenThrow.Children.IsEmpty()); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); result = VisitRequired(operation.WhenFalse); } else if (operation.WhenFalse is IConversionOperation whenFalseConversion && whenFalseConversion.Operand.Kind == OperationKind.Throw) { result = VisitRequired(operation.WhenTrue); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); IOperation rewrittenThrow = BaseVisitRequired(whenFalseConversion.Operand, null); Debug.Assert(rewrittenThrow.Kind == OperationKind.None); Debug.Assert(rewrittenThrow.Children.IsEmpty()); } else { var resultCaptureRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, isStackSpillRegion: true); EnterRegion(resultCaptureRegion); int captureId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); VisitAndCapture(operation.WhenTrue, captureId); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); VisitAndCapture(operation.WhenFalse, captureId); result = GetCaptureReference(captureId, operation); } AppendNewBlock(afterIf); return result; } } private void VisitAndCapture(IOperation operation, int captureId) { EvalStackFrame frame = PushStackFrame(); IOperation result = BaseVisitRequired(operation, captureId); PopStackFrame(frame); CaptureResultIfNotAlready(operation.Syntax, captureId, result); LeaveRegionIfAny(frame); } private IOperation VisitAndCapture(IOperation operation) { EvalStackFrame frame = PushStackFrame(); PushOperand(BaseVisitRequired(operation, null)); SpillEvalStack(); return PopStackFrame(frame, PopOperand()); } private void CaptureResultIfNotAlready(SyntaxNode syntax, int captureId, IOperation result) { Debug.Assert(_startSpillingAt == _evalStack.Count); if (result.Kind != OperationKind.FlowCaptureReference || captureId != ((IFlowCaptureReferenceOperation)result).Id.Value) { SpillEvalStack(); AddStatement(new FlowCaptureOperation(captureId, syntax, result)); } } /// <summary> /// This class captures information about beginning of stack frame /// and corresponding <see cref="RegionBuilder"/> if one was allocated to /// track <see cref="CaptureId"/>s used by the stack spilling, etc. /// Do not create instances of this type manually, use <see cref="PushStackFrame"/> /// helper instead. Also, do not assign <see cref="RegionBuilderOpt"/> explicitly. /// Let the builder machinery do this when appropriate. /// </summary> private class EvalStackFrame { private RegionBuilder? _lazyRegionBuilder; public RegionBuilder? RegionBuilderOpt { get { return _lazyRegionBuilder; } set { Debug.Assert(_lazyRegionBuilder == null); Debug.Assert(value != null); _lazyRegionBuilder = value; } } } private EvalStackFrame PushStackFrame() { var frame = new EvalStackFrame(); _evalStack.Push((frame, operationOpt: null)); return frame; } private void PopStackFrame(EvalStackFrame frame, bool mergeNestedRegions = true) { Debug.Assert(frame != null); int stackDepth = _evalStack.Count; Debug.Assert(_startSpillingAt <= stackDepth); if (_startSpillingAt == stackDepth) { _startSpillingAt--; } (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack.Pop(); Debug.Assert(frame == frameOpt); Debug.Assert(operationOpt == null); if (frame.RegionBuilderOpt != null && mergeNestedRegions) { while (_currentRegion != frame.RegionBuilderOpt) { Debug.Assert(_currentRegion != null); RegionBuilder toMerge = _currentRegion; Debug.Assert(toMerge.Enclosing != null); _currentRegion = toMerge.Enclosing; Debug.Assert(toMerge.IsStackSpillRegion); Debug.Assert(!toMerge.HasLocalFunctions); Debug.Assert(toMerge.Locals.IsEmpty); _currentRegion.AddCaptureIds(toMerge.CaptureIds); // This region can be empty in certain error scenarios, such as `new T {}`, where T does not // have a class constraint. There are no arguments or initializers, so nothing will have // been put into the region at this point if (!toMerge.IsEmpty) { _currentRegion.ExtendToInclude(toMerge.LastBlock); } MergeSubRegionAndFree(toMerge, _blocks, _regionMap, canHaveEmptyRegion: true); } } } private void PopStackFrameAndLeaveRegion(EvalStackFrame frame) { PopStackFrame(frame); LeaveRegionIfAny(frame); } private void LeaveRegionIfAny(EvalStackFrame frame) { RegionBuilder? toLeave = frame.RegionBuilderOpt; if (toLeave != null) { while (_currentRegion != toLeave) { Debug.Assert(_currentRegion!.IsStackSpillRegion); LeaveRegion(); } LeaveRegion(); } } private T PopStackFrame<T>(EvalStackFrame frame, T value) { PopStackFrame(frame); return value; } private void LeaveRegionsUpTo(RegionBuilder resultCaptureRegion) { while (_currentRegion != resultCaptureRegion) { LeaveRegion(); } } private int GetNextCaptureId(RegionBuilder owner) { Debug.Assert(owner != null); int captureId = _captureIdDispenser.GetNextId(); owner.AddCaptureId(captureId); return captureId; } private void SpillEvalStack() { Debug.Assert(_startSpillingAt <= _evalStack.Count); #if DEBUG VerifySpilledStackFrames(); #endif int currentFrameIndex = -1; for (int i = _startSpillingAt - 1; i >= 0; i--) { (EvalStackFrame? frameOpt, _) = _evalStack[i]; if (frameOpt != null) { currentFrameIndex = i; Debug.Assert(frameOpt.RegionBuilderOpt != null); break; } } for (int i = _startSpillingAt; i < _evalStack.Count; i++) { (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack[i]; Debug.Assert((frameOpt == null) != (operationOpt == null)); if (frameOpt != null) { currentFrameIndex = i; Debug.Assert(frameOpt.RegionBuilderOpt == null); frameOpt.RegionBuilderOpt = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, isStackSpillRegion: true); EnterRegion(frameOpt.RegionBuilderOpt, spillingStack: true); continue; } Debug.Assert(operationOpt != null); // Declarations cannot have control flow, so we don't need to spill them. if (operationOpt.Kind != OperationKind.FlowCaptureReference && operationOpt.Kind != OperationKind.DeclarationExpression && operationOpt.Kind != OperationKind.Discard && operationOpt.Kind != OperationKind.OmittedArgument) { // Here we need to decide what region should own the new capture. Due to the spilling operations occurred before, // we currently might be in a region that is not associated with the stack frame we are in, but it is one of its // directly or indirectly nested regions. The operation that we are about to spill is likely to remove references // to some captures from the stack. That means that, after the spilling, we should be able to leave the spill // regions that no longer own captures referenced on the stack. The new capture that we create, should belong to // the region that will become current after that. Here we are trying to compute what will be that region. // Obviously, we shouldn’t be leaving the region associated with the frame. EvalStackFrame? currentFrame = _evalStack[currentFrameIndex].frameOpt; Debug.Assert(currentFrame != null); RegionBuilder? currentSpillRegion = currentFrame.RegionBuilderOpt; Debug.Assert(currentSpillRegion != null); if (_currentRegion != currentSpillRegion) { var idsStillOnTheStack = PooledHashSet<CaptureId>.GetInstance(); for (int j = currentFrameIndex + 1; j < _evalStack.Count; j++) { IOperation? operation = _evalStack[j].operationOpt; if (operation != null) { if (j < i) { if (operation is IFlowCaptureReferenceOperation reference) { idsStillOnTheStack.Add(reference.Id); } } else if (j > i) { foreach (IFlowCaptureReferenceOperation reference in operation.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { idsStillOnTheStack.Add(reference.Id); } } } } RegionBuilder candidate = CurrentRegionRequired; do { Debug.Assert(candidate.IsStackSpillRegion); if (candidate.HasCaptureIds && candidate.CaptureIds.Any((id, set) => set.Contains(id), idsStillOnTheStack)) { currentSpillRegion = candidate; break; } Debug.Assert(candidate.Enclosing != null); candidate = candidate.Enclosing; } while (candidate != currentSpillRegion); idsStillOnTheStack.Free(); } int captureId = GetNextCaptureId(currentSpillRegion); AddStatement(new FlowCaptureOperation(captureId, operationOpt.Syntax, operationOpt) #if DEBUG , spillingTheStack: true #endif ); _evalStack[i] = (frameOpt: null, operationOpt: GetCaptureReference(captureId, operationOpt)); while (_currentRegion != currentSpillRegion) { Debug.Assert(CurrentRegionRequired.IsStackSpillRegion); LeaveRegion(); } } } _startSpillingAt = _evalStack.Count; } #if DEBUG private void VerifySpilledStackFrames() { for (int i = 0; i < _startSpillingAt; i++) { (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack[i]; if (frameOpt != null) { Debug.Assert(operationOpt == null); Debug.Assert(frameOpt.RegionBuilderOpt != null); } else { Debug.Assert(operationOpt != null); } } } #endif private void PushOperand(IOperation operation) { Debug.Assert(_evalStack.Count != 0); Debug.Assert(_evalStack.First().frameOpt != null); Debug.Assert(_evalStack.First().operationOpt == null); Debug.Assert(_startSpillingAt <= _evalStack.Count); Debug.Assert(operation != null); _evalStack.Push((frameOpt: null, operation)); } private IOperation PopOperand() { int stackDepth = _evalStack.Count; Debug.Assert(_startSpillingAt <= stackDepth); if (_startSpillingAt == stackDepth) { _startSpillingAt--; } (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack.Pop(); Debug.Assert(frameOpt == null); Debug.Assert(operationOpt != null); return operationOpt; } private IOperation PeekOperand() { Debug.Assert(_startSpillingAt <= _evalStack.Count); (EvalStackFrame? frameOpt, IOperation? operationOpt) = _evalStack.Peek(); Debug.Assert(frameOpt == null); Debug.Assert(operationOpt != null); return operationOpt; } private void VisitAndPushArray<T>(ImmutableArray<T> array, Func<T, IOperation>? unwrapper = null) where T : IOperation { Debug.Assert(unwrapper != null || typeof(T) == typeof(IOperation)); foreach (var element in array) { PushOperand(VisitRequired(unwrapper == null ? element : unwrapper(element))); } } private ImmutableArray<T> PopArray<T>(ImmutableArray<T> originalArray, Func<IOperation, int, ImmutableArray<T>, T>? wrapper = null) where T : IOperation { Debug.Assert(wrapper != null || typeof(T) == typeof(IOperation)); int numElements = originalArray.Length; if (numElements == 0) { return ImmutableArray<T>.Empty; } else { var builder = ArrayBuilder<T>.GetInstance(numElements); // Iterate in reverse order so the index corresponds to the original index when pushed onto the stack for (int i = numElements - 1; i >= 0; i--) { IOperation visitedElement = PopOperand(); builder.Add(wrapper != null ? wrapper(visitedElement, i, originalArray) : (T)visitedElement); } builder.ReverseContents(); return builder.ToImmutableAndFree(); } } private ImmutableArray<T> VisitArray<T>(ImmutableArray<T> originalArray, Func<T, IOperation>? unwrapper = null, Func<IOperation, int, ImmutableArray<T>, T>? wrapper = null) where T : IOperation { #if DEBUG int stackSizeBefore = _evalStack.Count; #endif VisitAndPushArray(originalArray, unwrapper); ImmutableArray<T> visitedArray = PopArray(originalArray, wrapper); #if DEBUG Debug.Assert(stackSizeBefore == _evalStack.Count); #endif return visitedArray; } private ImmutableArray<IArgumentOperation> VisitArguments(ImmutableArray<IArgumentOperation> arguments) { return VisitArray(arguments, UnwrapArgument, RewriteArgumentFromArray); } private static IOperation UnwrapArgument(IArgumentOperation argument) { return argument.Value; } private IArgumentOperation RewriteArgumentFromArray(IOperation visitedArgument, int index, ImmutableArray<IArgumentOperation> args) { Debug.Assert(index >= 0 && index < args.Length); var originalArgument = (ArgumentOperation)args[index]; return new ArgumentOperation(originalArgument.ArgumentKind, originalArgument.Parameter, visitedArgument, originalArgument.InConversionConvertible, originalArgument.OutConversionConvertible, semanticModel: null, originalArgument.Syntax, IsImplicit(originalArgument)); } public override IOperation VisitSimpleAssignment(ISimpleAssignmentOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.Target)); IOperation value = VisitRequired(operation.Value); return PopStackFrame(frame, new SimpleAssignmentOperation(operation.IsRef, PopOperand(), value, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); } public override IOperation VisitCompoundAssignment(ICompoundAssignmentOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); var compoundAssignment = (CompoundAssignmentOperation)operation; PushOperand(VisitRequired(compoundAssignment.Target)); IOperation value = VisitRequired(compoundAssignment.Value); return PopStackFrame(frame, new CompoundAssignmentOperation(compoundAssignment.InConversionConvertible, compoundAssignment.OutConversionConvertible, operation.OperatorKind, operation.IsLifted, operation.IsChecked, operation.OperatorMethod, PopOperand(), value, semanticModel: null, syntax: operation.Syntax, type: operation.Type, isImplicit: IsImplicit(operation))); } public override IOperation VisitArrayElementReference(IArrayElementReferenceOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.ArrayReference)); ImmutableArray<IOperation> visitedIndices = VisitArray(operation.Indices); IOperation visitedArrayReference = PopOperand(); PopStackFrame(frame); return new ArrayElementReferenceOperation(visitedArrayReference, visitedIndices, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } private static bool IsConditional(IBinaryOperation operation) { switch (operation.OperatorKind) { case BinaryOperatorKind.ConditionalOr: case BinaryOperatorKind.ConditionalAnd: return true; } return false; } public override IOperation VisitBinaryOperator(IBinaryOperation operation, int? captureIdForResult) { if (IsConditional(operation)) { if (operation.OperatorMethod == null) { if (ITypeSymbolHelpers.IsBooleanType(operation.Type) && ITypeSymbolHelpers.IsBooleanType(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsBooleanType(operation.RightOperand.Type)) { // Regular boolean logic return VisitBinaryConditionalOperator(operation, sense: true, captureIdForResult, fallToTrueOpt: null, fallToFalseOpt: null); } else if (operation.IsLifted && ITypeSymbolHelpers.IsNullableOfBoolean(operation.Type) && ITypeSymbolHelpers.IsNullableOfBoolean(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsNullableOfBoolean(operation.RightOperand.Type)) { // Three-value boolean logic (VB). return VisitNullableBinaryConditionalOperator(operation, captureIdForResult); } else if (ITypeSymbolHelpers.IsObjectType(operation.Type) && ITypeSymbolHelpers.IsObjectType(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsObjectType(operation.RightOperand.Type)) { return VisitObjectBinaryConditionalOperator(operation, captureIdForResult); } else if (ITypeSymbolHelpers.IsDynamicType(operation.Type) && (ITypeSymbolHelpers.IsDynamicType(operation.LeftOperand.Type) || ITypeSymbolHelpers.IsDynamicType(operation.RightOperand.Type))) { return VisitDynamicBinaryConditionalOperator(operation, captureIdForResult); } } else { return VisitUserDefinedBinaryConditionalOperator(operation, captureIdForResult); } } EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.LeftOperand)); IOperation rightOperand = VisitRequired(operation.RightOperand); return PopStackFrame(frame, new BinaryOperation(operation.OperatorKind, PopOperand(), rightOperand, operation.IsLifted, operation.IsChecked, operation.IsCompareText, operation.OperatorMethod, ((BinaryOperation)operation).UnaryOperatorMethod, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); } public override IOperation VisitTupleBinaryOperator(ITupleBinaryOperation operation, int? captureIdForResult) { (IOperation visitedLeft, IOperation visitedRight) = VisitPreservingTupleOperations(operation.LeftOperand, operation.RightOperand); return new TupleBinaryOperation(operation.OperatorKind, visitedLeft, visitedRight, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitUnaryOperator(IUnaryOperation operation, int? captureIdForResult) { if (IsBooleanLogicalNot(operation)) { return VisitConditionalExpression(operation, sense: true, captureIdForResult, fallToTrueOpt: null, fallToFalseOpt: null); } return new UnaryOperation(operation.OperatorKind, VisitRequired(operation.Operand), operation.IsLifted, operation.IsChecked, operation.OperatorMethod, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } private static bool IsBooleanLogicalNot(IUnaryOperation operation) { return operation.OperatorKind == UnaryOperatorKind.Not && operation.OperatorMethod == null && ITypeSymbolHelpers.IsBooleanType(operation.Type) && ITypeSymbolHelpers.IsBooleanType(operation.Operand.Type); } private static bool CalculateAndOrSense(IBinaryOperation binOp, bool sense) { switch (binOp.OperatorKind) { case BinaryOperatorKind.ConditionalOr: // Rewrite (a || b) as ~(~a && ~b) return !sense; case BinaryOperatorKind.ConditionalAnd: return sense; default: throw ExceptionUtilities.UnexpectedValue(binOp.OperatorKind); } } private IOperation VisitBinaryConditionalOperator(IBinaryOperation binOp, bool sense, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) { // ~(a && b) is equivalent to (~a || ~b) if (!CalculateAndOrSense(binOp, sense)) { // generate (~a || ~b) return VisitShortCircuitingOperator(binOp, sense: sense, stopSense: sense, stopValue: true, captureIdForResult, fallToTrueOpt, fallToFalseOpt); } else { // generate (a && b) return VisitShortCircuitingOperator(binOp, sense: sense, stopSense: !sense, stopValue: false, captureIdForResult, fallToTrueOpt, fallToFalseOpt); } } private IOperation VisitNullableBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) { SpillEvalStack(); IOperation left = binOp.LeftOperand; IOperation right = binOp.RightOperand; IOperation condition; bool isAndAlso = CalculateAndOrSense(binOp, true); // case BinaryOperatorKind.ConditionalOr: // Dim result As Boolean? // // If left.GetValueOrDefault Then // GoTo resultIsLeft // End If // // If Not ((Not right).GetValueOrDefault) Then // result = right // GoTo done // End If // //resultIsLeft: // result = left // //done: // Return result // case BinaryOperatorKind.ConditionalAnd: // Dim result As Boolean? // // If (Not left).GetValueOrDefault() Then // GoTo resultIsLeft // End If // // If Not (right.GetValueOrDefault()) Then // result = right // GoTo done // End If // //resultIsLeft: // result = left // //done: // Return result var resultCaptureRegion = CurrentRegionRequired; var done = new BasicBlockBuilder(BasicBlockKind.Block); var checkRight = new BasicBlockBuilder(BasicBlockKind.Block); var resultIsLeft = new BasicBlockBuilder(BasicBlockKind.Block); IOperation capturedLeft = VisitAndCapture(left); condition = capturedLeft; if (isAndAlso) { condition = negateNullable(condition); } condition = CallNullableMember(condition, SpecialMember.System_Nullable_T_GetValueOrDefault); ConditionalBranch(condition, jumpIfTrue: true, resultIsLeft); UnconditionalBranch(checkRight); int resultId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); AppendNewBlock(checkRight); EvalStackFrame frame = PushStackFrame(); IOperation capturedRight = VisitAndCapture(right); condition = capturedRight; if (!isAndAlso) { condition = negateNullable(condition); } condition = CallNullableMember(condition, SpecialMember.System_Nullable_T_GetValueOrDefault); ConditionalBranch(condition, jumpIfTrue: true, resultIsLeft); _currentBasicBlock = null; AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, OperationCloner.CloneOperation(capturedRight))); UnconditionalBranch(done); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(resultIsLeft); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, OperationCloner.CloneOperation(capturedLeft))); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(done); return GetCaptureReference(resultId, binOp); IOperation negateNullable(IOperation operand) { return new UnaryOperation(UnaryOperatorKind.Not, operand, isLifted: true, isChecked: false, operatorMethod: null, semanticModel: null, operand.Syntax, operand.Type, constantValue: null, isImplicit: true); } } private IOperation VisitObjectBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) { SpillEvalStack(); INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); IOperation left = binOp.LeftOperand; IOperation right = binOp.RightOperand; IOperation condition; bool isAndAlso = CalculateAndOrSense(binOp, true); var done = new BasicBlockBuilder(BasicBlockKind.Block); var checkRight = new BasicBlockBuilder(BasicBlockKind.Block); EvalStackFrame frame = PushStackFrame(); condition = CreateConversion(VisitRequired(left), booleanType); ConditionalBranch(condition, jumpIfTrue: isAndAlso, checkRight); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); var resultCaptureRegion = CurrentRegionRequired; int resultId = GetNextCaptureId(resultCaptureRegion); ConstantValue constantValue = ConstantValue.Create(!isAndAlso); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, new LiteralOperation(semanticModel: null, left.Syntax, booleanType, constantValue, isImplicit: true))); UnconditionalBranch(done); AppendNewBlock(checkRight); frame = PushStackFrame(); condition = CreateConversion(VisitRequired(right), booleanType); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, condition)); PopStackFrame(frame); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(done); condition = new FlowCaptureReferenceOperation(resultId, binOp.Syntax, booleanType, constantValue: null); Debug.Assert(binOp.Type is not null); return new ConversionOperation(condition, _compilation.ClassifyConvertibleConversion(condition, binOp.Type, out _), isTryCast: false, isChecked: false, semanticModel: null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), isImplicit: true); } private IOperation CreateConversion(IOperation operand, ITypeSymbol type) { return new ConversionOperation(operand, _compilation.ClassifyConvertibleConversion(operand, type, out ConstantValue? constantValue), isTryCast: false, isChecked: false, semanticModel: null, operand.Syntax, type, constantValue, isImplicit: true); } private IOperation VisitDynamicBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) { SpillEvalStack(); Debug.Assert(binOp.Type is not null); var resultCaptureRegion = CurrentRegionRequired; INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); IOperation left = binOp.LeftOperand; IOperation right = binOp.RightOperand; IMethodSymbol? unaryOperatorMethod = ((BinaryOperation)binOp).UnaryOperatorMethod; bool isAndAlso = CalculateAndOrSense(binOp, true); bool jumpIfTrue; IOperation condition; // Dynamic logical && and || operators are lowered as follows: // left && right -> IsFalse(left) ? left : And(left, right) // left || right -> IsTrue(left) ? left : Or(left, right) var done = new BasicBlockBuilder(BasicBlockKind.Block); var doBitWise = new BasicBlockBuilder(BasicBlockKind.Block); IOperation capturedLeft = VisitAndCapture(left); condition = capturedLeft; if (ITypeSymbolHelpers.IsBooleanType(left.Type)) { Debug.Assert(unaryOperatorMethod == null); jumpIfTrue = isAndAlso; } else if (ITypeSymbolHelpers.IsDynamicType(left.Type) || unaryOperatorMethod != null) { jumpIfTrue = false; if (unaryOperatorMethod == null || (ITypeSymbolHelpers.IsBooleanType(unaryOperatorMethod.ReturnType) && (ITypeSymbolHelpers.IsNullableType(left.Type) || !ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)))) { condition = new UnaryOperation(isAndAlso ? UnaryOperatorKind.False : UnaryOperatorKind.True, condition, isLifted: false, isChecked: false, operatorMethod: unaryOperatorMethod, semanticModel: null, condition.Syntax, booleanType, constantValue: null, isImplicit: true); } else { condition = MakeInvalidOperation(booleanType, condition); } } else { // This is either an error case, or left is implicitly convertible to boolean condition = CreateConversion(condition, booleanType); jumpIfTrue = isAndAlso; } ConditionalBranch(condition, jumpIfTrue, doBitWise); _currentBasicBlock = null; int resultId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); IOperation resultFromLeft = OperationCloner.CloneOperation(capturedLeft); if (!ITypeSymbolHelpers.IsDynamicType(left.Type)) { resultFromLeft = CreateConversion(resultFromLeft, binOp.Type); } AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, resultFromLeft)); UnconditionalBranch(done); AppendNewBlock(doBitWise); EvalStackFrame frame = PushStackFrame(); PushOperand(OperationCloner.CloneOperation(capturedLeft)); IOperation visitedRight = VisitRequired(right); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, new BinaryOperation(isAndAlso ? BinaryOperatorKind.And : BinaryOperatorKind.Or, PopOperand(), visitedRight, isLifted: false, binOp.IsChecked, binOp.IsCompareText, binOp.OperatorMethod, unaryOperatorMethod: null, semanticModel: null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), IsImplicit(binOp)))); PopStackFrameAndLeaveRegion(frame); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(done); return GetCaptureReference(resultId, binOp); } private IOperation VisitUserDefinedBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) { SpillEvalStack(); var resultCaptureRegion = CurrentRegionRequired; INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); bool isLifted = binOp.IsLifted; IOperation left = binOp.LeftOperand; IOperation right = binOp.RightOperand; IMethodSymbol? unaryOperatorMethod = ((BinaryOperation)binOp).UnaryOperatorMethod; bool isAndAlso = CalculateAndOrSense(binOp, true); IOperation condition; var done = new BasicBlockBuilder(BasicBlockKind.Block); var doBitWise = new BasicBlockBuilder(BasicBlockKind.Block); IOperation capturedLeft = VisitAndCapture(left); condition = capturedLeft; if (ITypeSymbolHelpers.IsNullableType(left.Type)) { if (unaryOperatorMethod == null ? isLifted : !ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)) { condition = MakeIsNullOperation(condition, booleanType); ConditionalBranch(condition, jumpIfTrue: true, doBitWise); _currentBasicBlock = null; Debug.Assert(unaryOperatorMethod == null || !ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)); condition = CallNullableMember(OperationCloner.CloneOperation(capturedLeft), SpecialMember.System_Nullable_T_GetValueOrDefault); } } else if (unaryOperatorMethod != null && ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)) { condition = MakeInvalidOperation(unaryOperatorMethod.Parameters[0].Type, condition); } if (unaryOperatorMethod != null && ITypeSymbolHelpers.IsBooleanType(unaryOperatorMethod.ReturnType)) { condition = new UnaryOperation(isAndAlso ? UnaryOperatorKind.False : UnaryOperatorKind.True, condition, isLifted: false, isChecked: false, operatorMethod: unaryOperatorMethod, semanticModel: null, condition.Syntax, unaryOperatorMethod.ReturnType, constantValue: null, isImplicit: true); } else { condition = MakeInvalidOperation(booleanType, condition); } ConditionalBranch(condition, jumpIfTrue: false, doBitWise); _currentBasicBlock = null; int resultId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, OperationCloner.CloneOperation(capturedLeft))); UnconditionalBranch(done); AppendNewBlock(doBitWise); EvalStackFrame frame = PushStackFrame(); PushOperand(OperationCloner.CloneOperation(capturedLeft)); IOperation visitedRight = VisitRequired(right); AddStatement(new FlowCaptureOperation(resultId, binOp.Syntax, new BinaryOperation(isAndAlso ? BinaryOperatorKind.And : BinaryOperatorKind.Or, PopOperand(), visitedRight, isLifted, binOp.IsChecked, binOp.IsCompareText, binOp.OperatorMethod, unaryOperatorMethod: null, semanticModel: null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), IsImplicit(binOp)))); PopStackFrameAndLeaveRegion(frame); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(done); return GetCaptureReference(resultId, binOp); } private IOperation VisitShortCircuitingOperator(IBinaryOperation condition, bool sense, bool stopSense, bool stopValue, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) { Debug.Assert(IsBooleanConditionalOperator(condition)); // we generate: // // gotoif (a == stopSense) fallThrough // b == sense // goto labEnd // fallThrough: // stopValue // labEnd: // AND OR // +- ------ ----- // stopSense | !sense sense // stopValue | 0 1 SpillEvalStack(); ref BasicBlockBuilder? lazyFallThrough = ref stopValue ? ref fallToTrueOpt : ref fallToFalseOpt; bool newFallThroughBlock = (lazyFallThrough == null); VisitConditionalBranch(condition.LeftOperand, ref lazyFallThrough, stopSense); var resultCaptureRegion = CurrentRegionRequired; int captureId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); IOperation resultFromRight = VisitConditionalExpression(condition.RightOperand, sense, captureId, fallToTrueOpt, fallToFalseOpt); CaptureResultIfNotAlready(condition.RightOperand.Syntax, captureId, resultFromRight); LeaveRegionsUpTo(resultCaptureRegion); if (newFallThroughBlock) { var labEnd = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(labEnd); AppendNewBlock(lazyFallThrough); var constantValue = ConstantValue.Create(stopValue); SyntaxNode leftSyntax = (lazyFallThrough!.GetSingletonPredecessorOrDefault() != null ? condition.LeftOperand : condition).Syntax; AddStatement(new FlowCaptureOperation(captureId, leftSyntax, new LiteralOperation(semanticModel: null, leftSyntax, condition.Type, constantValue, isImplicit: true))); AppendNewBlock(labEnd); } return GetCaptureReference(captureId, condition); } private IOperation VisitConditionalExpression(IOperation condition, bool sense, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) { Debug.Assert(ITypeSymbolHelpers.IsBooleanType(condition.Type)); IUnaryOperation? lastUnary = null; do { switch (condition) { case IParenthesizedOperation parenthesized: condition = parenthesized.Operand; continue; case IUnaryOperation unary when IsBooleanLogicalNot(unary): lastUnary = unary; condition = unary.Operand; sense = !sense; continue; } break; } while (true); if (condition.Kind == OperationKind.Binary) { var binOp = (IBinaryOperation)condition; if (IsBooleanConditionalOperator(binOp)) { return VisitBinaryConditionalOperator(binOp, sense, captureIdForResult, fallToTrueOpt, fallToFalseOpt); } } condition = VisitRequired(condition); if (!sense) { return lastUnary != null ? new UnaryOperation(lastUnary.OperatorKind, condition, lastUnary.IsLifted, lastUnary.IsChecked, lastUnary.OperatorMethod, semanticModel: null, lastUnary.Syntax, lastUnary.Type, lastUnary.GetConstantValue(), IsImplicit(lastUnary)) : new UnaryOperation(UnaryOperatorKind.Not, condition, isLifted: false, isChecked: false, operatorMethod: null, semanticModel: null, condition.Syntax, condition.Type, constantValue: null, isImplicit: true); } return condition; } private static bool IsBooleanConditionalOperator(IBinaryOperation binOp) { return IsConditional(binOp) && binOp.OperatorMethod == null && ITypeSymbolHelpers.IsBooleanType(binOp.Type) && ITypeSymbolHelpers.IsBooleanType(binOp.LeftOperand.Type) && ITypeSymbolHelpers.IsBooleanType(binOp.RightOperand.Type); } private void VisitConditionalBranch(IOperation condition, [NotNull] ref BasicBlockBuilder? dest, bool jumpIfTrue) { SpillEvalStack(); #if DEBUG RegionBuilder? current = _currentRegion; #endif VisitConditionalBranchCore(condition, ref dest, jumpIfTrue); #if DEBUG Debug.Assert(current == _currentRegion); #endif } /// <summary> /// This function does not change the current region. The stack should be spilled before calling it. /// </summary> private void VisitConditionalBranchCore(IOperation condition, [NotNull] ref BasicBlockBuilder? dest, bool jumpIfTrue) { oneMoreTime: Debug.Assert(_startSpillingAt == _evalStack.Count); while (condition.Kind == OperationKind.Parenthesized) { condition = ((IParenthesizedOperation)condition).Operand; } switch (condition.Kind) { case OperationKind.Binary: var binOp = (IBinaryOperation)condition; if (IsBooleanConditionalOperator(binOp)) { if (CalculateAndOrSense(binOp, jumpIfTrue)) { // gotoif(LeftOperand != sense) fallThrough // gotoif(RightOperand == sense) dest // fallThrough: BasicBlockBuilder? fallThrough = null; VisitConditionalBranchCore(binOp.LeftOperand, ref fallThrough, !jumpIfTrue); VisitConditionalBranchCore(binOp.RightOperand, ref dest, jumpIfTrue); AppendNewBlock(fallThrough); return; } else { // gotoif(LeftOperand == sense) dest // gotoif(RightOperand == sense) dest VisitConditionalBranchCore(binOp.LeftOperand, ref dest, jumpIfTrue); condition = binOp.RightOperand; goto oneMoreTime; } } // none of above. // then it is regular binary expression - Or, And, Xor ... goto default; case OperationKind.Unary: var unOp = (IUnaryOperation)condition; if (IsBooleanLogicalNot(unOp)) { jumpIfTrue = !jumpIfTrue; condition = unOp.Operand; goto oneMoreTime; } goto default; case OperationKind.Conditional: if (ITypeSymbolHelpers.IsBooleanType(condition.Type)) { var conditional = (IConditionalOperation)condition; Debug.Assert(conditional.WhenFalse is not null); if (ITypeSymbolHelpers.IsBooleanType(conditional.WhenTrue.Type) && ITypeSymbolHelpers.IsBooleanType(conditional.WhenFalse.Type)) { BasicBlockBuilder? whenFalse = null; VisitConditionalBranchCore(conditional.Condition, ref whenFalse, jumpIfTrue: false); VisitConditionalBranchCore(conditional.WhenTrue, ref dest, jumpIfTrue); var afterIf = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(afterIf); AppendNewBlock(whenFalse); VisitConditionalBranchCore(conditional.WhenFalse, ref dest, jumpIfTrue); AppendNewBlock(afterIf); return; } } goto default; case OperationKind.Coalesce: if (ITypeSymbolHelpers.IsBooleanType(condition.Type)) { var coalesce = (ICoalesceOperation)condition; if (ITypeSymbolHelpers.IsBooleanType(coalesce.WhenNull.Type)) { var whenNull = new BasicBlockBuilder(BasicBlockKind.Block); EvalStackFrame frame = PushStackFrame(); IOperation convertedTestExpression = NullCheckAndConvertCoalesceValue(coalesce, whenNull); dest = dest ?? new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(convertedTestExpression, jumpIfTrue, dest); _currentBasicBlock = null; var afterCoalesce = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(afterCoalesce); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(whenNull); VisitConditionalBranchCore(coalesce.WhenNull, ref dest, jumpIfTrue); AppendNewBlock(afterCoalesce); return; } } goto default; case OperationKind.Conversion: var conversion = (IConversionOperation)condition; if (conversion.Operand.Kind == OperationKind.Throw) { IOperation? rewrittenThrow = base.Visit(conversion.Operand, null); Debug.Assert(rewrittenThrow != null); Debug.Assert(rewrittenThrow.Kind == OperationKind.None); Debug.Assert(rewrittenThrow.Children.IsEmpty()); dest = dest ?? new BasicBlockBuilder(BasicBlockKind.Block); return; } goto default; default: { EvalStackFrame frame = PushStackFrame(); condition = VisitRequired(condition); dest = dest ?? new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(condition, jumpIfTrue, dest); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); return; } } } private void ConditionalBranch(IOperation condition, bool jumpIfTrue, BasicBlockBuilder destination) { BasicBlockBuilder previous = CurrentBasicBlock; BasicBlockBuilder.Branch branch = RegularBranch(destination); Debug.Assert(previous.BranchValue == null); Debug.Assert(!previous.HasCondition); Debug.Assert(condition != null); Debug.Assert(branch.Destination != null); Operation.SetParentOperation(condition, null); branch.Destination.AddPredecessor(previous); previous.BranchValue = condition; previous.ConditionKind = jumpIfTrue ? ControlFlowConditionKind.WhenTrue : ControlFlowConditionKind.WhenFalse; previous.Conditional = branch; } /// <summary> /// Returns converted test expression. /// Caller is responsible for spilling the stack and pushing a stack frame before calling this helper. /// </summary> private IOperation NullCheckAndConvertCoalesceValue(ICoalesceOperation operation, BasicBlockBuilder whenNull) { Debug.Assert(_evalStack.Last().frameOpt != null); Debug.Assert(_startSpillingAt >= _evalStack.Count - 1); IOperation operationValue = operation.Value; SyntaxNode valueSyntax = operationValue.Syntax; ITypeSymbol? valueTypeOpt = operationValue.Type; PushOperand(VisitRequired(operationValue)); SpillEvalStack(); IOperation testExpression = PopOperand(); ConditionalBranch(MakeIsNullOperation(testExpression), jumpIfTrue: true, whenNull); _currentBasicBlock = null; CommonConversion testConversion = operation.ValueConversion; IOperation capturedValue = OperationCloner.CloneOperation(testExpression); IOperation? convertedTestExpression = null; if (testConversion.Exists) { IOperation? possiblyUnwrappedValue; if (ITypeSymbolHelpers.IsNullableType(valueTypeOpt) && (!testConversion.IsIdentity || !ITypeSymbolHelpers.IsNullableType(operation.Type))) { possiblyUnwrappedValue = TryCallNullableMember(capturedValue, SpecialMember.System_Nullable_T_GetValueOrDefault); } else { possiblyUnwrappedValue = capturedValue; } if (possiblyUnwrappedValue != null) { if (testConversion.IsIdentity) { convertedTestExpression = possiblyUnwrappedValue; } else { convertedTestExpression = new ConversionOperation(possiblyUnwrappedValue, ((CoalesceOperation)operation).ValueConversionConvertible, isTryCast: false, isChecked: false, semanticModel: null, valueSyntax, operation.Type, constantValue: null, isImplicit: true); } } } if (convertedTestExpression == null) { convertedTestExpression = MakeInvalidOperation(operation.Type, capturedValue); } return convertedTestExpression; } public override IOperation VisitCoalesce(ICoalesceOperation operation, int? captureIdForResult) { SpillEvalStack(); var conversion = operation.WhenNull as IConversionOperation; bool alternativeThrows = conversion?.Operand.Kind == OperationKind.Throw; RegionBuilder resultCaptureRegion = CurrentRegionRequired; EvalStackFrame frame = PushStackFrame(); var whenNull = new BasicBlockBuilder(BasicBlockKind.Block); IOperation convertedTestExpression = NullCheckAndConvertCoalesceValue(operation, whenNull); IOperation result; var afterCoalesce = new BasicBlockBuilder(BasicBlockKind.Block); if (alternativeThrows) { // This is a special case with "throw" as an alternative. We don't need to create an additional // capture for the result because there won't be any result from the alternative branch. result = convertedTestExpression; UnconditionalBranch(afterCoalesce); PopStackFrame(frame); AppendNewBlock(whenNull); Debug.Assert(conversion is not null); IOperation? rewrittenThrow = base.Visit(conversion.Operand, null); Debug.Assert(rewrittenThrow != null); Debug.Assert(rewrittenThrow.Kind == OperationKind.None); Debug.Assert(rewrittenThrow.Children.IsEmpty()); } else { int resultCaptureId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Value.Syntax, convertedTestExpression)); result = GetCaptureReference(resultCaptureId, operation); UnconditionalBranch(afterCoalesce); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(whenNull); VisitAndCapture(operation.WhenNull, resultCaptureId); LeaveRegionsUpTo(resultCaptureRegion); } AppendNewBlock(afterCoalesce); return result; } public override IOperation? VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, int? captureIdForResult) { SpillEvalStack(); // If we're in a statement context, we elide the capture of the result of the assignment, as it will // just be wrapped in an expression statement that isn't used anywhere and isn't observed by anything. Debug.Assert(operation.Parent != null); bool isStatement = _currentStatement == operation || operation.Parent.Kind == OperationKind.ExpressionStatement; Debug.Assert(captureIdForResult == null || !isStatement); RegionBuilder resultCaptureRegion = CurrentRegionRequired; EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.Target)); SpillEvalStack(); IOperation locationCapture = PopOperand(); // Capture the value, as it will only be evaluated once. The location will be used separately later for // the null case EvalStackFrame valueFrame = PushStackFrame(); SpillEvalStack(); Debug.Assert(valueFrame.RegionBuilderOpt != null); int valueCaptureId = GetNextCaptureId(valueFrame.RegionBuilderOpt); AddStatement(new FlowCaptureOperation(valueCaptureId, locationCapture.Syntax, locationCapture)); IOperation valueCapture = GetCaptureReference(valueCaptureId, locationCapture); var whenNull = new BasicBlockBuilder(BasicBlockKind.Block); var afterCoalesce = new BasicBlockBuilder(BasicBlockKind.Block); int resultCaptureId = isStatement ? -1 : captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); if (operation.Target?.Type?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T && ((INamedTypeSymbol)operation.Target.Type!).TypeArguments[0].Equals(operation.Type)) { nullableValueTypeReturn(); } else { standardReturn(); } PopStackFrame(frame); LeaveRegionsUpTo(resultCaptureRegion); AppendNewBlock(afterCoalesce); return isStatement ? null : GetCaptureReference(resultCaptureId, operation); void nullableValueTypeReturn() { // We'll transform this into one of two possibilities, depending on whether we're using // this as an expression or a statement. // // Expression Form: // intermediate1 = valueCapture.GetValueOrDefault(); // branch if false to whenNull: valueCapture.HasValue() // result = intermediate // branch to after // // whenNull: // intermediate2 = rightValue // result = intermediate2 // locationCapture = Convert(intermediate2) // // after: // result // // Statement Form // branch if false to whenNull: valueCapture.HasValue() // branch to after // // whenNull: // locationCapture = Convert(rightValue) // // after: int intermediateResult = -1; EvalStackFrame? intermediateFrame = null; if (!isStatement) { intermediateFrame = PushStackFrame(); SpillEvalStack(); Debug.Assert(intermediateFrame.RegionBuilderOpt != null); intermediateResult = GetNextCaptureId(intermediateFrame.RegionBuilderOpt); AddStatement( new FlowCaptureOperation(intermediateResult, operation.Target.Syntax, CallNullableMember(valueCapture, SpecialMember.System_Nullable_T_GetValueOrDefault))); } ConditionalBranch( CallNullableMember(OperationCloner.CloneOperation(valueCapture), SpecialMember.System_Nullable_T_get_HasValue), jumpIfTrue: false, whenNull); if (!isStatement) { Debug.Assert(intermediateFrame != null); _currentBasicBlock = null; AddStatement( new FlowCaptureOperation(resultCaptureId, operation.Syntax, GetCaptureReference(intermediateResult, operation.Target))); PopStackFrame(intermediateFrame); } PopStackFrame(valueFrame); UnconditionalBranch(afterCoalesce); AppendNewBlock(whenNull); EvalStackFrame whenNullFrame = PushStackFrame(); SpillEvalStack(); IOperation whenNullValue = VisitRequired(operation.Value); if (!isStatement) { Debug.Assert(whenNullFrame.RegionBuilderOpt != null); int intermediateValueCaptureId = GetNextCaptureId(whenNullFrame.RegionBuilderOpt); AddStatement(new FlowCaptureOperation(intermediateValueCaptureId, whenNullValue.Syntax, whenNullValue)); whenNullValue = GetCaptureReference(intermediateValueCaptureId, whenNullValue); AddStatement( new FlowCaptureOperation( resultCaptureId, operation.Syntax, GetCaptureReference(intermediateValueCaptureId, whenNullValue))); } AddStatement( new SimpleAssignmentOperation( isRef: false, target: OperationCloner.CloneOperation(locationCapture), value: CreateConversion(whenNullValue, operation.Target.Type), semanticModel: null, syntax: operation.Syntax, type: operation.Target.Type, constantValue: operation.GetConstantValue(), isImplicit: true)); PopStackFrameAndLeaveRegion(whenNullFrame); } void standardReturn() { ConditionalBranch(MakeIsNullOperation(valueCapture), jumpIfTrue: true, whenNull); if (!isStatement) { _currentBasicBlock = null; AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Syntax, OperationCloner.CloneOperation(valueCapture))); } PopStackFrameAndLeaveRegion(valueFrame); UnconditionalBranch(afterCoalesce); AppendNewBlock(whenNull); // The return of Visit(operation.WhenNull) can be a flow capture that wasn't used in the non-null branch. We want to create a // region around it to ensure that the scope of the flow capture is as narrow as possible. If there was no flow capture, region // packing will take care of removing the empty region. EvalStackFrame whenNullFrame = PushStackFrame(); IOperation whenNullValue = VisitRequired(operation.Value); IOperation whenNullAssignment = new SimpleAssignmentOperation(isRef: false, OperationCloner.CloneOperation(locationCapture), whenNullValue, semanticModel: null, operation.Syntax, operation.Type, constantValue: operation.GetConstantValue(), isImplicit: true); if (isStatement) { AddStatement(whenNullAssignment); } else { AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Syntax, whenNullAssignment)); } PopStackFrameAndLeaveRegion(whenNullFrame); } } private static BasicBlockBuilder.Branch RegularBranch(BasicBlockBuilder destination) { return new BasicBlockBuilder.Branch() { Destination = destination, Kind = ControlFlowBranchSemantics.Regular }; } private static IOperation MakeInvalidOperation(ITypeSymbol? type, IOperation child) { return new InvalidOperation(ImmutableArray.Create<IOperation>(child), semanticModel: null, child.Syntax, type, constantValue: null, isImplicit: true); } private static IOperation MakeInvalidOperation(SyntaxNode syntax, ITypeSymbol? type, IOperation child1, IOperation child2) { return MakeInvalidOperation(syntax, type, ImmutableArray.Create<IOperation>(child1, child2)); } private static IOperation MakeInvalidOperation(SyntaxNode syntax, ITypeSymbol? type, ImmutableArray<IOperation> children) { return new InvalidOperation(children, semanticModel: null, syntax, type, constantValue: null, isImplicit: true); } private IsNullOperation MakeIsNullOperation(IOperation operand) { return MakeIsNullOperation(operand, _compilation.GetSpecialType(SpecialType.System_Boolean)); } private static IsNullOperation MakeIsNullOperation(IOperation operand, ITypeSymbol booleanType) { Debug.Assert(ITypeSymbolHelpers.IsBooleanType(booleanType)); ConstantValue? constantValue = operand.GetConstantValue() is { IsNull: var isNull } ? ConstantValue.Create(isNull) : null; return new IsNullOperation(operand.Syntax, operand, booleanType, constantValue); } private IOperation? TryCallNullableMember(IOperation value, SpecialMember nullableMember) { Debug.Assert(nullableMember == SpecialMember.System_Nullable_T_GetValueOrDefault || nullableMember == SpecialMember.System_Nullable_T_get_HasValue || nullableMember == SpecialMember.System_Nullable_T_get_Value || nullableMember == SpecialMember.System_Nullable_T__op_Explicit_ToT || nullableMember == SpecialMember.System_Nullable_T__op_Implicit_FromT); ITypeSymbol? valueType = value.Type; Debug.Assert(ITypeSymbolHelpers.IsNullableType(valueType)); var method = (IMethodSymbol?)_compilation.CommonGetSpecialTypeMember(nullableMember)?.GetISymbol(); if (method != null) { foreach (ISymbol candidate in valueType.GetMembers(method.Name)) { if (candidate.OriginalDefinition.Equals(method)) { method = (IMethodSymbol)candidate; return new InvocationOperation(method, value, isVirtual: false, ImmutableArray<IArgumentOperation>.Empty, semanticModel: null, value.Syntax, method.ReturnType, isImplicit: true); } } } return null; } private IOperation CallNullableMember(IOperation value, SpecialMember nullableMember) { Debug.Assert(ITypeSymbolHelpers.IsNullableType(value.Type)); return TryCallNullableMember(value, nullableMember) ?? MakeInvalidOperation(ITypeSymbolHelpers.GetNullableUnderlyingType(value.Type), value); } public override IOperation? VisitConditionalAccess(IConditionalAccessOperation operation, int? captureIdForResult) { SpillEvalStack(); RegionBuilder resultCaptureRegion = CurrentRegionRequired; // Avoid creation of default values and FlowCapture for conditional access on a statement level. bool isOnStatementLevel = _currentStatement == operation || (_currentStatement == operation.Parent && _currentStatement?.Kind == OperationKind.ExpressionStatement); EvalStackFrame? expressionFrame = null; var operations = ArrayBuilder<IOperation>.GetInstance(); if (!isOnStatementLevel) { expressionFrame = PushStackFrame(); } IConditionalAccessOperation currentConditionalAccess = operation; IOperation testExpression; var whenNull = new BasicBlockBuilder(BasicBlockKind.Block); var previousTracker = _currentConditionalAccessTracker; _currentConditionalAccessTracker = new ConditionalAccessOperationTracker(operations, whenNull); while (true) { testExpression = currentConditionalAccess.Operation; if (!isConditionalAccessInstancePresentInChildren(currentConditionalAccess.WhenNotNull)) { // https://github.com/dotnet/roslyn/issues/27564: It looks like there is a bug in IOperation tree around XmlMemberAccessExpressionSyntax, // a None operation is created and all children are dropped. // See Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests.ExpressionCompilerTests.ConditionalAccessExpressionType // Because of this, the recursion to visit the child operations will never occur if we visit the WhenNull of the current // conditional access, so we need to manually visit the Operation of the conditional access now. _ = VisitConditionalAccessTestExpression(testExpression); break; } operations.Push(testExpression); if (currentConditionalAccess.WhenNotNull is not IConditionalAccessOperation nested) { break; } currentConditionalAccess = nested; } if (isOnStatementLevel) { Debug.Assert(captureIdForResult == null); IOperation result = VisitRequired(currentConditionalAccess.WhenNotNull); resetConditionalAccessTracker(); if (_currentStatement != operation) { Debug.Assert(_currentStatement is not null); var expressionStatement = (IExpressionStatementOperation)_currentStatement; result = new ExpressionStatementOperation(result, semanticModel: null, expressionStatement.Syntax, IsImplicit(expressionStatement)); } AddStatement(result); AppendNewBlock(whenNull); return null; } else { Debug.Assert(expressionFrame != null); int resultCaptureId = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); if (ITypeSymbolHelpers.IsNullableType(operation.Type) && !ITypeSymbolHelpers.IsNullableType(currentConditionalAccess.WhenNotNull.Type)) { IOperation access = VisitRequired(currentConditionalAccess.WhenNotNull); AddStatement(new FlowCaptureOperation(resultCaptureId, currentConditionalAccess.WhenNotNull.Syntax, MakeNullable(access, operation.Type))); } else { CaptureResultIfNotAlready(currentConditionalAccess.WhenNotNull.Syntax, resultCaptureId, VisitRequired(currentConditionalAccess.WhenNotNull, resultCaptureId)); } PopStackFrame(expressionFrame); LeaveRegionsUpTo(resultCaptureRegion); resetConditionalAccessTracker(); var afterAccess = new BasicBlockBuilder(BasicBlockKind.Block); UnconditionalBranch(afterAccess); AppendNewBlock(whenNull); SyntaxNode defaultValueSyntax = (operation.Operation == testExpression ? testExpression : operation).Syntax; Debug.Assert(operation.Type is not null); AddStatement(new FlowCaptureOperation(resultCaptureId, defaultValueSyntax, new DefaultValueOperation(semanticModel: null, defaultValueSyntax, operation.Type, (operation.Type.IsReferenceType && !ITypeSymbolHelpers.IsNullableType(operation.Type)) ? ConstantValue.Null : null, isImplicit: true))); AppendNewBlock(afterAccess); return GetCaptureReference(resultCaptureId, operation); } void resetConditionalAccessTracker() { Debug.Assert(!_currentConditionalAccessTracker.IsDefault); Debug.Assert(_currentConditionalAccessTracker.Operations.Count == 0); _currentConditionalAccessTracker.Free(); _currentConditionalAccessTracker = previousTracker; } static bool isConditionalAccessInstancePresentInChildren(IOperation operation) { if (operation is InvalidOperation invalidOperation) { return checkInvalidChildren(invalidOperation); } // The conditional access should always be first leaf node in the subtree when performing a depth-first search. Visit the first child recursively // until we either reach the bottom, or find the conditional access. Operation currentOperation = (Operation)operation; while (currentOperation.ChildOperations.GetEnumerator() is var enumerator && enumerator.MoveNext()) { if (enumerator.Current is IConditionalAccessInstanceOperation) { return true; } else if (enumerator.Current is InvalidOperation invalidChild) { return checkInvalidChildren(invalidChild); } currentOperation = (Operation)enumerator.Current; } return false; } static bool checkInvalidChildren(InvalidOperation operation) { // Invalid operations can have children ordering that doesn't put the conditional access instance first. For these cases, // use a recursive check foreach (var child in operation.ChildOperations) { if (child is IConditionalAccessInstanceOperation || isConditionalAccessInstancePresentInChildren(child)) { return true; } } return false; } } public override IOperation VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, int? captureIdForResult) { Debug.Assert(!_currentConditionalAccessTracker.IsDefault && _currentConditionalAccessTracker.Operations.Count > 0); IOperation testExpression = _currentConditionalAccessTracker.Operations.Pop(); return VisitConditionalAccessTestExpression(testExpression); } private IOperation VisitConditionalAccessTestExpression(IOperation testExpression) { Debug.Assert(!_currentConditionalAccessTracker.IsDefault); SyntaxNode testExpressionSyntax = testExpression.Syntax; ITypeSymbol? testExpressionType = testExpression.Type; var frame = PushStackFrame(); PushOperand(VisitRequired(testExpression)); SpillEvalStack(); IOperation spilledTestExpression = PopOperand(); PopStackFrame(frame); ConditionalBranch(MakeIsNullOperation(spilledTestExpression), jumpIfTrue: true, _currentConditionalAccessTracker.WhenNull); _currentBasicBlock = null; IOperation receiver = OperationCloner.CloneOperation(spilledTestExpression); if (ITypeSymbolHelpers.IsNullableType(testExpressionType)) { receiver = CallNullableMember(receiver, SpecialMember.System_Nullable_T_GetValueOrDefault); } return receiver; } public override IOperation? VisitExpressionStatement(IExpressionStatementOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); IOperation? underlying = Visit(operation.Operation); if (underlying == null) { Debug.Assert(operation.Operation.Kind == OperationKind.ConditionalAccess || operation.Operation.Kind == OperationKind.CoalesceAssignment); return FinishVisitingStatement(operation); } else if (operation.Operation.Kind == OperationKind.Throw) { return FinishVisitingStatement(operation); } return FinishVisitingStatement(operation, new ExpressionStatementOperation(underlying, semanticModel: null, operation.Syntax, IsImplicit(operation))); } public override IOperation? VisitWhileLoop(IWhileLoopOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); var locals = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals); var @continue = GetLabeledOrNewBlock(operation.ContinueLabel); var @break = GetLabeledOrNewBlock(operation.ExitLabel); if (operation.ConditionIsTop) { // while (condition) // body; // // becomes // // continue: // { // GotoIfFalse condition break; // body // goto continue; // } // break: AppendNewBlock(@continue); EnterRegion(locals); Debug.Assert(operation.Condition is not null); VisitConditionalBranch(operation.Condition, ref @break, jumpIfTrue: operation.ConditionIsUntil); VisitStatement(operation.Body); UnconditionalBranch(@continue); } else { // do // body // while (condition); // // becomes // // start: // { // body // continue: // GotoIfTrue condition start; // } // break: var start = new BasicBlockBuilder(BasicBlockKind.Block); AppendNewBlock(start); EnterRegion(locals); VisitStatement(operation.Body); AppendNewBlock(@continue); if (operation.Condition != null) { VisitConditionalBranch(operation.Condition, ref start, jumpIfTrue: !operation.ConditionIsUntil); } else { UnconditionalBranch(start); } } Debug.Assert(_currentRegion == locals); LeaveRegion(); AppendNewBlock(@break); return FinishVisitingStatement(operation); } public override IOperation? VisitTry(ITryOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); var afterTryCatchFinally = GetLabeledOrNewBlock(operation.ExitLabel); if (operation.Catches.IsEmpty && operation.Finally == null) { // Malformed node without handlers // It looks like we can get here for VB only. Let's recover the same way C# does, i.e. // pretend that there is no Try. Just visit body. VisitStatement(operation.Body); AppendNewBlock(afterTryCatchFinally); return FinishVisitingStatement(operation); } RegionBuilder? tryAndFinallyRegion = null; bool haveFinally = operation.Finally != null; if (haveFinally) { tryAndFinallyRegion = new RegionBuilder(ControlFlowRegionKind.TryAndFinally); EnterRegion(tryAndFinallyRegion); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); } bool haveCatches = !operation.Catches.IsEmpty; if (haveCatches) { EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndCatch)); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); } Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.Try); VisitStatement(operation.Body); UnconditionalBranch(afterTryCatchFinally); if (haveCatches) { LeaveRegion(); foreach (ICatchClauseOperation catchClause in operation.Catches) { RegionBuilder? filterAndHandlerRegion = null; IOperation? exceptionDeclarationOrExpression = catchClause.ExceptionDeclarationOrExpression; IOperation? filter = catchClause.Filter; bool haveFilter = filter != null; var catchBlock = new BasicBlockBuilder(BasicBlockKind.Block); if (haveFilter) { filterAndHandlerRegion = new RegionBuilder(ControlFlowRegionKind.FilterAndHandler, catchClause.ExceptionType, catchClause.Locals); EnterRegion(filterAndHandlerRegion); var filterRegion = new RegionBuilder(ControlFlowRegionKind.Filter, catchClause.ExceptionType); EnterRegion(filterRegion); AddExceptionStore(catchClause.ExceptionType, exceptionDeclarationOrExpression); VisitConditionalBranch(filter!, ref catchBlock, jumpIfTrue: true); var continueDispatchBlock = new BasicBlockBuilder(BasicBlockKind.Block); AppendNewBlock(continueDispatchBlock); continueDispatchBlock.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; LeaveRegion(); Debug.Assert(!filterRegion.IsEmpty); Debug.Assert(filterRegion.LastBlock.FallThrough.Destination == null); Debug.Assert(!filterRegion.FirstBlock.HasPredecessors); } var handlerRegion = new RegionBuilder(ControlFlowRegionKind.Catch, catchClause.ExceptionType, haveFilter ? default : catchClause.Locals); EnterRegion(handlerRegion); AppendNewBlock(catchBlock, linkToPrevious: false); if (!haveFilter) { AddExceptionStore(catchClause.ExceptionType, exceptionDeclarationOrExpression); } VisitStatement(catchClause.Handler); UnconditionalBranch(afterTryCatchFinally); LeaveRegion(); Debug.Assert(!handlerRegion.IsEmpty); if (haveFilter) { Debug.Assert(CurrentRegionRequired == filterAndHandlerRegion); LeaveRegion(); #if DEBUG Debug.Assert(filterAndHandlerRegion.Regions![0].LastBlock!.FallThrough.Destination == null); if (handlerRegion.FirstBlock.HasPredecessors) { var predecessors = ArrayBuilder<BasicBlockBuilder>.GetInstance(); handlerRegion.FirstBlock.GetPredecessors(predecessors); Debug.Assert(predecessors.All(p => filterAndHandlerRegion.Regions[0].FirstBlock!.Ordinal <= p.Ordinal && filterAndHandlerRegion.Regions[0].LastBlock!.Ordinal >= p.Ordinal)); predecessors.Free(); } #endif } else { Debug.Assert(!handlerRegion.FirstBlock.HasPredecessors); } } Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.TryAndCatch); LeaveRegion(); } if (haveFinally) { Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.Try); LeaveRegion(); var finallyRegion = new RegionBuilder(ControlFlowRegionKind.Finally); EnterRegion(finallyRegion); AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); VisitStatement(operation.Finally); var continueDispatchBlock = new BasicBlockBuilder(BasicBlockKind.Block); AppendNewBlock(continueDispatchBlock); continueDispatchBlock.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; LeaveRegion(); Debug.Assert(_currentRegion == tryAndFinallyRegion); LeaveRegion(); Debug.Assert(!finallyRegion.IsEmpty); Debug.Assert(finallyRegion.LastBlock.FallThrough.Destination == null); Debug.Assert(!finallyRegion.FirstBlock.HasPredecessors); } AppendNewBlock(afterTryCatchFinally, linkToPrevious: false); Debug.Assert(tryAndFinallyRegion?.Regions![1].LastBlock!.FallThrough.Destination == null); return FinishVisitingStatement(operation); } private void AddExceptionStore(ITypeSymbol exceptionType, IOperation? exceptionDeclarationOrExpression) { if (exceptionDeclarationOrExpression != null) { IOperation exceptionTarget; SyntaxNode syntax = exceptionDeclarationOrExpression.Syntax; if (exceptionDeclarationOrExpression.Kind == OperationKind.VariableDeclarator) { ILocalSymbol local = ((IVariableDeclaratorOperation)exceptionDeclarationOrExpression).Symbol; exceptionTarget = new LocalReferenceOperation(local, isDeclaration: true, semanticModel: null, syntax, local.Type, constantValue: null, isImplicit: true); } else { exceptionTarget = VisitRequired(exceptionDeclarationOrExpression); } if (exceptionTarget != null) { AddStatement(new SimpleAssignmentOperation( isRef: false, target: exceptionTarget, value: new CaughtExceptionOperation(syntax, exceptionType), semanticModel: null, syntax: syntax, type: null, constantValue: null, isImplicit: true)); } } } public override IOperation VisitCatchClause(ICatchClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation? VisitReturn(IReturnOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); IOperation? returnedValue = Visit(operation.ReturnedValue); switch (operation.Kind) { case OperationKind.YieldReturn: AddStatement(new ReturnOperation(returnedValue, OperationKind.YieldReturn, semanticModel: null, operation.Syntax, IsImplicit(operation))); break; case OperationKind.YieldBreak: case OperationKind.Return: BasicBlockBuilder current = CurrentBasicBlock; LinkBlocks(CurrentBasicBlock, _exit, returnedValue is null ? ControlFlowBranchSemantics.Regular : ControlFlowBranchSemantics.Return); Debug.Assert(current.BranchValue == null); Debug.Assert(!current.HasCondition); current.BranchValue = Operation.SetParentOperation(returnedValue, null); _currentBasicBlock = null; break; default: throw ExceptionUtilities.UnexpectedValue(operation.Kind); } return FinishVisitingStatement(operation); } public override IOperation? VisitLabeled(ILabeledOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); VisitLabel(operation.Label); VisitStatement(operation.Operation); return FinishVisitingStatement(operation); } public void VisitLabel(ILabelSymbol operation) { BasicBlockBuilder labeled = GetLabeledOrNewBlock(operation); if (labeled.Ordinal != -1) { // Must be a duplicate label. Recover by simply allocating a new block. labeled = new BasicBlockBuilder(BasicBlockKind.Block); } AppendNewBlock(labeled); } private BasicBlockBuilder GetLabeledOrNewBlock(ILabelSymbol? labelOpt) { if (labelOpt == null) { return new BasicBlockBuilder(BasicBlockKind.Block); } BasicBlockBuilder? labeledBlock; if (_labeledBlocks == null) { _labeledBlocks = PooledDictionary<ILabelSymbol, BasicBlockBuilder>.GetInstance(); } else if (_labeledBlocks.TryGetValue(labelOpt, out labeledBlock)) { return labeledBlock; } labeledBlock = new BasicBlockBuilder(BasicBlockKind.Block); _labeledBlocks.Add(labelOpt, labeledBlock); return labeledBlock; } public override IOperation? VisitBranch(IBranchOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); UnconditionalBranch(GetLabeledOrNewBlock(operation.Target)); return FinishVisitingStatement(operation); } public override IOperation? VisitEmpty(IEmptyOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); return FinishVisitingStatement(operation); } public override IOperation? VisitThrow(IThrowOperation operation, int? captureIdForResult) { bool isStatement = (_currentStatement == operation); if (!isStatement) { SpillEvalStack(); } EvalStackFrame frame = PushStackFrame(); LinkThrowStatement(Visit(operation.Exception)); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block), linkToPrevious: false); if (isStatement) { return null; } else { return new NoneOperation(children: ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Syntax, constantValue: null, isImplicit: true, type: null); } } private void LinkThrowStatement(IOperation? exception) { BasicBlockBuilder current = CurrentBasicBlock; Debug.Assert(current.BranchValue == null); Debug.Assert(!current.HasCondition); Debug.Assert(current.FallThrough.Destination == null); Debug.Assert(current.FallThrough.Kind == ControlFlowBranchSemantics.None); current.BranchValue = Operation.SetParentOperation(exception, null); current.FallThrough.Kind = exception == null ? ControlFlowBranchSemantics.Rethrow : ControlFlowBranchSemantics.Throw; } public override IOperation? VisitUsing(IUsingOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); DisposeOperationInfo disposeInfo = ((UsingOperation)operation).DisposeInfo; HandleUsingOperationParts(operation.Resources, operation.Body, disposeInfo.DisposeMethod, disposeInfo.DisposeArguments, operation.Locals, operation.IsAsynchronous); return FinishVisitingStatement(operation); } private void HandleUsingOperationParts(IOperation resources, IOperation body, IMethodSymbol? disposeMethod, ImmutableArray<IArgumentOperation> disposeArguments, ImmutableArray<ILocalSymbol> locals, bool isAsynchronous) { var usingRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: locals); EnterRegion(usingRegion); ITypeSymbol iDisposable = isAsynchronous ? _compilation.CommonGetWellKnownType(WellKnownType.System_IAsyncDisposable).GetITypeSymbol() : _compilation.GetSpecialType(SpecialType.System_IDisposable); if (resources is IVariableDeclarationGroupOperation declarationGroup) { var resourceQueue = ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>.GetInstance(declarationGroup.Declarations.Length); foreach (IVariableDeclarationOperation declaration in declarationGroup.Declarations) { foreach (IVariableDeclaratorOperation declarator in declaration.Declarators) { resourceQueue.Add((declaration, declarator)); } } resourceQueue.ReverseContents(); processQueue(resourceQueue); } else { Debug.Assert(resources.Kind != OperationKind.VariableDeclaration); Debug.Assert(resources.Kind != OperationKind.VariableDeclarator); EvalStackFrame frame = PushStackFrame(); IOperation resource = VisitRequired(resources); if (shouldConvertToIDisposableBeforeTry(resource)) { resource = ConvertToIDisposable(resource, iDisposable); } PushOperand(resource); SpillEvalStack(); resource = PopOperand(); PopStackFrame(frame); processResource(resource, resourceQueueOpt: null); LeaveRegionIfAny(frame); } Debug.Assert(_currentRegion == usingRegion); LeaveRegion(); void processQueue(ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>? resourceQueueOpt) { if (resourceQueueOpt == null || resourceQueueOpt.Count == 0) { VisitStatement(body); } else { (IVariableDeclarationOperation declaration, IVariableDeclaratorOperation declarator) = resourceQueueOpt.Pop(); HandleVariableDeclarator(declaration, declarator); ILocalSymbol localSymbol = declarator.Symbol; processResource(new LocalReferenceOperation(localSymbol, isDeclaration: false, semanticModel: null, declarator.Syntax, localSymbol.Type, constantValue: null, isImplicit: true), resourceQueueOpt); } } bool shouldConvertToIDisposableBeforeTry(IOperation resource) { return resource.Type == null || resource.Type.Kind == SymbolKind.DynamicType; } void processResource(IOperation resource, ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>? resourceQueueOpt) { // When ResourceType is a non-nullable value type that implements IDisposable, the expansion is: // // { // ResourceType resource = expr; // try { statement; } // finally { ((IDisposable)resource).Dispose(); } // } // // Otherwise, when ResourceType is a non-nullable value type that implements // disposal via pattern, the expansion is: // // { // try { statement; } // finally { resource.Dispose(); } // } // Otherwise, when Resource type is a nullable value type or // a reference type other than dynamic that implements IDisposable, the expansion is: // // { // ResourceType resource = expr; // try { statement; } // finally { if (resource != null) ((IDisposable)resource).Dispose(); } // } // // Otherwise, when Resource type is a reference type other than dynamic // that implements disposal via pattern, the expansion is: // // { // ResourceType resource = expr; // try { statement; } // finally { if (resource != null) resource.Dispose(); } // } // // Otherwise, when ResourceType is dynamic, the expansion is: // { // dynamic resource = expr; // IDisposable d = (IDisposable)resource; // try { statement; } // finally { if (d != null) d.Dispose(); } // } RegionBuilder? resourceRegion = null; if (shouldConvertToIDisposableBeforeTry(resource)) { resourceRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); EnterRegion(resourceRegion); resource = ConvertToIDisposable(resource, iDisposable); int captureId = GetNextCaptureId(resourceRegion); AddStatement(new FlowCaptureOperation(captureId, resource.Syntax, resource)); resource = GetCaptureReference(captureId, resource); } var afterTryFinally = new BasicBlockBuilder(BasicBlockKind.Block); EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); processQueue(resourceQueueOpt); Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.Try); UnconditionalBranch(afterTryFinally); LeaveRegion(); AddDisposingFinally(resource, requiresRuntimeConversion: false, iDisposable, disposeMethod, disposeArguments, isAsynchronous); Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.TryAndFinally); LeaveRegion(); if (resourceRegion != null) { Debug.Assert(_currentRegion == resourceRegion); LeaveRegion(); } AppendNewBlock(afterTryFinally, linkToPrevious: false); } } private void AddDisposingFinally(IOperation resource, bool requiresRuntimeConversion, ITypeSymbol iDisposable, IMethodSymbol? disposeMethod, ImmutableArray<IArgumentOperation> disposeArguments, bool isAsynchronous) { Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.TryAndFinally); var endOfFinally = new BasicBlockBuilder(BasicBlockKind.Block); endOfFinally.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; var finallyRegion = new RegionBuilder(ControlFlowRegionKind.Finally); EnterRegion(finallyRegion); AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); if (requiresRuntimeConversion) { Debug.Assert(!isNotNullableValueType(resource.Type)); resource = ConvertToIDisposable(resource, iDisposable, isTryCast: true); int captureId = GetNextCaptureId(finallyRegion); AddStatement(new FlowCaptureOperation(captureId, resource.Syntax, resource)); resource = GetCaptureReference(captureId, resource); } if (requiresRuntimeConversion || !isNotNullableValueType(resource.Type)) { IOperation condition = MakeIsNullOperation(OperationCloner.CloneOperation(resource)); ConditionalBranch(condition, jumpIfTrue: true, endOfFinally); _currentBasicBlock = null; } if (!iDisposable.Equals(resource.Type) && disposeMethod is null) { resource = ConvertToIDisposable(resource, iDisposable); } EvalStackFrame disposeFrame = PushStackFrame(); AddStatement(tryDispose(resource) ?? MakeInvalidOperation(type: null, resource)); PopStackFrameAndLeaveRegion(disposeFrame); AppendNewBlock(endOfFinally); Debug.Assert(_currentRegion == finallyRegion); LeaveRegion(); return; IOperation? tryDispose(IOperation value) { Debug.Assert((disposeMethod is object && !disposeArguments.IsDefault) || (value.Type!.Equals(iDisposable) && disposeArguments.IsDefaultOrEmpty)); var method = disposeMethod ?? (isAsynchronous ? (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_IAsyncDisposable__DisposeAsync)?.GetISymbol() : (IMethodSymbol?)_compilation.CommonGetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose)?.GetISymbol()); if (method != null) { var args = disposeMethod is object ? VisitArguments(disposeArguments) : ImmutableArray<IArgumentOperation>.Empty; var invocation = new InvocationOperation(method, value, isVirtual: disposeMethod?.IsVirtual ?? true, args, semanticModel: null, value.Syntax, method.ReturnType, isImplicit: true); if (isAsynchronous) { return new AwaitOperation(invocation, semanticModel: null, value.Syntax, _compilation.GetSpecialType(SpecialType.System_Void), isImplicit: true); } return invocation; } return null; } bool isNotNullableValueType([NotNullWhen(true)] ITypeSymbol? type) { return type?.IsValueType == true && !ITypeSymbolHelpers.IsNullableType(type); } } private IOperation ConvertToIDisposable(IOperation operand, ITypeSymbol iDisposable, bool isTryCast = false) { Debug.Assert(iDisposable.SpecialType == SpecialType.System_IDisposable || iDisposable.Equals(_compilation.CommonGetWellKnownType(WellKnownType.System_IAsyncDisposable)?.GetITypeSymbol())); return new ConversionOperation(operand, _compilation.ClassifyConvertibleConversion(operand, iDisposable, out var constantValue), isTryCast, isChecked: false, semanticModel: null, operand.Syntax, iDisposable, constantValue, isImplicit: true); } public override IOperation? VisitLock(ILockOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); ITypeSymbol objectType = _compilation.GetSpecialType(SpecialType.System_Object); // If Monitor.Enter(object, ref bool) is available: // // L $lock = `LockedValue`; // bool $lockTaken = false; // try // { // Monitor.Enter($lock, ref $lockTaken); // `body` // } // finally // { // if ($lockTaken) Monitor.Exit($lock); // } // If Monitor.Enter(object, ref bool) is not available: // // L $lock = `LockedValue`; // Monitor.Enter($lock); // NB: before try-finally so we don't Exit if an exception prevents us from acquiring the lock. // try // { // `body` // } // finally // { // Monitor.Exit($lock); // } // If original type of the LockedValue object is System.Object, VB calls runtime helper (if one is available) // Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType to ensure no value type is // used. // For simplicity, we will not synthesize this call because its presence is unlikely to affect graph analysis. var lockStatement = (LockOperation)operation; var lockRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: lockStatement.LockTakenSymbol != null ? ImmutableArray.Create(lockStatement.LockTakenSymbol) : ImmutableArray<ILocalSymbol>.Empty); EnterRegion(lockRegion); EvalStackFrame frame = PushStackFrame(); IOperation lockedValue = VisitRequired(operation.LockedValue); if (!objectType.Equals(lockedValue.Type)) { lockedValue = CreateConversion(lockedValue, objectType); } PushOperand(lockedValue); SpillEvalStack(); lockedValue = PopOperand(); PopStackFrame(frame); var enterMethod = (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2)?.GetISymbol(); bool legacyMode = (enterMethod == null); if (legacyMode) { Debug.Assert(lockStatement.LockTakenSymbol == null); enterMethod = (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter)?.GetISymbol(); // Monitor.Enter($lock); if (enterMethod == null) { AddStatement(MakeInvalidOperation(type: null, lockedValue)); } else { AddStatement(new InvocationOperation(enterMethod, instance: null, isVirtual: false, ImmutableArray.Create<IArgumentOperation>( new ArgumentOperation(ArgumentKind.Explicit, enterMethod.Parameters[0], lockedValue, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, lockedValue.Syntax, isImplicit: true)), semanticModel: null, lockedValue.Syntax, enterMethod.ReturnType, isImplicit: true)); } } var afterTryFinally = new BasicBlockBuilder(BasicBlockKind.Block); EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); IOperation? lockTaken = null; if (!legacyMode) { // Monitor.Enter($lock, ref $lockTaken); Debug.Assert(lockStatement.LockTakenSymbol is not null); Debug.Assert(enterMethod is not null); lockTaken = new LocalReferenceOperation(lockStatement.LockTakenSymbol, isDeclaration: true, semanticModel: null, lockedValue.Syntax, lockStatement.LockTakenSymbol.Type, constantValue: null, isImplicit: true); AddStatement(new InvocationOperation(enterMethod, instance: null, isVirtual: false, ImmutableArray.Create<IArgumentOperation>( new ArgumentOperation(ArgumentKind.Explicit, enterMethod.Parameters[0], lockedValue, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, lockedValue.Syntax, isImplicit: true), new ArgumentOperation(ArgumentKind.Explicit, enterMethod.Parameters[1], lockTaken, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, lockedValue.Syntax, isImplicit: true)), semanticModel: null, lockedValue.Syntax, enterMethod.ReturnType, isImplicit: true)); } VisitStatement(operation.Body); Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.Try); UnconditionalBranch(afterTryFinally); LeaveRegion(); var endOfFinally = new BasicBlockBuilder(BasicBlockKind.Block); endOfFinally.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; EnterRegion(new RegionBuilder(ControlFlowRegionKind.Finally)); AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); if (!legacyMode) { // if ($lockTaken) Debug.Assert(lockStatement.LockTakenSymbol is not null); IOperation condition = new LocalReferenceOperation(lockStatement.LockTakenSymbol, isDeclaration: false, semanticModel: null, lockedValue.Syntax, lockStatement.LockTakenSymbol.Type, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, endOfFinally); _currentBasicBlock = null; } // Monitor.Exit($lock); var exitMethod = (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Exit)?.GetISymbol(); lockedValue = OperationCloner.CloneOperation(lockedValue); if (exitMethod == null) { AddStatement(MakeInvalidOperation(type: null, lockedValue)); } else { AddStatement(new InvocationOperation(exitMethod, instance: null, isVirtual: false, ImmutableArray.Create<IArgumentOperation>( new ArgumentOperation(ArgumentKind.Explicit, exitMethod.Parameters[0], lockedValue, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, lockedValue.Syntax, isImplicit: true)), semanticModel: null, lockedValue.Syntax, exitMethod.ReturnType, isImplicit: true)); } AppendNewBlock(endOfFinally); LeaveRegion(); Debug.Assert(CurrentRegionRequired.Kind == ControlFlowRegionKind.TryAndFinally); LeaveRegion(); LeaveRegionsUpTo(lockRegion); LeaveRegion(); AppendNewBlock(afterTryFinally, linkToPrevious: false); return FinishVisitingStatement(operation); } public override IOperation? VisitForEachLoop(IForEachLoopOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); var enumeratorCaptureRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); EnterRegion(enumeratorCaptureRegion); ForEachLoopOperationInfo? info = ((ForEachLoopOperation)operation).Info; RegionBuilder? regionForCollection = null; if (!operation.Locals.IsEmpty && operation.LoopControlVariable.Kind == OperationKind.VariableDeclarator) { // VB has rather interesting scoping rules for control variable. // It is in scope in the collection expression. However, it is considered to be // "a different" version of that local. Effectively when the code is emitted, // there are two distinct locals, one is used in the collection expression and the // other is used as a loop control variable. This is done to have proper hoisting // and lifetime in presence of lambdas. // Rather than introducing a separate local symbol, we will simply add another // lifetime region for that local around the collection expression. var declarator = (IVariableDeclaratorOperation)operation.LoopControlVariable; ILocalSymbol local = declarator.Symbol; foreach (IOperation op in operation.Collection.DescendantsAndSelf()) { if (op is ILocalReferenceOperation l && l.Local.Equals(local)) { regionForCollection = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: ImmutableArray.Create(local)); EnterRegion(regionForCollection); break; } } } IOperation enumerator = getEnumerator(); if (regionForCollection != null) { Debug.Assert(regionForCollection == _currentRegion); LeaveRegion(); } if (info?.NeedsDispose == true) { EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); } var @continue = GetLabeledOrNewBlock(operation.ContinueLabel); var @break = GetLabeledOrNewBlock(operation.ExitLabel); AppendNewBlock(@continue); EvalStackFrame frame = PushStackFrame(); ConditionalBranch(getCondition(enumerator), jumpIfTrue: false, @break); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); var localsRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals); EnterRegion(localsRegion); frame = PushStackFrame(); AddStatement(getLoopControlVariableAssignment(applyConversion(info?.CurrentConversion, getCurrent(OperationCloner.CloneOperation(enumerator)), info?.ElementType))); PopStackFrameAndLeaveRegion(frame); VisitStatement(operation.Body); Debug.Assert(localsRegion == _currentRegion); UnconditionalBranch(@continue); LeaveRegion(); AppendNewBlock(@break); if (info?.NeedsDispose == true) { var afterTryFinally = new BasicBlockBuilder(BasicBlockKind.Block); Debug.Assert(_currentRegion.Kind == ControlFlowRegionKind.Try); UnconditionalBranch(afterTryFinally); LeaveRegion(); bool isAsynchronous = info.IsAsynchronous; var iDisposable = isAsynchronous ? _compilation.CommonGetWellKnownType(WellKnownType.System_IAsyncDisposable).GetITypeSymbol() : _compilation.GetSpecialType(SpecialType.System_IDisposable); AddDisposingFinally(OperationCloner.CloneOperation(enumerator), requiresRuntimeConversion: !info.KnownToImplementIDisposable && info.PatternDisposeMethod == null, iDisposable, info.PatternDisposeMethod, info.DisposeArguments, isAsynchronous); Debug.Assert(_currentRegion.Kind == ControlFlowRegionKind.TryAndFinally); LeaveRegion(); AppendNewBlock(afterTryFinally, linkToPrevious: false); } Debug.Assert(_currentRegion == enumeratorCaptureRegion); LeaveRegion(); return FinishVisitingStatement(operation); IOperation applyConversion(IConvertibleConversion? conversionOpt, IOperation operand, ITypeSymbol? targetType) { if (conversionOpt?.ToCommonConversion().IsIdentity == false) { operand = new ConversionOperation(operand, conversionOpt, isTryCast: false, isChecked: false, semanticModel: null, operand.Syntax, targetType, constantValue: null, isImplicit: true); } return operand; } IOperation getEnumerator() { IOperation result; EvalStackFrame getEnumeratorFrame = PushStackFrame(); if (info?.GetEnumeratorMethod != null) { IOperation invocation = makeInvocation(operation.Collection.Syntax, info.GetEnumeratorMethod, info.GetEnumeratorMethod.IsStatic ? null : Visit(operation.Collection), info.GetEnumeratorArguments); int enumeratorCaptureId = GetNextCaptureId(enumeratorCaptureRegion); AddStatement(new FlowCaptureOperation(enumeratorCaptureId, operation.Collection.Syntax, invocation)); result = new FlowCaptureReferenceOperation(enumeratorCaptureId, operation.Collection.Syntax, info.GetEnumeratorMethod.ReturnType, constantValue: null); } else { // This must be an error case AddStatement(MakeInvalidOperation(type: null, VisitRequired(operation.Collection))); result = new InvalidOperation(ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Collection.Syntax, type: null, constantValue: null, isImplicit: true); } PopStackFrameAndLeaveRegion(getEnumeratorFrame); return result; } IOperation getCondition(IOperation enumeratorRef) { if (info?.MoveNextMethod != null) { var moveNext = makeInvocationDroppingInstanceForStaticMethods(info.MoveNextMethod, enumeratorRef, info.MoveNextArguments); if (operation.IsAsynchronous) { return new AwaitOperation(moveNext, semanticModel: null, operation.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), isImplicit: true); } return moveNext; } else { // This must be an error case return MakeInvalidOperation(_compilation.GetSpecialType(SpecialType.System_Boolean), enumeratorRef); } } IOperation getCurrent(IOperation enumeratorRef) { if (info?.CurrentProperty != null) { return new PropertyReferenceOperation(info.CurrentProperty, makeArguments(info.CurrentArguments), info.CurrentProperty.IsStatic ? null : enumeratorRef, semanticModel: null, operation.LoopControlVariable.Syntax, info.CurrentProperty.Type, isImplicit: true); } else { // This must be an error case return MakeInvalidOperation(type: null, enumeratorRef); } } IOperation getLoopControlVariableAssignment(IOperation current) { switch (operation.LoopControlVariable.Kind) { case OperationKind.VariableDeclarator: var declarator = (IVariableDeclaratorOperation)operation.LoopControlVariable; ILocalSymbol local = declarator.Symbol; current = applyConversion(info?.ElementConversion, current, local.Type); return new SimpleAssignmentOperation(isRef: local.RefKind != RefKind.None, new LocalReferenceOperation(local, isDeclaration: true, semanticModel: null, declarator.Syntax, local.Type, constantValue: null, isImplicit: true), current, semanticModel: null, declarator.Syntax, type: null, constantValue: null, isImplicit: true); case OperationKind.Tuple: case OperationKind.DeclarationExpression: Debug.Assert(info?.ElementConversion?.ToCommonConversion().IsIdentity != false); return new DeconstructionAssignmentOperation(VisitPreservingTupleOperations(operation.LoopControlVariable), current, semanticModel: null, operation.LoopControlVariable.Syntax, operation.LoopControlVariable.Type, isImplicit: true); default: return new SimpleAssignmentOperation(isRef: false, // In C# this is an error case and VB doesn't support ref locals VisitRequired(operation.LoopControlVariable), current, semanticModel: null, operation.LoopControlVariable.Syntax, operation.LoopControlVariable.Type, constantValue: null, isImplicit: true); } } InvocationOperation makeInvocationDroppingInstanceForStaticMethods(IMethodSymbol method, IOperation instance, ImmutableArray<IArgumentOperation> arguments) { return makeInvocation(instance.Syntax, method, method.IsStatic ? null : instance, arguments); } InvocationOperation makeInvocation(SyntaxNode syntax, IMethodSymbol method, IOperation? instanceOpt, ImmutableArray<IArgumentOperation> arguments) { Debug.Assert(method.IsStatic == (instanceOpt == null)); return new InvocationOperation(method, instanceOpt, isVirtual: method.IsVirtual || method.IsAbstract || method.IsOverride, makeArguments(arguments), semanticModel: null, syntax, method.ReturnType, isImplicit: true); } ImmutableArray<IArgumentOperation> makeArguments(ImmutableArray<IArgumentOperation> arguments) { if (arguments != null) { return VisitArguments(arguments); } return ImmutableArray<IArgumentOperation>.Empty; } } public override IOperation? VisitForToLoop(IForToLoopOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; bool isObjectLoop = (loopObject != null); ImmutableArray<ILocalSymbol> locals = operation.Locals; if (isObjectLoop) { locals = locals.Insert(0, loopObject!); } ITypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); BasicBlockBuilder @continue = GetLabeledOrNewBlock(operation.ContinueLabel); BasicBlockBuilder? @break = GetLabeledOrNewBlock(operation.ExitLabel); BasicBlockBuilder checkConditionBlock = new BasicBlockBuilder(BasicBlockKind.Block); BasicBlockBuilder bodyBlock = new BasicBlockBuilder(BasicBlockKind.Block); var loopRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: locals); EnterRegion(loopRegion); // Handle loop initialization int limitValueId = -1; int stepValueId = -1; IFlowCaptureReferenceOperation? positiveFlag = null; ITypeSymbol? stepEnumUnderlyingTypeOrSelf = ITypeSymbolHelpers.GetEnumUnderlyingTypeOrSelf(operation.StepValue.Type); initializeLoop(); // Now check condition AppendNewBlock(checkConditionBlock); checkLoopCondition(); // Handle body AppendNewBlock(bodyBlock); VisitStatement(operation.Body); // Increment AppendNewBlock(@continue); incrementLoopControlVariable(); UnconditionalBranch(checkConditionBlock); LeaveRegion(); AppendNewBlock(@break); return FinishVisitingStatement(operation); IOperation tryCallObjectForLoopControlHelper(SyntaxNode syntax, WellKnownMember helper) { Debug.Assert(isObjectLoop && loopObject is not null); bool isInitialization = (helper == WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj); var loopObjectReference = new LocalReferenceOperation(loopObject, isDeclaration: isInitialization, semanticModel: null, operation.LoopControlVariable.Syntax, loopObject.Type, constantValue: null, isImplicit: true); var method = (IMethodSymbol?)_compilation.CommonGetWellKnownTypeMember(helper)?.GetISymbol(); int parametersCount = WellKnownMembers.GetDescriptor(helper).ParametersCount; if (method is null) { var builder = ArrayBuilder<IOperation>.GetInstance(--parametersCount, fillWithValue: null!); builder[--parametersCount] = loopObjectReference; do { builder[--parametersCount] = PopOperand(); } while (parametersCount != 0); Debug.Assert(builder.All(o => o != null)); return MakeInvalidOperation(operation.LimitValue.Syntax, booleanType, builder.ToImmutableAndFree()); } else { var builder = ArrayBuilder<IArgumentOperation>.GetInstance(parametersCount, fillWithValue: null!); builder[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, method.Parameters[parametersCount], visitLoopControlVariableReference(forceImplicit: true), // Yes we are going to evaluate it again inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, syntax, isImplicit: true); builder[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, method.Parameters[parametersCount], loopObjectReference, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, syntax, isImplicit: true); do { IOperation value = PopOperand(); builder[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, method.Parameters[parametersCount], value, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, isInitialization ? value.Syntax : syntax, isImplicit: true); } while (parametersCount != 0); Debug.Assert(builder.All(op => op is not null)); return new InvocationOperation(method, instance: null, isVirtual: false, builder.ToImmutableAndFree(), semanticModel: null, operation.LimitValue.Syntax, method.ReturnType, isImplicit: true); } } void initializeLoop() { EvalStackFrame frame = PushStackFrame(); PushOperand(visitLoopControlVariableReference(forceImplicit: false)); PushOperand(VisitRequired(operation.InitialValue)); if (isObjectLoop) { // For i as Object = 3 To 6 step 2 // body // Next // // becomes ==> // // { // Dim loopObj ' mysterious object that holds the loop state // // ' helper does internal initialization and tells if we need to do any iterations // if Not ObjectFlowControl.ForLoopControl.ForLoopInitObj(ctrl, init, limit, step, ref loopObj, ref ctrl) // goto exit: // start: // body // // continue: // ' helper updates loop state and tells if we need to do another iteration. // if ObjectFlowControl.ForLoopControl.ForNextCheckObj(ctrl, loopObj, ref ctrl) // GoTo start // } // exit: PushOperand(VisitRequired(operation.LimitValue)); PushOperand(VisitRequired(operation.StepValue)); IOperation condition = tryCallObjectForLoopControlHelper(operation.LoopControlVariable.Syntax, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); } else { SpillEvalStack(); RegionBuilder currentRegion = CurrentRegionRequired; limitValueId = GetNextCaptureId(loopRegion); VisitAndCapture(operation.LimitValue, limitValueId); stepValueId = GetNextCaptureId(loopRegion); VisitAndCapture(operation.StepValue, stepValueId); IOperation stepValue = GetCaptureReference(stepValueId, operation.StepValue); if (userDefinedInfo != null) { Debug.Assert(_forToLoopBinaryOperatorLeftOperand == null); Debug.Assert(_forToLoopBinaryOperatorRightOperand == null); // calculate and cache result of a positive check := step >= (step - step). _forToLoopBinaryOperatorLeftOperand = GetCaptureReference(stepValueId, operation.StepValue); _forToLoopBinaryOperatorRightOperand = GetCaptureReference(stepValueId, operation.StepValue); IOperation subtraction = VisitRequired(userDefinedInfo.Subtraction); _forToLoopBinaryOperatorLeftOperand = stepValue; _forToLoopBinaryOperatorRightOperand = subtraction; int positiveFlagId = GetNextCaptureId(loopRegion); VisitAndCapture(userDefinedInfo.GreaterThanOrEqual, positiveFlagId); positiveFlag = GetCaptureReference(positiveFlagId, userDefinedInfo.GreaterThanOrEqual); _forToLoopBinaryOperatorLeftOperand = null; _forToLoopBinaryOperatorRightOperand = null; } else if (!(operation.StepValue.GetConstantValue() is { IsBad: false }) && !ITypeSymbolHelpers.IsSignedIntegralType(stepEnumUnderlyingTypeOrSelf) && !ITypeSymbolHelpers.IsUnsignedIntegralType(stepEnumUnderlyingTypeOrSelf)) { IOperation? stepValueIsNull = null; if (ITypeSymbolHelpers.IsNullableType(stepValue.Type)) { stepValueIsNull = MakeIsNullOperation(GetCaptureReference(stepValueId, operation.StepValue), booleanType); stepValue = CallNullableMember(stepValue, SpecialMember.System_Nullable_T_GetValueOrDefault); } ITypeSymbol? stepValueEnumUnderlyingTypeOrSelf = ITypeSymbolHelpers.GetEnumUnderlyingTypeOrSelf(stepValue.Type); if (ITypeSymbolHelpers.IsNumericType(stepValueEnumUnderlyingTypeOrSelf)) { // this one is tricky. // step value is not used directly in the loop condition // however its value determines the iteration direction // isUp = IsTrue(step >= step - step) // which implies that "step = null" ==> "isUp = false" IOperation isUp; int positiveFlagId = GetNextCaptureId(loopRegion); var afterPositiveCheck = new BasicBlockBuilder(BasicBlockKind.Block); if (stepValueIsNull != null) { var whenNotNull = new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(stepValueIsNull, jumpIfTrue: false, whenNotNull); _currentBasicBlock = null; // "isUp = false" isUp = new LiteralOperation(semanticModel: null, stepValue.Syntax, booleanType, constantValue: ConstantValue.Create(false), isImplicit: true); AddStatement(new FlowCaptureOperation(positiveFlagId, isUp.Syntax, isUp)); UnconditionalBranch(afterPositiveCheck); AppendNewBlock(whenNotNull); } IOperation literal = new LiteralOperation(semanticModel: null, stepValue.Syntax, stepValue.Type, constantValue: ConstantValue.Default(stepValueEnumUnderlyingTypeOrSelf.SpecialType), isImplicit: true); isUp = new BinaryOperation(BinaryOperatorKind.GreaterThanOrEqual, stepValue, literal, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, stepValue.Syntax, booleanType, constantValue: null, isImplicit: true); AddStatement(new FlowCaptureOperation(positiveFlagId, isUp.Syntax, isUp)); AppendNewBlock(afterPositiveCheck); positiveFlag = GetCaptureReference(positiveFlagId, isUp); } else { // This must be an error case. // It is fine to do nothing in this case, we are in recovery mode. } } IOperation initialValue = PopOperand(); AddStatement(new SimpleAssignmentOperation(isRef: false, // Loop control variable PopOperand(), initialValue, semanticModel: null, operation.InitialValue.Syntax, type: null, constantValue: null, isImplicit: true)); } PopStackFrameAndLeaveRegion(frame); } void checkLoopCondition() { if (isObjectLoop) { // For i as Object = 3 To 6 step 2 // body // Next // // becomes ==> // // { // Dim loopObj ' mysterious object that holds the loop state // // ' helper does internal initialization and tells if we need to do any iterations // if Not ObjectFlowControl.ForLoopControl.ForLoopInitObj(ctrl, init, limit, step, ref loopObj, ref ctrl) // goto exit: // start: // body // // continue: // ' helper updates loop state and tells if we need to do another iteration. // if ObjectFlowControl.ForLoopControl.ForNextCheckObj(ctrl, loopObj, ref ctrl) // GoTo start // } // exit: EvalStackFrame frame = PushStackFrame(); PushOperand(visitLoopControlVariableReference(forceImplicit: true)); IOperation condition = tryCallObjectForLoopControlHelper(operation.LimitValue.Syntax, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); return; } else if (userDefinedInfo != null) { Debug.Assert(_forToLoopBinaryOperatorLeftOperand == null); Debug.Assert(_forToLoopBinaryOperatorRightOperand == null); // Generate If(positiveFlag, controlVariable <= limit, controlVariable >= limit) EvalStackFrame frame = PushStackFrame(); // Spill control variable reference, we are going to have branches here. PushOperand(visitLoopControlVariableReference(forceImplicit: true)); // Yes we are going to evaluate it again SpillEvalStack(); IOperation controlVariableReferenceForCondition = PopOperand(); var notPositive = new BasicBlockBuilder(BasicBlockKind.Block); Debug.Assert(positiveFlag is not null); ConditionalBranch(positiveFlag, jumpIfTrue: false, notPositive); _currentBasicBlock = null; _forToLoopBinaryOperatorLeftOperand = controlVariableReferenceForCondition; _forToLoopBinaryOperatorRightOperand = GetCaptureReference(limitValueId, operation.LimitValue); VisitConditionalBranch(userDefinedInfo.LessThanOrEqual, ref @break, jumpIfTrue: false); UnconditionalBranch(bodyBlock); AppendNewBlock(notPositive); _forToLoopBinaryOperatorLeftOperand = OperationCloner.CloneOperation(_forToLoopBinaryOperatorLeftOperand); _forToLoopBinaryOperatorRightOperand = OperationCloner.CloneOperation(_forToLoopBinaryOperatorRightOperand); VisitConditionalBranch(userDefinedInfo.GreaterThanOrEqual, ref @break, jumpIfTrue: false); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); _forToLoopBinaryOperatorLeftOperand = null; _forToLoopBinaryOperatorRightOperand = null; return; } else { EvalStackFrame frame = PushStackFrame(); PushOperand(visitLoopControlVariableReference(forceImplicit: true)); // Yes we are going to evaluate it again IOperation limitReference = GetCaptureReference(limitValueId, operation.LimitValue); var comparisonKind = BinaryOperatorKind.None; // unsigned step is always Up if (ITypeSymbolHelpers.IsUnsignedIntegralType(stepEnumUnderlyingTypeOrSelf)) { comparisonKind = BinaryOperatorKind.LessThanOrEqual; } else if (operation.StepValue.GetConstantValue() is { IsBad: false } value) { Debug.Assert(value.Discriminator != ConstantValueTypeDiscriminator.Bad); if (value.IsNegativeNumeric) { comparisonKind = BinaryOperatorKind.GreaterThanOrEqual; } else if (value.IsNumeric) { comparisonKind = BinaryOperatorKind.LessThanOrEqual; } } // for signed integral steps not known at compile time // we do " (val Xor (step >> 31)) <= (limit Xor (step >> 31)) " // where 31 is actually the size-1 if (comparisonKind == BinaryOperatorKind.None && ITypeSymbolHelpers.IsSignedIntegralType(stepEnumUnderlyingTypeOrSelf)) { comparisonKind = BinaryOperatorKind.LessThanOrEqual; PushOperand(negateIfStepNegative(PopOperand())); limitReference = negateIfStepNegative(limitReference); } IOperation condition; if (comparisonKind != BinaryOperatorKind.None) { condition = new BinaryOperation(comparisonKind, PopOperand(), limitReference, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.LimitValue.Syntax, booleanType, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); return; } if (positiveFlag == null) { // Must be an error case. condition = MakeInvalidOperation(operation.LimitValue.Syntax, booleanType, PopOperand(), limitReference); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); return; } IOperation? eitherLimitOrControlVariableIsNull = null; if (ITypeSymbolHelpers.IsNullableType(operation.LimitValue.Type)) { eitherLimitOrControlVariableIsNull = new BinaryOperation(BinaryOperatorKind.Or, MakeIsNullOperation(limitReference, booleanType), MakeIsNullOperation(PopOperand(), booleanType), isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.StepValue.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), constantValue: null, isImplicit: true); // if either limit or control variable is null, we exit the loop var whenBothNotNull = new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(eitherLimitOrControlVariableIsNull, jumpIfTrue: false, whenBothNotNull); UnconditionalBranch(@break); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(whenBothNotNull); frame = PushStackFrame(); PushOperand(CallNullableMember(visitLoopControlVariableReference(forceImplicit: true), SpecialMember.System_Nullable_T_GetValueOrDefault)); // Yes we are going to evaluate it again limitReference = CallNullableMember(GetCaptureReference(limitValueId, operation.LimitValue), SpecialMember.System_Nullable_T_GetValueOrDefault); } // If (positiveFlag, ctrl <= limit, ctrl >= limit) SpillEvalStack(); IOperation controlVariableReferenceforCondition = PopOperand(); var notPositive = new BasicBlockBuilder(BasicBlockKind.Block); ConditionalBranch(positiveFlag, jumpIfTrue: false, notPositive); _currentBasicBlock = null; condition = new BinaryOperation(BinaryOperatorKind.LessThanOrEqual, controlVariableReferenceforCondition, limitReference, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.LimitValue.Syntax, booleanType, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); AppendNewBlock(notPositive); condition = new BinaryOperation(BinaryOperatorKind.GreaterThanOrEqual, OperationCloner.CloneOperation(controlVariableReferenceforCondition), OperationCloner.CloneOperation(limitReference), isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.LimitValue.Syntax, booleanType, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, @break); UnconditionalBranch(bodyBlock); PopStackFrameAndLeaveRegion(frame); return; } throw ExceptionUtilities.Unreachable; } // Produce "(operand Xor (step >> 31))" // where 31 is actually the size-1 IOperation negateIfStepNegative(IOperation operand) { int bits = stepEnumUnderlyingTypeOrSelf.SpecialType.VBForToShiftBits(); var shiftConst = new LiteralOperation(semanticModel: null, operand.Syntax, _compilation.GetSpecialType(SpecialType.System_Int32), constantValue: ConstantValue.Create(bits), isImplicit: true); var shiftedStep = new BinaryOperation(BinaryOperatorKind.RightShift, GetCaptureReference(stepValueId, operation.StepValue), shiftConst, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operand.Syntax, operation.StepValue.Type, constantValue: null, isImplicit: true); return new BinaryOperation(BinaryOperatorKind.ExclusiveOr, shiftedStep, operand, isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operand.Syntax, operand.Type, constantValue: null, isImplicit: true); } void incrementLoopControlVariable() { if (isObjectLoop) { // there is nothing interesting to do here, increment is folded into the condition check return; } else if (userDefinedInfo != null) { Debug.Assert(_forToLoopBinaryOperatorLeftOperand == null); Debug.Assert(_forToLoopBinaryOperatorRightOperand == null); EvalStackFrame frame = PushStackFrame(); IOperation controlVariableReferenceForAssignment = visitLoopControlVariableReference(forceImplicit: true); // Yes we are going to evaluate it again // We are going to evaluate control variable again and that might require branches PushOperand(controlVariableReferenceForAssignment); // Generate: controlVariable + stepValue _forToLoopBinaryOperatorLeftOperand = visitLoopControlVariableReference(forceImplicit: true); // Yes we are going to evaluate it again _forToLoopBinaryOperatorRightOperand = GetCaptureReference(stepValueId, operation.StepValue); IOperation increment = VisitRequired(userDefinedInfo.Addition); _forToLoopBinaryOperatorLeftOperand = null; _forToLoopBinaryOperatorRightOperand = null; controlVariableReferenceForAssignment = PopOperand(); AddStatement(new SimpleAssignmentOperation(isRef: false, controlVariableReferenceForAssignment, increment, semanticModel: null, controlVariableReferenceForAssignment.Syntax, type: null, constantValue: null, isImplicit: true)); PopStackFrameAndLeaveRegion(frame); } else { BasicBlockBuilder afterIncrement = new BasicBlockBuilder(BasicBlockKind.Block); IOperation controlVariableReferenceForAssignment; bool isNullable = ITypeSymbolHelpers.IsNullableType(operation.StepValue.Type); EvalStackFrame frame = PushStackFrame(); PushOperand(visitLoopControlVariableReference(forceImplicit: true)); // Yes we are going to evaluate it again if (isNullable) { // Spill control variable reference, we are going to have branches here. SpillEvalStack(); BasicBlockBuilder whenNotNull = new BasicBlockBuilder(BasicBlockKind.Block); EvalStackFrame nullCheckFrame = PushStackFrame(); IOperation condition = new BinaryOperation(BinaryOperatorKind.Or, MakeIsNullOperation(GetCaptureReference(stepValueId, operation.StepValue), booleanType), MakeIsNullOperation(visitLoopControlVariableReference(forceImplicit: true), // Yes we are going to evaluate it again booleanType), isLifted: false, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.StepValue.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, whenNotNull); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(nullCheckFrame); controlVariableReferenceForAssignment = OperationCloner.CloneOperation(PeekOperand()); Debug.Assert(controlVariableReferenceForAssignment.Kind == OperationKind.FlowCaptureReference); AddStatement(new SimpleAssignmentOperation(isRef: false, controlVariableReferenceForAssignment, new DefaultValueOperation(semanticModel: null, controlVariableReferenceForAssignment.Syntax, controlVariableReferenceForAssignment.Type, constantValue: null, isImplicit: true), semanticModel: null, controlVariableReferenceForAssignment.Syntax, type: null, constantValue: null, isImplicit: true)); UnconditionalBranch(afterIncrement); AppendNewBlock(whenNotNull); } IOperation controlVariableReferenceForIncrement = visitLoopControlVariableReference(forceImplicit: true); // Yes we are going to evaluate it again IOperation stepValueForIncrement = GetCaptureReference(stepValueId, operation.StepValue); if (isNullable) { Debug.Assert(ITypeSymbolHelpers.IsNullableType(controlVariableReferenceForIncrement.Type)); controlVariableReferenceForIncrement = CallNullableMember(controlVariableReferenceForIncrement, SpecialMember.System_Nullable_T_GetValueOrDefault); stepValueForIncrement = CallNullableMember(stepValueForIncrement, SpecialMember.System_Nullable_T_GetValueOrDefault); } IOperation increment = new BinaryOperation(BinaryOperatorKind.Add, controlVariableReferenceForIncrement, stepValueForIncrement, isLifted: false, isChecked: operation.IsChecked, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, operation.StepValue.Syntax, controlVariableReferenceForIncrement.Type, constantValue: null, isImplicit: true); controlVariableReferenceForAssignment = PopOperand(); if (isNullable) { Debug.Assert(controlVariableReferenceForAssignment.Type != null); increment = MakeNullable(increment, controlVariableReferenceForAssignment.Type); } AddStatement(new SimpleAssignmentOperation(isRef: false, controlVariableReferenceForAssignment, increment, semanticModel: null, controlVariableReferenceForAssignment.Syntax, type: null, constantValue: null, isImplicit: true)); PopStackFrame(frame, mergeNestedRegions: !isNullable); // We have a branch out in between when nullable is involved LeaveRegionIfAny(frame); AppendNewBlock(afterIncrement); } } IOperation visitLoopControlVariableReference(bool forceImplicit) { switch (operation.LoopControlVariable.Kind) { case OperationKind.VariableDeclarator: var declarator = (IVariableDeclaratorOperation)operation.LoopControlVariable; ILocalSymbol local = declarator.Symbol; return new LocalReferenceOperation(local, isDeclaration: true, semanticModel: null, declarator.Syntax, local.Type, constantValue: null, isImplicit: true); default: Debug.Assert(!_forceImplicit); _forceImplicit = forceImplicit; IOperation result = VisitRequired(operation.LoopControlVariable); _forceImplicit = false; return result; } } } private static FlowCaptureReferenceOperation GetCaptureReference(int id, IOperation underlying) { return new FlowCaptureReferenceOperation(id, underlying.Syntax, underlying.Type, underlying.GetConstantValue()); } internal override IOperation VisitAggregateQuery(IAggregateQueryOperation operation, int? captureIdForResult) { SpillEvalStack(); IOperation? previousAggregationGroup = _currentAggregationGroup; _currentAggregationGroup = VisitAndCapture(operation.Group); IOperation result = VisitRequired(operation.Aggregation); _currentAggregationGroup = previousAggregationGroup; return result; } public override IOperation? VisitSwitch(ISwitchOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); IOperation switchValue = VisitAndCapture(operation.Value); ImmutableArray<ILocalSymbol> locals = getLocals(); var switchRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: locals); EnterRegion(switchRegion); BasicBlockBuilder? defaultBody = null; // Adjusted in handleSection BasicBlockBuilder @break = GetLabeledOrNewBlock(operation.ExitLabel); foreach (ISwitchCaseOperation section in operation.Cases) { handleSection(section); } Debug.Assert(_currentRegion == switchRegion); if (defaultBody != null) { UnconditionalBranch(defaultBody); } LeaveRegion(); AppendNewBlock(@break); return FinishVisitingStatement(operation); ImmutableArray<ILocalSymbol> getLocals() { ImmutableArray<ILocalSymbol> l = operation.Locals; foreach (ISwitchCaseOperation section in operation.Cases) { l = l.Concat(section.Locals); } return l; } void handleSection(ISwitchCaseOperation section) { var body = new BasicBlockBuilder(BasicBlockKind.Block); var nextSection = new BasicBlockBuilder(BasicBlockKind.Block); IOperation? condition = ((SwitchCaseOperation)section).Condition; if (condition != null) { Debug.Assert(section.Clauses.All(c => c.Label == null)); Debug.Assert(_currentSwitchOperationExpression == null); _currentSwitchOperationExpression = switchValue; VisitConditionalBranch(condition, ref nextSection, jumpIfTrue: false); _currentSwitchOperationExpression = null; } else { foreach (ICaseClauseOperation caseClause in section.Clauses) { var nextCase = new BasicBlockBuilder(BasicBlockKind.Block); handleCase(caseClause, body, nextCase); AppendNewBlock(nextCase); } UnconditionalBranch(nextSection); } AppendNewBlock(body); VisitStatements(section.Body); UnconditionalBranch(@break); AppendNewBlock(nextSection); } void handleCase(ICaseClauseOperation caseClause, BasicBlockBuilder body, [DisallowNull] BasicBlockBuilder? nextCase) { IOperation condition; BasicBlockBuilder labeled = GetLabeledOrNewBlock(caseClause.Label); LinkBlocks(labeled, body); switch (caseClause.CaseKind) { case CaseKind.SingleValue: handleEqualityCheck(((ISingleValueCaseClauseOperation)caseClause).Value); break; void handleEqualityCheck(IOperation compareWith) { bool leftIsNullable = ITypeSymbolHelpers.IsNullableType(operation.Value.Type); bool rightIsNullable = ITypeSymbolHelpers.IsNullableType(compareWith.Type); bool isLifted = leftIsNullable || rightIsNullable; EvalStackFrame frame = PushStackFrame(); PushOperand(OperationCloner.CloneOperation(switchValue)); IOperation rightOperand = VisitRequired(compareWith); IOperation leftOperand = PopOperand(); if (isLifted) { if (!leftIsNullable) { if (leftOperand.Type != null) { Debug.Assert(compareWith.Type != null); leftOperand = MakeNullable(leftOperand, compareWith.Type); } } else if (!rightIsNullable && rightOperand.Type != null) { Debug.Assert(operation.Value.Type != null); rightOperand = MakeNullable(rightOperand, operation.Value.Type); } } condition = new BinaryOperation(BinaryOperatorKind.Equals, leftOperand, rightOperand, isLifted, isChecked: false, isCompareText: false, operatorMethod: null, unaryOperatorMethod: null, semanticModel: null, compareWith.Syntax, booleanType, constantValue: null, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, nextCase); PopStackFrameAndLeaveRegion(frame); AppendNewBlock(labeled); _currentBasicBlock = null; } case CaseKind.Pattern: { var patternClause = (IPatternCaseClauseOperation)caseClause; EvalStackFrame frame = PushStackFrame(); PushOperand(OperationCloner.CloneOperation(switchValue)); var pattern = (IPatternOperation)VisitRequired(patternClause.Pattern); condition = new IsPatternOperation(PopOperand(), pattern, semanticModel: null, patternClause.Pattern.Syntax, booleanType, isImplicit: true); ConditionalBranch(condition, jumpIfTrue: false, nextCase); PopStackFrameAndLeaveRegion(frame); if (patternClause.Guard != null) { AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); VisitConditionalBranch(patternClause.Guard, ref nextCase, jumpIfTrue: false); } AppendNewBlock(labeled); _currentBasicBlock = null; } break; case CaseKind.Relational: var relationalValueClause = (IRelationalCaseClauseOperation)caseClause; if (relationalValueClause.Relation == BinaryOperatorKind.Equals) { handleEqualityCheck(relationalValueClause.Value); break; } // A switch section with a relational case other than an equality must have // a condition associated with it. This point should not be reachable. throw ExceptionUtilities.UnexpectedValue(relationalValueClause.Relation); case CaseKind.Default: var defaultClause = (IDefaultCaseClauseOperation)caseClause; if (defaultBody == null) { defaultBody = labeled; } // 'default' clause is never entered from the top, we'll jump back to it after all // sections are processed. UnconditionalBranch(nextCase); AppendNewBlock(labeled); _currentBasicBlock = null; break; case CaseKind.Range: // A switch section with a range case must have a condition associated with it. // This point should not be reachable. default: throw ExceptionUtilities.UnexpectedValue(caseClause.CaseKind); } } } private IOperation MakeNullable(IOperation operand, ITypeSymbol type) { Debug.Assert(ITypeSymbolHelpers.IsNullableType(type)); Debug.Assert(ITypeSymbolHelpers.GetNullableUnderlyingType(type).Equals(operand.Type)); return CreateConversion(operand, type); } public override IOperation VisitSwitchCase(ISwitchCaseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitRangeCaseClause(IRangeCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitPatternCaseClause(IPatternCaseClauseOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation? VisitEnd(IEndOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); BasicBlockBuilder current = CurrentBasicBlock; AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block), linkToPrevious: false); Debug.Assert(current.BranchValue == null); Debug.Assert(!current.HasCondition); Debug.Assert(current.FallThrough.Destination == null); Debug.Assert(current.FallThrough.Kind == ControlFlowBranchSemantics.None); current.FallThrough.Kind = ControlFlowBranchSemantics.ProgramTermination; return FinishVisitingStatement(operation); } public override IOperation? VisitForLoop(IForLoopOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); // for (initializer; condition; increment) // body; // // becomes the following (with block added for locals) // // { // initializer; // start: // { // GotoIfFalse condition break; // body; // continue: // increment; // goto start; // } // } // break: EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals)); ImmutableArray<IOperation> initialization = operation.Before; if (initialization.Length == 1 && initialization[0].Kind == OperationKind.VariableDeclarationGroup) { HandleVariableDeclarations((VariableDeclarationGroupOperation)initialization.Single()); } else { VisitStatements(initialization); } var start = new BasicBlockBuilder(BasicBlockKind.Block); AppendNewBlock(start); EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.ConditionLocals)); var @break = GetLabeledOrNewBlock(operation.ExitLabel); if (operation.Condition != null) { VisitConditionalBranch(operation.Condition, ref @break, jumpIfTrue: false); } VisitStatement(operation.Body); var @continue = GetLabeledOrNewBlock(operation.ContinueLabel); AppendNewBlock(@continue); VisitStatements(operation.AtLoopBottom); UnconditionalBranch(start); LeaveRegion(); // ConditionLocals LeaveRegion(); // Locals AppendNewBlock(@break); return FinishVisitingStatement(operation); } internal override IOperation? VisitFixed(IFixedOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: operation.Locals)); HandleVariableDeclarations(operation.Variables); VisitStatement(operation.Body); LeaveRegion(); return FinishVisitingStatement(operation); } public override IOperation? VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, int? captureIdForResult) { // Anything that has a declaration group (such as for loops) needs to handle them directly itself, // this should only be encountered by the visitor for declaration statements. StartVisitingStatement(operation); HandleVariableDeclarations(operation); return FinishVisitingStatement(operation); } private void HandleVariableDeclarations(IVariableDeclarationGroupOperation operation) { // We erase variable declarations from the control flow graph, as variable lifetime information is // contained in a parallel data structure. foreach (var declaration in operation.Declarations) { HandleVariableDeclaration(declaration); } } private void HandleVariableDeclaration(IVariableDeclarationOperation operation) { foreach (IVariableDeclaratorOperation declarator in operation.Declarators) { HandleVariableDeclarator(operation, declarator); } } private void HandleVariableDeclarator(IVariableDeclarationOperation declaration, IVariableDeclaratorOperation declarator) { if (declarator.Initializer == null && declaration.Initializer == null) { return; } ILocalSymbol localSymbol = declarator.Symbol; // If the local is a static (possible in VB), then we create a semaphore for conditional execution of the initializer. BasicBlockBuilder? afterInitialization = null; if (localSymbol.IsStatic) { afterInitialization = new BasicBlockBuilder(BasicBlockKind.Block); ITypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); var initializationSemaphore = new StaticLocalInitializationSemaphoreOperation(localSymbol, declarator.Syntax, booleanType); ConditionalBranch(initializationSemaphore, jumpIfTrue: false, afterInitialization); _currentBasicBlock = null; EnterRegion(new RegionBuilder(ControlFlowRegionKind.StaticLocalInitializer)); } EvalStackFrame frame = PushStackFrame(); IOperation? initializer = null; SyntaxNode? assignmentSyntax = null; if (declarator.Initializer != null) { initializer = Visit(declarator.Initializer.Value); assignmentSyntax = declarator.Syntax; } if (declaration.Initializer != null) { IOperation operationInitializer = VisitRequired(declaration.Initializer.Value); assignmentSyntax = declaration.Syntax; if (initializer != null) { initializer = new InvalidOperation(ImmutableArray.Create(initializer, operationInitializer), semanticModel: null, declaration.Syntax, type: localSymbol.Type, constantValue: null, isImplicit: true); } else { initializer = operationInitializer; } } Debug.Assert(initializer != null && assignmentSyntax != null); // If we have an afterInitialization, then we must have static local and an initializer to ensure we don't create empty regions that can't be cleaned up. Debug.Assert((afterInitialization, localSymbol.IsStatic) is (null, false) or (not null, true)); // We can't use the IdentifierToken as the syntax for the local reference, so we use the // entire declarator as the node var localRef = new LocalReferenceOperation(localSymbol, isDeclaration: true, semanticModel: null, declarator.Syntax, localSymbol.Type, constantValue: null, isImplicit: true); var assignment = new SimpleAssignmentOperation(isRef: localSymbol.IsRef, localRef, initializer, semanticModel: null, assignmentSyntax, localRef.Type, constantValue: null, isImplicit: true); AddStatement(assignment); PopStackFrameAndLeaveRegion(frame); if (localSymbol.IsStatic) { LeaveRegion(); AppendNewBlock(afterInitialization!); } } public override IOperation VisitVariableDeclaration(IVariableDeclarationOperation operation, int? captureIdForResult) { // All variable declarators should be handled by VisitVariableDeclarationGroup. throw ExceptionUtilities.Unreachable; } public override IOperation VisitVariableDeclarator(IVariableDeclaratorOperation operation, int? captureIdForResult) { // All variable declarators should be handled by VisitVariableDeclaration. throw ExceptionUtilities.Unreachable; } public override IOperation VisitVariableInitializer(IVariableInitializerOperation operation, int? captureIdForResult) { // All variable initializers should be removed from the tree by VisitVariableDeclaration. throw ExceptionUtilities.Unreachable; } public override IOperation VisitFlowCapture(IFlowCaptureOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitIsNull(IIsNullOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitCaughtException(ICaughtExceptionOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitInvocation(IInvocationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); IOperation? instance = operation.TargetMethod.IsStatic ? null : operation.Instance; (IOperation? visitedInstance, ImmutableArray<IArgumentOperation> visitedArguments) = VisitInstanceWithArguments(instance, operation.Arguments); PopStackFrame(frame); return new InvocationOperation(operation.TargetMethod, visitedInstance, operation.IsVirtual, visitedArguments, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } private (IOperation? visitedInstance, ImmutableArray<IArgumentOperation> visitedArguments) VisitInstanceWithArguments(IOperation? instance, ImmutableArray<IArgumentOperation> arguments) { if (instance != null) { PushOperand(VisitRequired(instance)); } ImmutableArray<IArgumentOperation> visitedArguments = VisitArguments(arguments); IOperation? visitedInstance = instance == null ? null : PopOperand(); return (visitedInstance, visitedArguments); } internal override IOperation VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, int? argument) { EvalStackFrame frame = PushStackFrame(); // Initializer is removed from the tree and turned into a series of statements that assign to the created instance IOperation initializedInstance = new NoPiaObjectCreationOperation(initializer: null, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, initializedInstance)); } public override IOperation VisitObjectCreation(IObjectCreationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); EvalStackFrame argumentsFrame = PushStackFrame(); ImmutableArray<IArgumentOperation> visitedArgs = VisitArguments(operation.Arguments); PopStackFrame(argumentsFrame); // Initializer is removed from the tree and turned into a series of statements that assign to the created instance IOperation initializedInstance = new ObjectCreationOperation(operation.Constructor, initializer: null, visitedArgs, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, initializedInstance)); } public override IOperation VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); var initializedInstance = new TypeParameterObjectCreationOperation(initializer: null, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, initializedInstance)); } public override IOperation VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); EvalStackFrame argumentsFrame = PushStackFrame(); ImmutableArray<IOperation> visitedArguments = VisitArray(operation.Arguments); PopStackFrame(argumentsFrame); var hasDynamicArguments = (HasDynamicArgumentsExpression)operation; IOperation initializedInstance = new DynamicObjectCreationOperation(initializer: null, visitedArguments, hasDynamicArguments.ArgumentNames, hasDynamicArguments.ArgumentRefKinds, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, initializedInstance)); } private IOperation HandleObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation? initializer, IOperation objectCreation) { // If the initializer is null, nothing to spill. Just return the original instance. if (initializer == null || initializer.Initializers.IsEmpty) { return objectCreation; } // Initializer wasn't null, so spill the stack and capture the initialized instance. Returns a reference to the captured instance. PushOperand(objectCreation); SpillEvalStack(); objectCreation = PopOperand(); visitInitializer(initializer, objectCreation); return objectCreation; void visitInitializer(IObjectOrCollectionInitializerOperation initializerOperation, IOperation initializedInstance) { ImplicitInstanceInfo previousInitializedInstance = _currentImplicitInstance; _currentImplicitInstance = new ImplicitInstanceInfo(initializedInstance); foreach (IOperation innerInitializer in initializerOperation.Initializers) { handleInitializer(innerInitializer); } _currentImplicitInstance = previousInitializedInstance; } void handleInitializer(IOperation innerInitializer) { switch (innerInitializer.Kind) { case OperationKind.MemberInitializer: handleMemberInitializer((IMemberInitializerOperation)innerInitializer); return; case OperationKind.SimpleAssignment: handleSimpleAssignment((ISimpleAssignmentOperation)innerInitializer); return; default: // This assert is to document the list of things we know are possible to go through the default handler. It's possible there // are other nodes that will go through here, and if a new test triggers this assert, it will likely be fine to just add // the node type to the assert. It's here merely to ensure that we think about whether that node type actually does need // special handling in the context of a collection or object initializer before just assuming that it's fine. #if DEBUG var validKinds = ImmutableArray.Create(OperationKind.Invocation, OperationKind.DynamicInvocation, OperationKind.Increment, OperationKind.Literal, OperationKind.LocalReference, OperationKind.Binary, OperationKind.FieldReference, OperationKind.Invalid); Debug.Assert(validKinds.Contains(innerInitializer.Kind)); #endif EvalStackFrame frame = PushStackFrame(); AddStatement(Visit(innerInitializer)); PopStackFrameAndLeaveRegion(frame); return; } } void handleSimpleAssignment(ISimpleAssignmentOperation assignmentOperation) { EvalStackFrame frame = PushStackFrame(); bool pushSuccess = tryPushTarget(assignmentOperation.Target); IOperation result; if (!pushSuccess) { // Error case. We don't try any error recovery here, just return whatever the default visit would. result = VisitRequired(assignmentOperation); } else { // We push the target, which effectively pushes individual components of the target (ie the instance, and arguments if present). // After that has been pushed, we visit the value of the assignment, to ensure that the instance is captured if // needed. Finally, we reassemble the target, which will pull the potentially captured instance from the stack // and reassemble the member reference from the parts. IOperation right = VisitRequired(assignmentOperation.Value); IOperation left = popTarget(assignmentOperation.Target); result = new SimpleAssignmentOperation(assignmentOperation.IsRef, left, right, semanticModel: null, assignmentOperation.Syntax, assignmentOperation.Type, assignmentOperation.GetConstantValue(), IsImplicit(assignmentOperation)); } AddStatement(result); PopStackFrameAndLeaveRegion(frame); } void handleMemberInitializer(IMemberInitializerOperation memberInitializer) { // We explicitly do not push the initialized member onto the stack here. We visit the initialized member to get the implicit receiver that will be substituted in when an // IInstanceReferenceOperation with InstanceReferenceKind.ImplicitReceiver is encountered. If that receiver needs to be pushed onto the stack, its parent will handle it. // In member initializers, the code generated will evaluate InitializedMember multiple times. For example, if you have the following: // // class C1 // { // public C2 C2 { get; set; } = new C2(); // public void M() // { // var x = new C1 { C2 = { P1 = 1, P2 = 2 } }; // } // } // class C2 // { // public int P1 { get; set; } // public int P2 { get; set; } // } // // We generate the following code for C1.M(). Note the multiple calls to C1::get_C2(). // IL_0000: nop // IL_0001: newobj instance void C1::.ctor() // IL_0006: dup // IL_0007: callvirt instance class C2 C1::get_C2() // IL_000c: ldc.i4.1 // IL_000d: callvirt instance void C2::set_P1(int32) // IL_0012: nop // IL_0013: dup // IL_0014: callvirt instance class C2 C1::get_C2() // IL_0019: ldc.i4.2 // IL_001a: callvirt instance void C2::set_P2(int32) // IL_001f: nop // IL_0020: stloc.0 // IL_0021: ret // // We therefore visit the InitializedMember to get the implicit receiver for the contained initializer, and that implicit receiver will be cloned everywhere it encounters // an IInstanceReferenceOperation with ReferenceKind InstanceReferenceKind.ImplicitReceiver EvalStackFrame frame = PushStackFrame(); bool pushSuccess = tryPushTarget(memberInitializer.InitializedMember); IOperation instance = pushSuccess ? popTarget(memberInitializer.InitializedMember) : VisitRequired(memberInitializer.InitializedMember); visitInitializer(memberInitializer.Initializer, instance); PopStackFrameAndLeaveRegion(frame); } bool tryPushTarget(IOperation instance) { switch (instance.Kind) { case OperationKind.FieldReference: case OperationKind.EventReference: case OperationKind.PropertyReference: var memberReference = (IMemberReferenceOperation)instance; if (memberReference.Kind == OperationKind.PropertyReference) { // We assume all arguments have side effects and spill them. We only avoid recapturing things that have already been captured once. VisitAndPushArray(((IPropertyReferenceOperation)memberReference).Arguments, UnwrapArgument); SpillEvalStack(); } // If there is control flow in the value being assigned, we want to make sure that // the instance is captured appropriately, but the setter/field load in the reference will only be evaluated after // the value has been evaluated. So we assemble the reference after visiting the value. if (!memberReference.Member.IsStatic && memberReference.Instance != null) { PushOperand(VisitRequired(memberReference.Instance)); } return true; case OperationKind.ArrayElementReference: var arrayReference = (IArrayElementReferenceOperation)instance; VisitAndPushArray(arrayReference.Indices); SpillEvalStack(); PushOperand(VisitRequired(arrayReference.ArrayReference)); return true; case OperationKind.DynamicIndexerAccess: var dynamicIndexer = (IDynamicIndexerAccessOperation)instance; VisitAndPushArray(dynamicIndexer.Arguments); SpillEvalStack(); PushOperand(VisitRequired(dynamicIndexer.Operation)); return true; case OperationKind.DynamicMemberReference: var dynamicReference = (IDynamicMemberReferenceOperation)instance; if (dynamicReference.Instance != null) { PushOperand(VisitRequired(dynamicReference.Instance)); } return true; default: // As in the assert in handleInitializer, this assert documents the operation kinds that we know go through this path, // and it is possible others go through here as well. If they are encountered, we simply need to ensure // that they don't have any interesting semantics in object or collection initialization contexts and add them to the // assert. Debug.Assert(instance.Kind == OperationKind.Invalid || instance.Kind == OperationKind.None); return false; } } IOperation popTarget(IOperation originalTarget) { IOperation? instance; switch (originalTarget.Kind) { case OperationKind.FieldReference: var fieldReference = (IFieldReferenceOperation)originalTarget; instance = (!fieldReference.Member.IsStatic && fieldReference.Instance != null) ? PopOperand() : null; return new FieldReferenceOperation(fieldReference.Field, fieldReference.IsDeclaration, instance, semanticModel: null, fieldReference.Syntax, fieldReference.Type, fieldReference.GetConstantValue(), IsImplicit(fieldReference)); case OperationKind.EventReference: var eventReference = (IEventReferenceOperation)originalTarget; instance = (!eventReference.Member.IsStatic && eventReference.Instance != null) ? PopOperand() : null; return new EventReferenceOperation(eventReference.Event, instance, semanticModel: null, eventReference.Syntax, eventReference.Type, IsImplicit(eventReference)); case OperationKind.PropertyReference: var propertyReference = (IPropertyReferenceOperation)originalTarget; instance = (!propertyReference.Member.IsStatic && propertyReference.Instance != null) ? PopOperand() : null; ImmutableArray<IArgumentOperation> propertyArguments = PopArray(propertyReference.Arguments, RewriteArgumentFromArray); return new PropertyReferenceOperation(propertyReference.Property, propertyArguments, instance, semanticModel: null, propertyReference.Syntax, propertyReference.Type, IsImplicit(propertyReference)); case OperationKind.ArrayElementReference: var arrayElementReference = (IArrayElementReferenceOperation)originalTarget; instance = PopOperand(); ImmutableArray<IOperation> indices = PopArray(arrayElementReference.Indices); return new ArrayElementReferenceOperation(instance, indices, semanticModel: null, originalTarget.Syntax, originalTarget.Type, IsImplicit(originalTarget)); case OperationKind.DynamicIndexerAccess: var dynamicAccess = (DynamicIndexerAccessOperation)originalTarget; instance = PopOperand(); ImmutableArray<IOperation> arguments = PopArray(dynamicAccess.Arguments); return new DynamicIndexerAccessOperation(instance, arguments, dynamicAccess.ArgumentNames, dynamicAccess.ArgumentRefKinds, semanticModel: null, dynamicAccess.Syntax, dynamicAccess.Type, IsImplicit(dynamicAccess)); case OperationKind.DynamicMemberReference: var dynamicReference = (IDynamicMemberReferenceOperation)originalTarget; instance = dynamicReference.Instance != null ? PopOperand() : null; return new DynamicMemberReferenceOperation(instance, dynamicReference.MemberName, dynamicReference.TypeArguments, dynamicReference.ContainingType, semanticModel: null, dynamicReference.Syntax, dynamicReference.Type, IsImplicit(dynamicReference)); default: // Unlike in tryPushTarget, we assume that if this method is called, we were successful in pushing, so // this must be one of the explicitly handled kinds throw ExceptionUtilities.UnexpectedValue(originalTarget.Kind); } } } public override IOperation VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, int? captureIdForResult) { Debug.Fail("This code path should not be reachable."); return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray<IOperation>.Empty); } public override IOperation VisitMemberInitializer(IMemberInitializerOperation operation, int? captureIdForResult) { Debug.Fail("This code path should not be reachable."); return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray<IOperation>.Empty); } public override IOperation VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, int? captureIdForResult) { if (operation.Initializers.IsEmpty) { return new AnonymousObjectCreationOperation(initializers: ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } ImplicitInstanceInfo savedCurrentImplicitInstance = _currentImplicitInstance; Debug.Assert(operation.Type is not null); _currentImplicitInstance = new ImplicitInstanceInfo((INamedTypeSymbol)operation.Type); Debug.Assert(_currentImplicitInstance.AnonymousTypePropertyValues is not null); SpillEvalStack(); EvalStackFrame frame = PushStackFrame(); var initializerBuilder = ArrayBuilder<IOperation>.GetInstance(operation.Initializers.Length); for (int i = 0; i < operation.Initializers.Length; i++) { var simpleAssignment = (ISimpleAssignmentOperation)operation.Initializers[i]; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Debug.Assert(propertyReference != null); Debug.Assert(propertyReference.Arguments.IsEmpty); Debug.Assert(propertyReference.Instance != null); Debug.Assert(propertyReference.Instance.Kind == OperationKind.InstanceReference); Debug.Assert(((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind == InstanceReferenceKind.ImplicitReceiver); var visitedPropertyInstance = new InstanceReferenceOperation(InstanceReferenceKind.ImplicitReceiver, semanticModel: null, propertyReference.Instance.Syntax, propertyReference.Instance.Type, IsImplicit(propertyReference.Instance)); IOperation visitedTarget = new PropertyReferenceOperation(propertyReference.Property, ImmutableArray<IArgumentOperation>.Empty, visitedPropertyInstance, semanticModel: null, propertyReference.Syntax, propertyReference.Type, IsImplicit(propertyReference)); IOperation visitedValue = visitAndCaptureInitializer(propertyReference.Property, simpleAssignment.Value); var visitedAssignment = new SimpleAssignmentOperation(isRef: simpleAssignment.IsRef, visitedTarget, visitedValue, semanticModel: null, simpleAssignment.Syntax, simpleAssignment.Type, simpleAssignment.GetConstantValue(), IsImplicit(simpleAssignment)); initializerBuilder.Add(visitedAssignment); } _currentImplicitInstance.Free(); _currentImplicitInstance = savedCurrentImplicitInstance; for (int i = 0; i < initializerBuilder.Count; i++) { PopOperand(); } PopStackFrame(frame); return new AnonymousObjectCreationOperation(initializerBuilder.ToImmutableAndFree(), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); IOperation visitAndCaptureInitializer(IPropertySymbol initializedProperty, IOperation initializer) { PushOperand(VisitRequired(initializer)); SpillEvalStack(); IOperation captured = PeekOperand(); // Keep it on the stack so that we know it is still used. // For VB, previously initialized properties can be referenced in subsequent initializers. // We store the capture Id for the property for such property references. // Note that for VB error cases with duplicate property names, all the property symbols are considered equal. // We use the last duplicate property's capture id and use it in subsequent property references. _currentImplicitInstance.AnonymousTypePropertyValues[initializedProperty] = captured; return captured; } } public override IOperation? VisitLocalFunction(ILocalFunctionOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); RegionBuilder owner = CurrentRegionRequired; while (owner.IsStackSpillRegion) { Debug.Assert(owner.Enclosing != null); owner = owner.Enclosing; } owner.Add(operation.Symbol, operation); return FinishVisitingStatement(operation); } private IOperation? VisitLocalFunctionAsRoot(ILocalFunctionOperation operation) { Debug.Assert(_currentStatement == null); VisitMethodBodies(operation.Body, operation.IgnoredBody); return null; } public override IOperation VisitAnonymousFunction(IAnonymousFunctionOperation operation, int? captureIdForResult) { _haveAnonymousFunction = true; return new FlowAnonymousFunctionOperation(GetCurrentContext(), operation, IsImplicit(operation)); } public override IOperation VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitArrayCreation(IArrayCreationOperation operation, int? captureIdForResult) { // We have couple of options on how to rewrite an array creation with an initializer: // 1) Retain the original tree shape so the visited IArrayCreationOperation still has an IArrayInitializerOperation child node. // 2) Lower the IArrayCreationOperation so it always has a null initializer, followed by explicit assignments // of the form "IArrayElementReference = value" for the array initializer values. // There will be no IArrayInitializerOperation in the tree with approach. // // We are going ahead with approach #1 for couple of reasons: // 1. Simplicity: The implementation is much simpler, and has a lot lower risk associated with it. // 2. Lack of array instance access in the initializer: Unlike the object/collection initializer scenario, // where the initializer can access the instance being initialized, array initializer does not have access // to the array instance being initialized, and hence it does not matter if the array allocation is done // before visiting the initializers or not. // // In future, based on the customer feedback, we can consider switching to approach #2 and lower the initializer into assignment(s). EvalStackFrame frame = PushStackFrame(); VisitAndPushArray(operation.DimensionSizes); var visitedInitializer = (IArrayInitializerOperation?)Visit(operation.Initializer); ImmutableArray<IOperation> visitedDimensions = PopArray(operation.DimensionSizes); PopStackFrame(frame); return new ArrayCreationOperation(visitedDimensions, visitedInitializer, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitArrayInitializer(IArrayInitializerOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); visitAndPushArrayInitializerValues(operation); return PopStackFrame(frame, popAndAssembleArrayInitializerValues(operation)); void visitAndPushArrayInitializerValues(IArrayInitializerOperation initializer) { foreach (IOperation elementValue in initializer.ElementValues) { // We need to retain the tree shape for nested array initializer. if (elementValue.Kind == OperationKind.ArrayInitializer) { visitAndPushArrayInitializerValues((IArrayInitializerOperation)elementValue); } else { PushOperand(VisitRequired(elementValue)); } } } IArrayInitializerOperation popAndAssembleArrayInitializerValues(IArrayInitializerOperation initializer) { var builder = ArrayBuilder<IOperation>.GetInstance(initializer.ElementValues.Length); for (int i = initializer.ElementValues.Length - 1; i >= 0; i--) { IOperation elementValue = initializer.ElementValues[i]; IOperation visitedElementValue; if (elementValue.Kind == OperationKind.ArrayInitializer) { visitedElementValue = popAndAssembleArrayInitializerValues((IArrayInitializerOperation)elementValue); } else { visitedElementValue = PopOperand(); } builder.Add(visitedElementValue); } builder.ReverseContents(); return new ArrayInitializerOperation(builder.ToImmutableAndFree(), semanticModel: null, initializer.Syntax, IsImplicit(initializer)); } } public override IOperation VisitInstanceReference(IInstanceReferenceOperation operation, int? captureIdForResult) { if (operation.ReferenceKind == InstanceReferenceKind.ImplicitReceiver) { // When we're in an object or collection initializer, we need to replace the instance reference with a reference to the object being initialized Debug.Assert(operation.IsImplicit); if (_currentImplicitInstance.ImplicitInstance != null) { return OperationCloner.CloneOperation(_currentImplicitInstance.ImplicitInstance); } else { Debug.Fail("This code path should not be reachable."); return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray<IOperation>.Empty); } } else { return new InstanceReferenceOperation(operation.ReferenceKind, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } } public override IOperation VisitDynamicInvocation(IDynamicInvocationOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); if (operation.Operation.Kind == OperationKind.DynamicMemberReference) { var instance = ((IDynamicMemberReferenceOperation)operation.Operation).Instance; if (instance != null) { PushOperand(VisitRequired(instance)); } } else { PushOperand(VisitRequired(operation.Operation)); } ImmutableArray<IOperation> rewrittenArguments = VisitArray(operation.Arguments); IOperation rewrittenOperation; if (operation.Operation.Kind == OperationKind.DynamicMemberReference) { var dynamicMemberReference = (IDynamicMemberReferenceOperation)operation.Operation; IOperation? rewrittenInstance = dynamicMemberReference.Instance != null ? PopOperand() : null; rewrittenOperation = new DynamicMemberReferenceOperation(rewrittenInstance, dynamicMemberReference.MemberName, dynamicMemberReference.TypeArguments, dynamicMemberReference.ContainingType, semanticModel: null, dynamicMemberReference.Syntax, dynamicMemberReference.Type, IsImplicit(dynamicMemberReference)); } else { rewrittenOperation = PopOperand(); } PopStackFrame(frame); return new DynamicInvocationOperation(rewrittenOperation, rewrittenArguments, ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation, int? captureIdForResult) { PushOperand(VisitRequired(operation.Operation)); ImmutableArray<IOperation> rewrittenArguments = VisitArray(operation.Arguments); IOperation rewrittenOperation = PopOperand(); return new DynamicIndexerAccessOperation(rewrittenOperation, rewrittenArguments, ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, int? captureIdForResult) { return new DynamicMemberReferenceOperation(Visit(operation.Instance), operation.MemberName, operation.TypeArguments, operation.ContainingType, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, int? captureIdForResult) { (IOperation visitedTarget, IOperation visitedValue) = VisitPreservingTupleOperations(operation.Target, operation.Value); return new DeconstructionAssignmentOperation(visitedTarget, visitedValue, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } /// <summary> /// Recursively push nexted values onto the stack for visiting /// </summary> private void PushTargetAndUnwrapTupleIfNecessary(IOperation value) { if (value.Kind == OperationKind.Tuple) { var tuple = (ITupleOperation)value; foreach (IOperation element in tuple.Elements) { PushTargetAndUnwrapTupleIfNecessary(element); } } else { PushOperand(VisitRequired(value)); } } /// <summary> /// Recursively pop nested tuple values off the stack after visiting /// </summary> private IOperation PopTargetAndWrapTupleIfNecessary(IOperation value) { if (value.Kind == OperationKind.Tuple) { var tuple = (ITupleOperation)value; var numElements = tuple.Elements.Length; var elementBuilder = ArrayBuilder<IOperation>.GetInstance(numElements); for (int i = numElements - 1; i >= 0; i--) { elementBuilder.Add(PopTargetAndWrapTupleIfNecessary(tuple.Elements[i])); } elementBuilder.ReverseContents(); return new TupleOperation(elementBuilder.ToImmutableAndFree(), tuple.NaturalType, semanticModel: null, tuple.Syntax, tuple.Type, IsImplicit(tuple)); } else { return PopOperand(); } } public override IOperation VisitDeclarationExpression(IDeclarationExpressionOperation operation, int? captureIdForResult) { return new DeclarationExpressionOperation(VisitPreservingTupleOperations(operation.Expression), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } private IOperation VisitPreservingTupleOperations(IOperation operation) { EvalStackFrame frame = PushStackFrame(); PushTargetAndUnwrapTupleIfNecessary(operation); return PopStackFrame(frame, PopTargetAndWrapTupleIfNecessary(operation)); } private (IOperation visitedLeft, IOperation visitedRight) VisitPreservingTupleOperations(IOperation left, IOperation right) { Debug.Assert(left != null); Debug.Assert(right != null); // If the left is a tuple, we want to decompose the tuple and push each element back onto the stack, so that if the right // has control flow the individual elements are captured. Then we can recompose the tuple after the right has been visited. // We do this to keep the graph sane, so that users don't have to track a tuple captured via flow control when it's not really // the tuple that's been captured, it's the operands to the tuple. EvalStackFrame frame = PushStackFrame(); PushTargetAndUnwrapTupleIfNecessary(left); IOperation visitedRight = VisitRequired(right); IOperation visitedLeft = PopTargetAndWrapTupleIfNecessary(left); PopStackFrame(frame); return (visitedLeft, visitedRight); } public override IOperation VisitTuple(ITupleOperation operation, int? captureIdForResult) { return VisitPreservingTupleOperations(operation); } internal override IOperation VisitNoneOperation(IOperation operation, int? captureIdForResult) { if (_currentStatement == operation) { return VisitNoneOperationStatement(operation); } else { return VisitNoneOperationExpression(operation); } } private IOperation VisitNoneOperationStatement(IOperation operation) { Debug.Assert(_currentStatement == operation); VisitStatements(((Operation)operation).ChildOperations.ToImmutableArray()); return new NoneOperation(ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } private IOperation VisitNoneOperationExpression(IOperation operation) { return PopStackFrame(PushStackFrame(), new NoneOperation(VisitArray(((Operation)operation).ChildOperations.ToImmutableArray()), semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); } public override IOperation? VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation, int? captureIdForResult) { return VisitNoneOperation(operation, captureIdForResult); } public override IOperation? VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation, int? captureIdForResult) { return VisitNoneOperation(operation, captureIdForResult); } public override IOperation? VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation? VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation, int? captureIdForResult) { return VisitNoneOperation(operation, captureIdForResult); } public override IOperation VisitInterpolatedString(IInterpolatedStringOperation operation, int? captureIdForResult) { // We visit and rewrite the interpolation parts in two phases: // 1. Visit all the non-literal parts of the interpolation and push them onto the eval stack. // 2. Traverse the parts in reverse order, popping the non-literal values from the eval stack and visiting the literal values. EvalStackFrame frame = PushStackFrame(); foreach (IInterpolatedStringContentOperation element in operation.Parts) { if (element.Kind == OperationKind.Interpolation) { var interpolation = (IInterpolationOperation)element; PushOperand(VisitRequired(interpolation.Expression)); if (interpolation.Alignment != null) { PushOperand(VisitRequired(interpolation.Alignment)); } } } var partsBuilder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(operation.Parts.Length); for (int i = operation.Parts.Length - 1; i >= 0; i--) { IInterpolatedStringContentOperation element = operation.Parts[i]; IInterpolatedStringContentOperation rewrittenElement; switch (element) { case IInterpolationOperation interpolation: IOperation? rewrittenFormatString; if (interpolation.FormatString != null) { Debug.Assert(interpolation.FormatString is ILiteralOperation or IConversionOperation { Operand: ILiteralOperation }); rewrittenFormatString = VisitRequired(interpolation.FormatString, argument: null); } else { rewrittenFormatString = null; } var rewrittenAlignment = interpolation.Alignment != null ? PopOperand() : null; var rewrittenExpression = PopOperand(); rewrittenElement = new InterpolationOperation(rewrittenExpression, rewrittenAlignment, rewrittenFormatString, semanticModel: null, element.Syntax, IsImplicit(element)); break; case IInterpolatedStringTextOperation interpolatedStringText: Debug.Assert(interpolatedStringText.Text is ILiteralOperation or IConversionOperation { Operand: ILiteralOperation }); var rewrittenInterpolationText = VisitRequired(interpolatedStringText.Text, argument: null); rewrittenElement = new InterpolatedStringTextOperation(rewrittenInterpolationText, semanticModel: null, element.Syntax, IsImplicit(element)); break; case IInterpolatedStringAppendOperation interpolatedStringAppend: rewrittenElement = new InterpolatedStringAppendOperation(VisitRequired(interpolatedStringAppend.AppendCall), interpolatedStringAppend.Kind, semanticModel: null, interpolatedStringAppend.Syntax, IsImplicit(interpolatedStringAppend)); break; default: throw ExceptionUtilities.UnexpectedValue(element.Kind); } partsBuilder.Add(rewrittenElement); } partsBuilder.ReverseContents(); PopStackFrame(frame); return new InterpolatedStringOperation(partsBuilder.ToImmutableAndFree(), semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitInterpolation(IInterpolationOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitNameOf(INameOfOperation operation, int? captureIdForResult) { Debug.Assert(operation.GetConstantValue() != null); return new LiteralOperation(semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitLiteral(ILiteralOperation operation, int? captureIdForResult) { return new LiteralOperation(semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitLocalReference(ILocalReferenceOperation operation, int? captureIdForResult) { return new LocalReferenceOperation(operation.Local, operation.IsDeclaration, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitParameterReference(IParameterReferenceOperation operation, int? captureIdForResult) { return new ParameterReferenceOperation(operation.Parameter, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitFieldReference(IFieldReferenceOperation operation, int? captureIdForResult) { IOperation? visitedInstance = operation.Field.IsStatic ? null : Visit(operation.Instance); return new FieldReferenceOperation(operation.Field, operation.IsDeclaration, visitedInstance, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitMethodReference(IMethodReferenceOperation operation, int? captureIdForResult) { IOperation? visitedInstance = operation.Method.IsStatic ? null : Visit(operation.Instance); return new MethodReferenceOperation(operation.Method, operation.IsVirtual, visitedInstance, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitPropertyReference(IPropertyReferenceOperation operation, int? captureIdForResult) { // Check if this is an anonymous type property reference with an implicit receiver within an anonymous object initializer. if (operation.Instance is IInstanceReferenceOperation instanceReference && instanceReference.ReferenceKind == InstanceReferenceKind.ImplicitReceiver && operation.Property.ContainingType.IsAnonymousType && operation.Property.ContainingType == _currentImplicitInstance.AnonymousType) { Debug.Assert(_currentImplicitInstance.AnonymousTypePropertyValues is not null); if (_currentImplicitInstance.AnonymousTypePropertyValues.TryGetValue(operation.Property, out IOperation? captured)) { return captured is IFlowCaptureReferenceOperation reference ? GetCaptureReference(reference.Id.Value, operation) : OperationCloner.CloneOperation(captured); } else { return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray<IOperation>.Empty); } } EvalStackFrame frame = PushStackFrame(); IOperation? instance = operation.Property.IsStatic ? null : operation.Instance; (IOperation? visitedInstance, ImmutableArray<IArgumentOperation> visitedArguments) = VisitInstanceWithArguments(instance, operation.Arguments); PopStackFrame(frame); return new PropertyReferenceOperation(operation.Property, visitedArguments, visitedInstance, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitEventReference(IEventReferenceOperation operation, int? captureIdForResult) { IOperation? visitedInstance = operation.Event.IsStatic ? null : Visit(operation.Instance); return new EventReferenceOperation(operation.Event, visitedInstance, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitTypeOf(ITypeOfOperation operation, int? captureIdForResult) { return new TypeOfOperation(operation.TypeOperand, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitParenthesized(IParenthesizedOperation operation, int? captureIdForResult) { return new ParenthesizedOperation(VisitRequired(operation.Operand), semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitAwait(IAwaitOperation operation, int? captureIdForResult) { return new AwaitOperation(VisitRequired(operation.Operation), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitSizeOf(ISizeOfOperation operation, int? captureIdForResult) { return new SizeOfOperation(operation.TypeOperand, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitStop(IStopOperation operation, int? captureIdForResult) { return new StopOperation(semanticModel: null, operation.Syntax, IsImplicit(operation)); } public override IOperation VisitIsType(IIsTypeOperation operation, int? captureIdForResult) { return new IsTypeOperation(VisitRequired(operation.ValueOperand), operation.TypeOperand, operation.IsNegated, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation? VisitParameterInitializer(IParameterInitializerOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); var parameterRef = new ParameterReferenceOperation(operation.Parameter, semanticModel: null, operation.Syntax, operation.Parameter.Type, isImplicit: true); VisitInitializer(rewrittenTarget: parameterRef, initializer: operation); return FinishVisitingStatement(operation); } public override IOperation? VisitFieldInitializer(IFieldInitializerOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); foreach (IFieldSymbol fieldSymbol in operation.InitializedFields) { IInstanceReferenceOperation? instance = fieldSymbol.IsStatic ? null : new InstanceReferenceOperation(InstanceReferenceKind.ContainingTypeInstance, semanticModel: null, operation.Syntax, fieldSymbol.ContainingType, isImplicit: true); var fieldRef = new FieldReferenceOperation(fieldSymbol, isDeclaration: false, instance, semanticModel: null, operation.Syntax, fieldSymbol.Type, constantValue: null, isImplicit: true); VisitInitializer(rewrittenTarget: fieldRef, initializer: operation); } return FinishVisitingStatement(operation); } public override IOperation? VisitPropertyInitializer(IPropertyInitializerOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); foreach (IPropertySymbol propertySymbol in operation.InitializedProperties) { var instance = propertySymbol.IsStatic ? null : new InstanceReferenceOperation(InstanceReferenceKind.ContainingTypeInstance, semanticModel: null, operation.Syntax, propertySymbol.ContainingType, isImplicit: true); ImmutableArray<IArgumentOperation> arguments; if (!propertySymbol.Parameters.IsEmpty) { // Must be an error case of initializing a property with parameters. var builder = ArrayBuilder<IArgumentOperation>.GetInstance(propertySymbol.Parameters.Length); foreach (var parameter in propertySymbol.Parameters) { var value = new InvalidOperation(ImmutableArray<IOperation>.Empty, semanticModel: null, operation.Syntax, parameter.Type, constantValue: null, isImplicit: true); var argument = new ArgumentOperation(ArgumentKind.Explicit, parameter, value, inConversion: OperationFactory.IdentityConversion, outConversion: OperationFactory.IdentityConversion, semanticModel: null, operation.Syntax, isImplicit: true); builder.Add(argument); } arguments = builder.ToImmutableAndFree(); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } IOperation propertyRef = new PropertyReferenceOperation(propertySymbol, arguments, instance, semanticModel: null, operation.Syntax, propertySymbol.Type, isImplicit: true); VisitInitializer(rewrittenTarget: propertyRef, initializer: operation); } return FinishVisitingStatement(operation); } private void VisitInitializer(IOperation rewrittenTarget, ISymbolInitializerOperation initializer) { EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: initializer.Locals)); EvalStackFrame frame = PushStackFrame(); var assignment = new SimpleAssignmentOperation(isRef: false, rewrittenTarget, VisitRequired(initializer.Value), semanticModel: null, initializer.Syntax, rewrittenTarget.Type, constantValue: null, isImplicit: true); AddStatement(assignment); PopStackFrameAndLeaveRegion(frame); LeaveRegion(); } public override IOperation VisitEventAssignment(IEventAssignmentOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); IOperation visitedEventReference, visitedHandler; // Get the IEventReferenceOperation, digging through IParenthesizedOperation. // Note that for error cases, the event reference might be an IInvalidOperation. IEventReferenceOperation? eventReference = getEventReference(); if (eventReference != null) { // Preserve the IEventReferenceOperation. var eventReferenceInstance = eventReference.Event.IsStatic ? null : eventReference.Instance; if (eventReferenceInstance != null) { PushOperand(VisitRequired(eventReferenceInstance)); } visitedHandler = VisitRequired(operation.HandlerValue); IOperation? visitedInstance = eventReferenceInstance == null ? null : PopOperand(); visitedEventReference = new EventReferenceOperation(eventReference.Event, visitedInstance, semanticModel: null, operation.EventReference.Syntax, operation.EventReference.Type, IsImplicit(operation.EventReference)); } else { Debug.Assert(operation.EventReference != null); PushOperand(VisitRequired(operation.EventReference)); visitedHandler = VisitRequired(operation.HandlerValue); visitedEventReference = PopOperand(); } PopStackFrame(frame); return new EventAssignmentOperation(visitedEventReference, visitedHandler, operation.Adds, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); IEventReferenceOperation? getEventReference() { IOperation current = operation.EventReference; while (true) { switch (current.Kind) { case OperationKind.EventReference: return (IEventReferenceOperation)current; case OperationKind.Parenthesized: current = ((IParenthesizedOperation)current).Operand; continue; default: return null; } } } } public override IOperation VisitRaiseEvent(IRaiseEventOperation operation, int? captureIdForResult) { StartVisitingStatement(operation); EvalStackFrame frame = PushStackFrame(); var instance = operation.EventReference.Event.IsStatic ? null : operation.EventReference.Instance; if (instance != null) { PushOperand(VisitRequired(instance)); } ImmutableArray<IArgumentOperation> visitedArguments = VisitArguments(operation.Arguments); IOperation? visitedInstance = instance == null ? null : PopOperand(); var visitedEventReference = new EventReferenceOperation(operation.EventReference.Event, visitedInstance, semanticModel: null, operation.EventReference.Syntax, operation.EventReference.Type, IsImplicit(operation.EventReference)); PopStackFrame(frame); return FinishVisitingStatement(operation, new RaiseEventOperation(visitedEventReference, visitedArguments, semanticModel: null, operation.Syntax, IsImplicit(operation))); } public override IOperation VisitAddressOf(IAddressOfOperation operation, int? captureIdForResult) { return new AddressOfOperation(VisitRequired(operation.Reference), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, int? captureIdForResult) { return new IncrementOrDecrementOperation(operation.IsPostfix, operation.IsLifted, operation.IsChecked, VisitRequired(operation.Target), operation.OperatorMethod, operation.Kind, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDiscardOperation(IDiscardOperation operation, int? captureIdForResult) { return new DiscardOperation(operation.DiscardSymbol, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitDiscardPattern(IDiscardPatternOperation pat, int? captureIdForResult) { return new DiscardPatternOperation(pat.InputType, pat.NarrowedType, semanticModel: null, pat.Syntax, IsImplicit(pat)); } public override IOperation VisitOmittedArgument(IOmittedArgumentOperation operation, int? captureIdForResult) { return new OmittedArgumentOperation(semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } internal override IOperation VisitPlaceholder(IPlaceholderOperation operation, int? captureIdForResult) { switch (operation.PlaceholderKind) { case PlaceholderKind.SwitchOperationExpression: if (_currentSwitchOperationExpression != null) { return OperationCloner.CloneOperation(_currentSwitchOperationExpression); } break; case PlaceholderKind.ForToLoopBinaryOperatorLeftOperand: if (_forToLoopBinaryOperatorLeftOperand != null) { return _forToLoopBinaryOperatorLeftOperand; } break; case PlaceholderKind.ForToLoopBinaryOperatorRightOperand: if (_forToLoopBinaryOperatorRightOperand != null) { return _forToLoopBinaryOperatorRightOperand; } break; case PlaceholderKind.AggregationGroup: if (_currentAggregationGroup != null) { return OperationCloner.CloneOperation(_currentAggregationGroup); } break; } Debug.Fail("All placeholders should be handled above. Have we introduced a new scenario where placeholders are used?"); return new PlaceholderOperation(operation.PlaceholderKind, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitConversion(IConversionOperation operation, int? captureIdForResult) { return new ConversionOperation(VisitRequired(operation.Operand), ((ConversionOperation)operation).ConversionConvertible, operation.IsTryCast, operation.IsChecked, semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitDefaultValue(IDefaultValueOperation operation, int? captureIdForResult) { return new DefaultValueOperation(semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); } public override IOperation VisitIsPattern(IIsPatternOperation operation, int? captureIdForResult) { EvalStackFrame frame = PushStackFrame(); PushOperand(VisitRequired(operation.Value)); var visitedPattern = (IPatternOperation)VisitRequired(operation.Pattern); IOperation visitedValue = PopOperand(); PopStackFrame(frame); return new IsPatternOperation(visitedValue, visitedPattern, semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitInvalid(IInvalidOperation operation, int? captureIdForResult) { var children = ArrayBuilder<IOperation>.GetInstance(); children.AddRange(((InvalidOperation)operation).Children); if (children.Count != 0 && children.Last().Kind == OperationKind.ObjectOrCollectionInitializer) { // We are dealing with erroneous object creation. All children, but the last one are arguments for the constructor, // but overload resolution failed. SpillEvalStack(); EvalStackFrame frame = PushStackFrame(); var initializer = (IObjectOrCollectionInitializerOperation)children.Last(); children.RemoveLast(); EvalStackFrame argumentsFrame = PushStackFrame(); foreach (var argument in children) { PushOperand(VisitRequired(argument)); } for (int i = children.Count - 1; i >= 0; i--) { children[i] = PopOperand(); } PopStackFrame(argumentsFrame); IOperation initializedInstance = new InvalidOperation(children.ToImmutableAndFree(), semanticModel: null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); initializedInstance = HandleObjectOrCollectionInitializer(initializer, initializedInstance); PopStackFrame(frame); return initializedInstance; } IOperation result; if (_currentStatement == operation) { result = visitInvalidOperationStatement(operation); } else { result = visitInvalidOperationExpression(operation); } return result; IOperation visitInvalidOperationStatement(IInvalidOperation invalidOperation) { Debug.Assert(_currentStatement == invalidOperation); VisitStatements(children.ToImmutableAndFree()); return new InvalidOperation(ImmutableArray<IOperation>.Empty, semanticModel: null, invalidOperation.Syntax, invalidOperation.Type, invalidOperation.GetConstantValue(), IsImplicit(invalidOperation)); } IOperation visitInvalidOperationExpression(IInvalidOperation invalidOperation) { return PopStackFrame(PushStackFrame(), new InvalidOperation(VisitArray(children.ToImmutableAndFree()), semanticModel: null, invalidOperation.Syntax, invalidOperation.Type, invalidOperation.GetConstantValue(), IsImplicit(operation))); } } public override IOperation? VisitReDim(IReDimOperation operation, int? argument) { StartVisitingStatement(operation); // We split the ReDim clauses into separate ReDim operations to ensure that we preserve the evaluation order, // i.e. each ReDim clause operand is re-allocated prior to evaluating the next clause. // Mark the split ReDim operations as implicit if we have more than one ReDim clause. bool isImplicit = operation.Clauses.Length > 1 || IsImplicit(operation); foreach (var clause in operation.Clauses) { EvalStackFrame frame = PushStackFrame(); var visitedReDimClause = visitReDimClause(clause); var visitedReDimOperation = new ReDimOperation(ImmutableArray.Create(visitedReDimClause), operation.Preserve, semanticModel: null, operation.Syntax, isImplicit); AddStatement(visitedReDimOperation); PopStackFrameAndLeaveRegion(frame); } return FinishVisitingStatement(operation); IReDimClauseOperation visitReDimClause(IReDimClauseOperation clause) { PushOperand(VisitRequired(clause.Operand)); var visitedDimensionSizes = VisitArray(clause.DimensionSizes); var visitedOperand = PopOperand(); return new ReDimClauseOperation(visitedOperand, visitedDimensionSizes, semanticModel: null, clause.Syntax, IsImplicit(clause)); } } public override IOperation VisitReDimClause(IReDimClauseOperation operation, int? argument) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitTranslatedQuery(ITranslatedQueryOperation operation, int? captureIdForResult) { return new TranslatedQueryOperation(VisitRequired(operation.Operation), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitConstantPattern(IConstantPatternOperation operation, int? captureIdForResult) { return new ConstantPatternOperation(VisitRequired(operation.Value), operation.InputType, operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitRelationalPattern(IRelationalPatternOperation operation, int? argument) { return new RelationalPatternOperation( operatorKind: operation.OperatorKind, value: VisitRequired(operation.Value), inputType: operation.InputType, narrowedType: operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitBinaryPattern(IBinaryPatternOperation operation, int? argument) { return new BinaryPatternOperation( operatorKind: operation.OperatorKind, leftPattern: (IPatternOperation)VisitRequired(operation.LeftPattern), rightPattern: (IPatternOperation)VisitRequired(operation.RightPattern), inputType: operation.InputType, narrowedType: operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitNegatedPattern(INegatedPatternOperation operation, int? argument) { return new NegatedPatternOperation( pattern: (IPatternOperation)VisitRequired(operation.Pattern), inputType: operation.InputType, narrowedType: operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitTypePattern(ITypePatternOperation operation, int? argument) { return new TypePatternOperation( matchedType: operation.MatchedType, inputType: operation.InputType, narrowedType: operation.NarrowedType, semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitDeclarationPattern(IDeclarationPatternOperation operation, int? captureIdForResult) { return new DeclarationPatternOperation( operation.MatchedType, operation.MatchesNull, operation.DeclaredSymbol, operation.InputType, operation.NarrowedType, semanticModel: null, operation.Syntax, IsImplicit(operation)); } public override IOperation VisitRecursivePattern(IRecursivePatternOperation operation, int? argument) { return new RecursivePatternOperation( operation.MatchedType, operation.DeconstructSymbol, operation.DeconstructionSubpatterns.SelectAsArray((p, @this) => (IPatternOperation)@this.VisitRequired(p), this), operation.PropertySubpatterns.SelectAsArray((p, @this) => (IPropertySubpatternOperation)@this.VisitRequired(p), this), operation.DeclaredSymbol, operation.InputType, operation.NarrowedType, semanticModel: null, operation.Syntax, IsImplicit(operation)); } public override IOperation VisitPropertySubpattern(IPropertySubpatternOperation operation, int? argument) { return new PropertySubpatternOperation( VisitRequired(operation.Member), (IPatternOperation)VisitRequired(operation.Pattern), semanticModel: null, syntax: operation.Syntax, isImplicit: IsImplicit(operation)); } public override IOperation VisitDelegateCreation(IDelegateCreationOperation operation, int? captureIdForResult) { return new DelegateCreationOperation(VisitRequired(operation.Target), semanticModel: null, operation.Syntax, operation.Type, IsImplicit(operation)); } public override IOperation VisitRangeOperation(IRangeOperation operation, int? argument) { if (operation.LeftOperand is object) { PushOperand(VisitRequired(operation.LeftOperand)); } IOperation? visitedRightOperand = null; if (operation.RightOperand is object) { visitedRightOperand = Visit(operation.RightOperand); } IOperation? visitedLeftOperand = operation.LeftOperand is null ? null : PopOperand(); return new RangeOperation(visitedLeftOperand, visitedRightOperand, operation.IsLifted, operation.Method, semanticModel: null, operation.Syntax, operation.Type, isImplicit: IsImplicit(operation)); } public override IOperation VisitSwitchExpression(ISwitchExpressionOperation operation, int? captureIdForResult) { // expression switch { pat1 when g1 => e1, pat2 when g2 => e2 } // // becomes // // captureInput = expression // START scope 1 (arm1 locals) // GotoIfFalse (captureInput is pat1 && g1) label1; // captureOutput = e1 // goto afterSwitch // label1: // END scope 1 // START scope 2 // GotoIfFalse (captureInput is pat2 && g2) label2; // captureOutput = e2 // goto afterSwitch // label2: // END scope 2 // throw new switch failure // afterSwitch: // result = captureOutput INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); SpillEvalStack(); RegionBuilder resultCaptureRegion = CurrentRegionRequired; int captureOutput = captureIdForResult ?? GetNextCaptureId(resultCaptureRegion); var capturedInput = VisitAndCapture(operation.Value); var afterSwitch = new BasicBlockBuilder(BasicBlockKind.Block); foreach (var arm in operation.Arms) { // START scope (arm locals) var armScopeRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, locals: arm.Locals); EnterRegion(armScopeRegion); var afterArm = new BasicBlockBuilder(BasicBlockKind.Block); // GotoIfFalse (captureInput is pat1) label; { EvalStackFrame frame = PushStackFrame(); var visitedPattern = (IPatternOperation)VisitRequired(arm.Pattern); var patternTest = new IsPatternOperation( OperationCloner.CloneOperation(capturedInput), visitedPattern, semanticModel: null, arm.Syntax, booleanType, IsImplicit(arm)); ConditionalBranch(patternTest, jumpIfTrue: false, afterArm); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); } // GotoIfFalse (guard) afterArm; if (arm.Guard != null) { EvalStackFrame frame = PushStackFrame(); VisitConditionalBranch(arm.Guard, ref afterArm, jumpIfTrue: false); _currentBasicBlock = null; PopStackFrameAndLeaveRegion(frame); } // captureOutput = e VisitAndCapture(arm.Value, captureOutput); // goto afterSwitch UnconditionalBranch(afterSwitch); // afterArm: AppendNewBlock(afterArm); // END scope 1 LeaveRegion(); // armScopeRegion } LeaveRegionsUpTo(resultCaptureRegion); // throw new SwitchExpressionException var matchFailureCtor = (IMethodSymbol?)(_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor) ?? _compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_InvalidOperationException__ctor))?.GetISymbol(); var makeException = (matchFailureCtor is null) ? MakeInvalidOperation(operation.Syntax, type: _compilation.GetSpecialType(SpecialType.System_Object), ImmutableArray<IOperation>.Empty) : new ObjectCreationOperation( matchFailureCtor, initializer: null, ImmutableArray<IArgumentOperation>.Empty, semanticModel: null, operation.Syntax, type: matchFailureCtor.ContainingType, constantValue: null, isImplicit: true); LinkThrowStatement(makeException); _currentBasicBlock = null; // afterSwitch: AppendNewBlock(afterSwitch, linkToPrevious: false); // result = captureOutput return GetCaptureReference(captureOutput, operation); } private void VisitUsingVariableDeclarationOperation(IUsingDeclarationOperation operation, ReadOnlySpan<IOperation> statements) { IOperation? saveCurrentStatement = _currentStatement; _currentStatement = operation; StartVisitingStatement(operation); // a using statement introduces a 'logical' block after declaration, we synthesize one here in order to analyze it like a regular using. Don't include // local functions in this block: they still belong in the containing block. We'll visit any local functions in the list after we visit the statements // in this block. ArrayBuilder<IOperation> statementsBuilder = ArrayBuilder<IOperation>.GetInstance(statements.Length); ArrayBuilder<IOperation>? localFunctionsBuilder = null; foreach (var statement in statements) { if (statement.Kind == OperationKind.LocalFunction) { (localFunctionsBuilder ??= ArrayBuilder<IOperation>.GetInstance()).Add(statement); } else { statementsBuilder.Add(statement); } } BlockOperation logicalBlock = BlockOperation.CreateTemporaryBlock(statementsBuilder.ToImmutableAndFree(), ((Operation)operation).OwningSemanticModel!, operation.Syntax); DisposeOperationInfo disposeInfo = ((UsingDeclarationOperation)operation).DisposeInfo; HandleUsingOperationParts( resources: operation.DeclarationGroup, body: logicalBlock, disposeInfo.DisposeMethod, disposeInfo.DisposeArguments, locals: ImmutableArray<ILocalSymbol>.Empty, isAsynchronous: operation.IsAsynchronous); FinishVisitingStatement(operation); _currentStatement = saveCurrentStatement; if (localFunctionsBuilder != null) { VisitStatements(localFunctionsBuilder.ToImmutableAndFree()); } } public IOperation? Visit(IOperation? operation) { // We should never be revisiting nodes we've already visited, and we don't set SemanticModel in this builder. Debug.Assert(operation == null || ((Operation)operation).OwningSemanticModel!.Compilation == _compilation); return Visit(operation, argument: null); } [return: NotNullIfNotNull("operation")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public IOperation? VisitRequired(IOperation? operation, int? argument = null) { Debug.Assert(operation == null || ((Operation)operation).OwningSemanticModel!.Compilation == _compilation); var result = Visit(operation, argument); Debug.Assert((result == null) == (operation == null)); return result; } [return: NotNullIfNotNull("operation")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public IOperation? BaseVisitRequired(IOperation? operation, int? argument) { var result = base.Visit(operation, argument); Debug.Assert((result == null) == (operation == null)); return result; } public override IOperation? Visit(IOperation? operation, int? argument) { if (operation == null) { return null; } return PopStackFrame(PushStackFrame(), base.Visit(operation, argument)); } public override IOperation DefaultVisit(IOperation operation, int? captureIdForResult) { // this should never reach, otherwise, there is missing override for IOperation type throw ExceptionUtilities.Unreachable; } public override IOperation VisitArgument(IArgumentOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitUsingDeclaration(IUsingDeclarationOperation operation, int? captureIdForResult) { throw ExceptionUtilities.Unreachable; } public override IOperation VisitWith(IWithOperation operation, int? captureIdForResult) { if (operation.Type!.IsAnonymousType) { return handleAnonymousTypeWithExpression((WithOperation)operation, captureIdForResult); } EvalStackFrame frame = PushStackFrame(); // Initializer is removed from the tree and turned into a series of statements that assign to the cloned instance IOperation visitedInstance = VisitRequired(operation.Operand); IOperation cloned; if (operation.Type.IsValueType) { cloned = visitedInstance; } else { cloned = operation.CloneMethod is null ? MakeInvalidOperation(visitedInstance.Type, visitedInstance) : new InvocationOperation(operation.CloneMethod, visitedInstance, isVirtual: true, arguments: ImmutableArray<IArgumentOperation>.Empty, semanticModel: null, operation.Syntax, operation.Type, isImplicit: true); } return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, cloned)); // For `old with { Property = ... }` we're going to do the same as `new { Property = ..., OtherProperty = old.OtherProperty }` IOperation handleAnonymousTypeWithExpression(WithOperation operation, int? captureIdForResult) { Debug.Assert(operation.Type!.IsAnonymousType); SpillEvalStack(); // before entering a new region, we ensure that anything that needs spilling was spilled // The outer region holds captures for all the values for the anonymous object creation var outerCaptureRegion = CurrentRegionRequired; // The inner region holds the capture for the operand (ie. old value) var innerCaptureRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); EnterRegion(innerCaptureRegion); var initializers = operation.Initializer.Initializers; var properties = operation.Type.GetMembers() .Where(m => m.Kind == SymbolKind.Property) .Select(m => (IPropertySymbol)m); int oldValueCaptureId; if (setsAllProperties(initializers, properties)) { // Avoid capturing the old value since we won't need it oldValueCaptureId = -1; AddStatement(VisitRequired(operation.Operand)); } else { oldValueCaptureId = GetNextCaptureId(innerCaptureRegion); VisitAndCapture(operation.Operand, oldValueCaptureId); } // calls to Visit may enter regions, so we reset things LeaveRegionsUpTo(innerCaptureRegion); var explicitProperties = new Dictionary<IPropertySymbol, IOperation>(SymbolEqualityComparer.IgnoreAll); var initializerBuilder = ArrayBuilder<IOperation>.GetInstance(initializers.Length); // Visit and capture all the values, and construct assignments using capture references foreach (IOperation initializer in initializers) { if (initializer is not ISimpleAssignmentOperation simpleAssignment) { AddStatement(VisitRequired(initializer)); continue; } if (simpleAssignment.Target.Kind != OperationKind.PropertyReference) { Debug.Assert(simpleAssignment.Target is InvalidOperation); AddStatement(VisitRequired(simpleAssignment.Value)); continue; } var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Debug.Assert(propertyReference != null); Debug.Assert(propertyReference.Arguments.IsEmpty); Debug.Assert(propertyReference.Instance != null); Debug.Assert(propertyReference.Instance.Kind == OperationKind.InstanceReference); Debug.Assert(((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind == InstanceReferenceKind.ImplicitReceiver); var property = propertyReference.Property; if (explicitProperties.ContainsKey(property)) { AddStatement(VisitRequired(simpleAssignment.Value)); continue; } int valueCaptureId = GetNextCaptureId(outerCaptureRegion); VisitAndCapture(simpleAssignment.Value, valueCaptureId); LeaveRegionsUpTo(innerCaptureRegion); var valueCaptureRef = new FlowCaptureReferenceOperation(valueCaptureId, operation.Operand.Syntax, operation.Operand.Type, constantValue: operation.Operand.GetConstantValue()); var assignment = makeAssignment(property, valueCaptureRef, operation); explicitProperties.Add(property, assignment); } // Make a sequence for all properties (in order), constructing assignments for the implicitly set properties var type = (INamedTypeSymbol)operation.Type; foreach (IPropertySymbol property in properties) { if (explicitProperties.TryGetValue(property, out var assignment)) { initializerBuilder.Add(assignment); } else { Debug.Assert(oldValueCaptureId >= 0); // `oldInstance` var oldInstance = new FlowCaptureReferenceOperation(oldValueCaptureId, operation.Operand.Syntax, operation.Operand.Type, constantValue: operation.Operand.GetConstantValue()); // `oldInstance.Property` var visitedValue = new PropertyReferenceOperation(property, ImmutableArray<IArgumentOperation>.Empty, oldInstance, semanticModel: null, operation.Syntax, property.Type, isImplicit: true); int extraValueCaptureId = GetNextCaptureId(outerCaptureRegion); AddStatement(new FlowCaptureOperation(extraValueCaptureId, operation.Syntax, visitedValue)); var extraValueCaptureRef = new FlowCaptureReferenceOperation(extraValueCaptureId, operation.Operand.Syntax, operation.Operand.Type, constantValue: operation.Operand.GetConstantValue()); assignment = makeAssignment(property, extraValueCaptureRef, operation); initializerBuilder.Add(assignment); } } LeaveRegionsUpTo(outerCaptureRegion); return new AnonymousObjectCreationOperation(initializerBuilder.ToImmutableAndFree(), semanticModel: null, operation.Syntax, operation.Type, operation.IsImplicit); } // Build an operation for `<implicitReceiver>.Property = <capturedValue>` SimpleAssignmentOperation makeAssignment(IPropertySymbol property, IOperation capturedValue, WithOperation operation) { // <implicitReceiver> var implicitReceiver = new InstanceReferenceOperation(InstanceReferenceKind.ImplicitReceiver, semanticModel: null, operation.Syntax, operation.Type, isImplicit: true); // <implicitReceiver>.Property var target = new PropertyReferenceOperation(property, ImmutableArray<IArgumentOperation>.Empty, implicitReceiver, semanticModel: null, operation.Syntax, property.Type, isImplicit: true); // <implicitReceiver>.Property = <capturedValue> return new SimpleAssignmentOperation(isRef: false, target, capturedValue, semanticModel: null, operation.Syntax, property.Type, constantValue: null, isImplicit: true); } static bool setsAllProperties(ImmutableArray<IOperation> initializers, IEnumerable<IPropertySymbol> properties) { var set = new HashSet<IPropertySymbol>(SymbolEqualityComparer.IgnoreAll); foreach (var initializer in initializers) { if (initializer is not ISimpleAssignmentOperation simpleAssignment) { continue; } if (simpleAssignment.Target.Kind != OperationKind.PropertyReference) { Debug.Assert(simpleAssignment.Target is InvalidOperation); continue; } var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Debug.Assert(properties.Contains(propertyReference.Property, SymbolEqualityComparer.IgnoreAll)); set.Add(propertyReference.Property); } return set.Count == properties.Count(); } } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/Operations/InstanceReferenceKind.cs
// Licensed to the .NET Foundation under one or more 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.Operations { /// <summary> /// Kind of reference for an <see cref="IInstanceReferenceOperation"/>. /// </summary> public enum InstanceReferenceKind { /// <summary> /// Reference to an instance of the containing type. Used for <code>this</code> and <code>base</code> in C# code, and <code>Me</code>, /// <code>MyClass</code>, <code>MyBase</code> in VB code. /// </summary> ContainingTypeInstance, /// <summary> /// Reference to the object being initialized in C# or VB object or collection initializer, /// anonymous type creation initializer, or to the object being referred to in a VB With statement, /// or the C# 'with' expression initializer. /// </summary> ImplicitReceiver, /// <summary> /// Reference to the value being matching in a property subpattern. /// </summary> PatternInput, } }
// Licensed to the .NET Foundation under one or more 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.Operations { /// <summary> /// Kind of reference for an <see cref="IInstanceReferenceOperation"/>. /// </summary> public enum InstanceReferenceKind { /// <summary> /// Reference to an instance of the containing type. Used for <code>this</code> and <code>base</code> in C# code, and <code>Me</code>, /// <code>MyClass</code>, <code>MyBase</code> in VB code. /// </summary> ContainingTypeInstance, /// <summary> /// Reference to the object being initialized in C# or VB object or collection initializer, /// anonymous type creation initializer, or to the object being referred to in a VB With statement, /// or the C# 'with' expression initializer. /// </summary> ImplicitReceiver, /// <summary> /// Reference to the value being matching in a property subpattern. /// </summary> PatternInput, /// <summary> /// Reference to the interpolated string handler instance created as part of a parent interpolated string handler conversion. /// </summary> InterpolatedStringHandler, } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/Operations/OperationInterfaces.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Tree Root="IOperation"> <!-- To regenerate the operation nodes, run eng/generate-compiler-code.cmd The operations in this file are _ordered_! If you change the order in here, you will affect the ordering in the generated OperationKind enum, which will break the public api analyzer. All new types should be put at the end of this file in order to ensure that the kind does not continue to change. UnusedOperationKinds indicates kinds that are currently skipped by the OperationKind enum. They can be used by future nodes by inserting those nodes at the correct point in the list. When implementing new operations, run tests with additional IOperation validation enabled. You can test with `Build.cmd -testIOperation`. Or to repro in VS, you can do `set ROSLYN_TEST_IOPERATION=true` then `devenv`. --> <UnusedOperationKinds> <Entry Value="0x1D"/> <Entry Value="0x62"/> <Entry Value="0x64"/> </UnusedOperationKinds> <Node Name="IInvalidOperation" Base="IOperation" SkipClassGeneration="true"> <Comments> <summary> Represents an invalid operation with one or more child operations. <para> Current usage: (1) C# invalid expression or invalid statement. (2) VB invalid expression or invalid statement. </para> </summary> </Comments> </Node> <Node Name="IBlockOperation" Base="IOperation"> <Comments> <summary> Represents a block containing a sequence of operations and local declarations. <para> Current usage: (1) C# "{ ... }" block statement. (2) VB implicit block statement for method bodies and other block scoped statements. </para> </summary> </Comments> <Property Name="Operations" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Operations contained within the block.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Local declarations contained within the block.</summary> </Comments> </Property> </Node> <Node Name="IVariableDeclarationGroupOperation" Base="IOperation"> <Comments> <summary>Represents a variable declaration statement.</summary> <para> Current Usage: (1) C# local declaration statement (2) C# fixed statement (3) C# using statement (4) C# using declaration (5) VB Dim statement (6) VB Using statement </para> </Comments> <Property Name="Declarations" Type="ImmutableArray&lt;IVariableDeclarationOperation&gt;"> <Comments> <summary>Variable declaration in the statement.</summary> <remarks> In C#, this will always be a single declaration, with all variables in <see cref="IVariableDeclarationOperation.Declarators" />. </remarks> </Comments> </Property> </Node> <Node Name="ISwitchOperation" Base="IOperation" ChildrenOrder="Value,Cases"> <Comments> <summary> Represents a switch operation with a value to be switched upon and switch cases. <para> Current usage: (1) C# switch statement. (2) VB Select Case statement. </para> </summary> </Comments> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Locals declared within the switch operation with scope spanning across all <see cref="Cases" />. </summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to be switched upon.</summary> </Comments> </Property> <Property Name="Cases" Type="ImmutableArray&lt;ISwitchCaseOperation&gt;"> <Comments> <summary>Cases of the switch.</summary> </Comments> </Property> <Property Name="ExitLabel" Type="ILabelSymbol"> <Comments> <summary>Exit label for the switch statement.</summary> </Comments> </Property> </Node> <AbstractNode Name="ILoopOperation" Base="IOperation"> <OperationKind Include="true" ExtraDescription="This is further differentiated by &lt;see cref=&quot;ILoopOperation.LoopKind&quot;/&gt;." /> <Comments> <summary> Represents a loop operation. <para> Current usage: (1) C# 'while', 'for', 'foreach' and 'do' loop statements (2) VB 'While', 'ForTo', 'ForEach', 'Do While' and 'Do Until' loop statements </para> </summary> </Comments> <Property Name="LoopKind" Type="LoopKind" MakeAbstract="true"> <Comments> <summary>Kind of the loop.</summary> </Comments> </Property> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the loop.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Declared locals.</summary> </Comments> </Property> <Property Name="ContinueLabel" Type="ILabelSymbol"> <Comments> <summary>Loop continue label.</summary> </Comments> </Property> <Property Name="ExitLabel" Type="ILabelSymbol"> <Comments> <summary>Loop exit/break label.</summary> </Comments> </Property> </AbstractNode> <Node Name="IForEachLoopOperation" Base="ILoopOperation" ChildrenOrder="Collection,LoopControlVariable,Body,NextVariables"> <OperationKind Include="false" /> <Comments> <summary> Represents a for each loop. <para> Current usage: (1) C# 'foreach' loop statement (2) VB 'For Each' loop statement </para> </summary> </Comments> <Property Name="LoopControlVariable" Type="IOperation"> <Comments> <summary>Refers to the operation for declaring a new local variable or reference an existing variable or an expression.</summary> </Comments> </Property> <Property Name="Collection" Type="IOperation"> <Comments> <summary>Collection value over which the loop iterates.</summary> </Comments> </Property> <Property Name="NextVariables" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary> Optional list of comma separated next variables at loop bottom in VB. This list is always empty for C#. </summary> </Comments> </Property> <Property Name="Info" Type="ForEachLoopOperationInfo?" Internal="true" /> <Property Name="IsAsynchronous" Type="bool"> <Comments> <summary> Whether this for each loop is asynchronous. Always false for VB. </summary> </Comments> </Property> </Node> <Node Name="IForLoopOperation" Base="ILoopOperation" ChildrenOrder="Before,Condition,Body,AtLoopBottom"> <OperationKind Include="false" /> <Comments> <summary> Represents a for loop. <para> Current usage: (1) C# 'for' loop statement </para> </summary> </Comments> <Property Name="Before" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>List of operations to execute before entry to the loop. For C#, this comes from the first clause of the for statement.</summary> </Comments> </Property> <Property Name="ConditionLocals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Locals declared within the loop Condition and are in scope throughout the <see cref="Condition" />, <see cref="ILoopOperation.Body" /> and <see cref="AtLoopBottom" />. They are considered to be declared per iteration. </summary> </Comments> </Property> <Property Name="Condition" Type="IOperation?"> <Comments> <summary>Condition of the loop. For C#, this comes from the second clause of the for statement.</summary> </Comments> </Property> <Property Name="AtLoopBottom" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>List of operations to execute at the bottom of the loop. For C#, this comes from the third clause of the for statement.</summary> </Comments> </Property> </Node> <Node Name="IForToLoopOperation" Base="ILoopOperation" ChildrenOrder="LoopControlVariable,InitialValue,LimitValue,StepValue,Body,NextVariables"> <OperationKind Include="false" /> <Comments> <summary> Represents a for to loop with loop control variable and initial, limit and step values for the control variable. <para> Current usage: (1) VB 'For ... To ... Step' loop statement </para> </summary> </Comments> <Property Name="LoopControlVariable" Type="IOperation"> <Comments> <summary>Refers to the operation for declaring a new local variable or reference an existing variable or an expression.</summary> </Comments> </Property> <Property Name="InitialValue" Type="IOperation"> <Comments> <summary>Operation for setting the initial value of the loop control variable. This comes from the expression between the 'For' and 'To' keywords.</summary> </Comments> </Property> <Property Name="LimitValue" Type="IOperation"> <Comments> <summary>Operation for the limit value of the loop control variable. This comes from the expression after the 'To' keyword.</summary> </Comments> </Property> <Property Name="StepValue" Type="IOperation"> <Comments> <summary> Operation for the step value of the loop control variable. This comes from the expression after the 'Step' keyword, or inferred by the compiler if 'Step' clause is omitted. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <code>true</code> if arithmetic operations behind this loop are 'checked'.</summary> </Comments> </Property> <Property Name="NextVariables" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Optional list of comma separated next variables at loop bottom.</summary> </Comments> </Property> <Property Name="Info" Type="(ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo)" Internal="true" /> </Node> <Node Name="IWhileLoopOperation" Base="ILoopOperation" SkipChildrenGeneration="true"> <OperationKind Include="false" /> <Comments> <summary> Represents a while or do while loop. <para> Current usage: (1) C# 'while' and 'do while' loop statements. (2) VB 'While', 'Do While' and 'Do Until' loop statements. </para> </summary> </Comments> <Property Name="Condition" Type="IOperation?"> <Comments> <summary>Condition of the loop. This can only be null in error scenarios.</summary> </Comments> </Property> <Property Name="ConditionIsTop" Type="bool"> <Comments> <summary> True if the <see cref="Condition" /> is evaluated at start of each loop iteration. False if it is evaluated at the end of each loop iteration. </summary> </Comments> </Property> <Property Name="ConditionIsUntil" Type="bool"> <Comments> <summary>True if the loop has 'Until' loop semantics and the loop is executed while <see cref="Condition" /> is false.</summary> </Comments> </Property> <Property Name="IgnoredCondition" Type="IOperation?"> <Comments> <summary> Additional conditional supplied for loop in error cases, which is ignored by the compiler. For example, for VB 'Do While' or 'Do Until' loop with syntax errors where both the top and bottom conditions are provided. The top condition is preferred and exposed as <see cref="Condition" /> and the bottom condition is ignored and exposed by this property. This property should be null for all non-error cases. </summary> </Comments> </Property> </Node> <Node Name="ILabeledOperation" Base="IOperation"> <Comments> <summary> Represents an operation with a label. <para> Current usage: (1) C# labeled statement. (2) VB label statement. </para> </summary> </Comments> <Property Name="Label" Type="ILabelSymbol"> <Comments> <summary>Label that can be the target of branches.</summary> </Comments> </Property> <Property Name="Operation" Type="IOperation?"> <Comments> <summary>Operation that has been labeled. In VB, this is always null.</summary> </Comments> </Property> </Node> <Node Name="IBranchOperation" Base="IOperation"> <Comments> <summary> Represents a branch operation. <para> Current usage: (1) C# goto, break, or continue statement. (2) VB GoTo, Exit ***, or Continue *** statement. </para> </summary> </Comments> <Property Name="Target" Type="ILabelSymbol"> <Comments> <summary>Label that is the target of the branch.</summary> </Comments> </Property> <Property Name="BranchKind" Type="BranchKind"> <Comments> <summary>Kind of the branch.</summary> </Comments> </Property> </Node> <Node Name="IEmptyOperation" Base="IOperation"> <Comments> <summary> Represents an empty or no-op operation. <para> Current usage: (1) C# empty statement. </para> </summary> </Comments> </Node> <Node Name="IReturnOperation" Base="IOperation"> <OperationKind> <Entry Name="Return" Value="0x9"/> <Entry Name="YieldBreak" Value="0xa" ExtraDescription="This has yield break semantics."/> <Entry Name="YieldReturn" Value="0xe" ExtraDescription="This has yield return semantics."/> </OperationKind> <Comments> <summary> Represents a return from the method with an optional return value. <para> Current usage: (1) C# return statement and yield statement. (2) VB Return statement. </para> </summary> </Comments> <Property Name="ReturnedValue" Type="IOperation?"> <Comments> <summary>Value to be returned.</summary> </Comments> </Property> </Node> <Node Name="ILockOperation" Base="IOperation" ChildrenOrder="LockedValue,Body"> <Comments> <summary> Represents a <see cref="Body" /> of operations that are executed while holding a lock onto the <see cref="LockedValue" />. <para> Current usage: (1) C# lock statement. (2) VB SyncLock statement. </para> </summary> </Comments> <Property Name="LockedValue" Type="IOperation"> <Comments> <summary>Operation producing a value to be locked.</summary> </Comments> </Property> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the lock, to be executed while holding the lock.</summary> </Comments> </Property> <Property Name="LockTakenSymbol" Type="ILocalSymbol?" Internal="true"/> </Node> <Node Name="ITryOperation" Base="IOperation" ChildrenOrder="Body,Catches,Finally"> <Comments> <summary> Represents a try operation for exception handling code with a body, catch clauses and a finally handler. <para> Current usage: (1) C# try statement. (2) VB Try statement. </para> </summary> </Comments> <Property Name="Body" Type="IBlockOperation"> <Comments> <summary>Body of the try, over which the handlers are active.</summary> </Comments> </Property> <Property Name="Catches" Type="ImmutableArray&lt;ICatchClauseOperation&gt;"> <Comments> <summary>Catch clauses of the try.</summary> </Comments> </Property> <Property Name="Finally" Type="IBlockOperation?"> <Comments> <summary>Finally handler of the try.</summary> </Comments> </Property> <Property Name="ExitLabel" Type="ILabelSymbol?"> <Comments> <summary>Exit label for the try. This will always be null for C#.</summary> </Comments> </Property> </Node> <Node Name="IUsingOperation" Base="IOperation" ChildrenOrder="Resources,Body"> <Comments> <summary> Represents a <see cref="Body" /> of operations that are executed while using disposable <see cref="Resources" />. <para> Current usage: (1) C# using statement. (2) VB Using statement. </para> </summary> </Comments> <Property Name="Resources" Type="IOperation"> <Comments> <summary>Declaration introduced or resource held by the using.</summary> </Comments> </Property> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the using, over which the resources of the using are maintained.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Locals declared within the <see cref="Resources" /> with scope spanning across this entire <see cref="IUsingOperation" />. </summary> </Comments> </Property> <Property Name="IsAsynchronous" Type="bool"> <Comments> <summary> Whether this using is asynchronous. Always false for VB. </summary> </Comments> </Property> <Property Name="DisposeInfo" Type="DisposeOperationInfo" Internal="true"> <Comments> <summary>Information about the method that will be invoked to dispose the <see cref="Resources" /> when pattern based disposal is used.</summary> </Comments> </Property> </Node> <Node Name="IExpressionStatementOperation" Base="IOperation"> <Comments> <summary> Represents an operation that drops the resulting value and the type of the underlying wrapped <see cref="Operation" />. <para> Current usage: (1) C# expression statement. (2) VB expression statement. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Underlying operation with a value and type.</summary> </Comments> </Property> </Node> <Node Name="ILocalFunctionOperation" Base="IOperation" ChildrenOrder="Body,IgnoredBody"> <Comments> <summary> Represents a local function defined within a method. <para> Current usage: (1) C# local function statement. </para> </summary> </Comments> <Property Name="Symbol" Type="IMethodSymbol"> <Comments> <summary>Local function symbol.</summary> </Comments> </Property> <Property Name="Body" Type="IBlockOperation?"> <Comments> <summary>Body of the local function.</summary> <remarks>This can be null in error scenarios, or when the method is an extern method.</remarks> </Comments> </Property> <Property Name="IgnoredBody" Type="IBlockOperation?"> <Comments> <summary>An extra body for the local function, if both a block body and expression body are specified in source.</summary> <remarks>This is only ever non-null in error situations.</remarks> </Comments> </Property> </Node> <Node Name="IStopOperation" Base="IOperation"> <Comments> <summary> Represents an operation to stop or suspend execution of code. <para> Current usage: (1) VB Stop statement. </para> </summary> </Comments> </Node> <Node Name="IEndOperation" Base="IOperation"> <Comments> <summary> Represents an operation that stops the execution of code abruptly. <para> Current usage: (1) VB End Statement. </para> </summary> </Comments> </Node> <Node Name="IRaiseEventOperation" Base="IOperation" ChildrenOrder="EventReference,Arguments"> <Comments> <summary> Represents an operation for raising an event. <para> Current usage: (1) VB raise event statement. </para> </summary> </Comments> <Property Name="EventReference" Type="IEventReferenceOperation"> <Comments> <summary>Reference to the event to be raised.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IArgumentOperation&gt;"> <Comments> <summary>Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order.</summary> <remarks> If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. Default values are supplied for optional arguments missing in source. </remarks> </Comments> </Property> </Node> <Node Name="ILiteralOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a textual literal numeric, string, etc. <para> Current usage: (1) C# literal expression. (2) VB literal expression. </para> </summary> </Comments> </Node> <Node Name="IConversionOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a type conversion. <para> Current usage: (1) C# conversion expression. (2) VB conversion expression. </para> </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Value to be converted.</summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?" SkipGeneration="true"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> <Property Name="Conversion" Type="CommonConversion"> <Comments> <summary>Gets the underlying common conversion information.</summary> <remarks> If you need conversion information that is language specific, use either <see cref="T:Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetConversion(IConversionOperation)" /> or <see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.GetConversion(IConversionOperation)" />. </remarks> </Comments> </Property> <Property Name="IsTryCast" Type="bool"> <Comments> <summary> False if the conversion will fail with a <see cref="InvalidCastException" /> at runtime if the cast fails. This is true for C#'s <c>as</c> operator and for VB's <c>TryCast</c> operator. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary>True if the conversion can fail at runtime with an overflow exception. This corresponds to C# checked and unchecked blocks.</summary> </Comments> </Property> </Node> <Node Name="IInvocationOperation" Base="IOperation" ChildrenOrder="Instance,Arguments" HasType="true"> <Comments> <summary> Represents an invocation of a method. <para> Current usage: (1) C# method invocation expression. (2) C# collection element initializer. For example, in the following collection initializer: <code>new C() { 1, 2, 3 }</code>, we will have 3 <see cref="IInvocationOperation" /> nodes, each of which will be a call to the corresponding Add method with either 1, 2, 3 as the argument. (3) VB method invocation expression. (4) VB collection element initializer. Similar to the C# example, <code>New C() From {1, 2, 3}</code> will have 3 <see cref="IInvocationOperation" /> nodes with 1, 2, and 3 as their arguments, respectively. </para> </summary> </Comments> <Property Name="TargetMethod" Type="IMethodSymbol"> <Comments> <summary>Method to be invoked.</summary> </Comments> </Property> <Property Name="Instance" Type="IOperation?"> <Comments> <summary>'This' or 'Me' instance to be supplied to the method, or null if the method is static.</summary> </Comments> </Property> <Property Name="IsVirtual" Type="bool"> <Comments> <summary>True if the invocation uses a virtual mechanism, and false otherwise.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IArgumentOperation&gt;"> <Comments> <summary>Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order.</summary> <remarks> If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. Default values are supplied for optional arguments missing in source. </remarks> </Comments> </Property> </Node> <Node Name="IArrayElementReferenceOperation" Base="IOperation" ChildrenOrder="ArrayReference,Indices" HasType="true"> <Comments> <summary> Represents a reference to an array element. <para> Current usage: (1) C# array element reference expression. (2) VB array element reference expression. </para> </summary> </Comments> <Property Name="ArrayReference" Type="IOperation"> <Comments> <summary>Array to be indexed.</summary> </Comments> </Property> <Property Name="Indices" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Indices that specify an individual element.</summary> </Comments> </Property> </Node> <Node Name="ILocalReferenceOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a reference to a declared local variable. <para> Current usage: (1) C# local reference expression. (2) VB local reference expression. </para> </summary> </Comments> <Property Name="Local" Type="ILocalSymbol"> <Comments> <summary>Referenced local variable.</summary> </Comments> </Property> <Property Name="IsDeclaration" Type="bool"> <Comments> <summary> True if this reference is also the declaration site of this variable. This is true in out variable declarations and in deconstruction operations where a new variable is being declared. </summary> </Comments> </Property> </Node> <Node Name="IParameterReferenceOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a reference to a parameter. <para> Current usage: (1) C# parameter reference expression. (2) VB parameter reference expression. </para> </summary> </Comments> <Property Name="Parameter" Type="IParameterSymbol"> <Comments> <summary>Referenced parameter.</summary> </Comments> </Property> </Node> <AbstractNode Name="IMemberReferenceOperation" Base="IOperation" > <Comments> <summary> Represents a reference to a member of a class, struct, or interface. <para> Current usage: (1) C# member reference expression. (2) VB member reference expression. </para> </summary> </Comments> <Property Name="Instance" Type="IOperation?"> <Comments> <summary>Instance of the type. Null if the reference is to a static/shared member.</summary> </Comments> </Property> <Property Name="Member" Type="ISymbol" SkipGeneration="true"> <Comments> <summary>Referenced member.</summary> </Comments> </Property> </AbstractNode> <Node Name="IFieldReferenceOperation" Base="IMemberReferenceOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a reference to a field. <para> Current usage: (1) C# field reference expression. (2) VB field reference expression. </para> </summary> </Comments> <Property Name="Field" Type="IFieldSymbol"> <Comments> <summary>Referenced field.</summary> </Comments> </Property> <Property Name="IsDeclaration" Type="bool"> <Comments> <summary>If the field reference is also where the field was declared.</summary> <remarks> This is only ever true in CSharp scripts, where a top-level statement creates a new variable in a reference, such as an out variable declaration or a deconstruction declaration. </remarks> </Comments> </Property> </Node> <Node Name="IMethodReferenceOperation" Base="IMemberReferenceOperation" HasType="true"> <Comments> <summary> Represents a reference to a method other than as the target of an invocation. <para> Current usage: (1) C# method reference expression. (2) VB method reference expression. </para> </summary> </Comments> <Property Name="Method" Type="IMethodSymbol"> <Comments> <summary>Referenced method.</summary> </Comments> </Property> <Property Name="IsVirtual" Type="bool"> <Comments> <summary>Indicates whether the reference uses virtual semantics.</summary> </Comments> </Property> </Node> <Node Name="IPropertyReferenceOperation" Base="IMemberReferenceOperation" ChildrenOrder="Instance,Arguments" HasType="true"> <Comments> <summary> Represents a reference to a property. <para> Current usage: (1) C# property reference expression. (2) VB property reference expression. </para> </summary> </Comments> <Property Name="Property" Type="IPropertySymbol"> <Comments> <summary>Referenced property.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IArgumentOperation&gt;"> <Comments> <summary>Arguments of the indexer property reference, excluding the instance argument. Arguments are in evaluation order.</summary> <remarks> If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. Default values are supplied for optional arguments missing in source. </remarks> </Comments> </Property> </Node> <Node Name="IEventReferenceOperation" Base="IMemberReferenceOperation" HasType="true"> <Comments> <summary> Represents a reference to an event. <para> Current usage: (1) C# event reference expression. (2) VB event reference expression. </para> </summary> </Comments> <Property Name="Event" Type="IEventSymbol"> <Comments> <summary>Referenced event.</summary> </Comments> </Property> </Node> <Node Name="IUnaryOperation" Base="IOperation" VisitorName="VisitUnaryOperator" HasType="true" HasConstantValue="true"> <OperationKind> <Entry Name="Unary" Value="0x1f" /> <Entry Name="UnaryOperator" Value="0x1f" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;Unary&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents an operation with one operand and a unary operator. <para> Current usage: (1) C# unary operation expression. (2) VB unary operation expression. </para> </summary> </Comments> <Property Name="OperatorKind" Type="UnaryOperatorKind"> <Comments> <summary>Kind of unary operation.</summary> </Comments> </Property> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Operand.</summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a 'lifted' unary operator. When there is an operator that is defined to work on a value type, 'lifted' operators are created to work on the <see cref="System.Nullable{T}" /> versions of those value types. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <see langword="true" /> if overflow checking is performed for the arithmetic operation. </summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> </Node> <Node Name="IBinaryOperation" Base="IOperation" VisitorName="VisitBinaryOperator" ChildrenOrder="LeftOperand,RightOperand" HasType="true" HasConstantValue="true"> <OperationKind> <Entry Name="Binary" Value="0x20" /> <Entry Name="BinaryOperator" Value="0x20" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;Binary&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents an operation with two operands and a binary operator that produces a result with a non-null type. <para> Current usage: (1) C# binary operator expression. (2) VB binary operator expression. </para> </summary> </Comments> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>Kind of binary operation.</summary> </Comments> </Property> <Property Name="LeftOperand" Type="IOperation"> <Comments> <summary>Left operand.</summary> </Comments> </Property> <Property Name="RightOperand" Type="IOperation"> <Comments> <summary>Right operand.</summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a 'lifted' binary operator. When there is an operator that is defined to work on a value type, 'lifted' operators are created to work on the <see cref="System.Nullable{T}" /> versions of those value types. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a 'checked' binary operator. </summary> </Comments> </Property> <Property Name="IsCompareText" Type="bool"> <Comments> <summary> <see langword="true" /> if the comparison is text based for string or object comparison in VB. </summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> <Property Name="UnaryOperatorMethod" Type="IMethodSymbol?" Internal="true"> <Comments> <summary> True/False operator method used for short circuiting. https://github.com/dotnet/roslyn/issues/27598 tracks exposing this information through public API </summary> </Comments> </Property> </Node> <Node Name="IConditionalOperation" Base="IOperation" ChildrenOrder="Condition,WhenTrue,WhenFalse" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a conditional operation with: (1) <see cref="Condition" /> to be tested, (2) <see cref="WhenTrue" /> operation to be executed when <see cref="Condition" /> is true and (3) <see cref="WhenFalse" /> operation to be executed when the <see cref="Condition" /> is false. <para> Current usage: (1) C# ternary expression "a ? b : c" and if statement. (2) VB ternary expression "If(a, b, c)" and If Else statement. </para> </summary> </Comments> <Property Name="Condition" Type="IOperation"> <Comments> <summary>Condition to be tested.</summary> </Comments> </Property> <Property Name="WhenTrue" Type="IOperation"> <Comments> <summary> Operation to be executed if the <see cref="Condition" /> is true. </summary> </Comments> </Property> <Property Name="WhenFalse" Type="IOperation?"> <Comments> <summary> Operation to be executed if the <see cref="Condition" /> is false. </summary> </Comments> </Property> <Property Name="IsRef" Type="bool"> <Comments> <summary>Is result a managed reference</summary> </Comments> </Property> </Node> <Node Name="ICoalesceOperation" Base="IOperation" ChildrenOrder="Value,WhenNull" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a coalesce operation with two operands: (1) <see cref="Value" />, which is the first operand that is unconditionally evaluated and is the result of the operation if non null. (2) <see cref="WhenNull" />, which is the second operand that is conditionally evaluated and is the result of the operation if <see cref="Value" /> is null. <para> Current usage: (1) C# null-coalescing expression "Value ?? WhenNull". (2) VB binary conditional expression "If(Value, WhenNull)". </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Operation to be unconditionally evaluated.</summary> </Comments> </Property> <Property Name="WhenNull" Type="IOperation"> <Comments> <summary> Operation to be conditionally evaluated if <see cref="Value" /> evaluates to null/Nothing. </summary> </Comments> </Property> <Property Name="ValueConversion" Type="CommonConversion"> <Comments> <summary> Conversion associated with <see cref="Value" /> when it is not null/Nothing. Identity if result type of the operation is the same as type of <see cref="Value" />. Otherwise, if type of <see cref="Value" /> is nullable, then conversion is applied to an unwrapped <see cref="Value" />, otherwise to the <see cref="Value" /> itself. </summary> </Comments> </Property> </Node> <Node Name="IAnonymousFunctionOperation" Base="IOperation"> <!-- IAnonymousFunctionOperations do not have a type, users must look at the IConversionOperation on top of this node to get the type of lambda, matching SemanticModel.GetType behavior. --> <Comments> <summary> Represents an anonymous function operation. <para> Current usage: (1) C# lambda expression. (2) VB anonymous delegate expression. </para> </summary> </Comments> <Property Name="Symbol" Type="IMethodSymbol"> <Comments> <summary>Symbol of the anonymous function.</summary> </Comments> </Property> <Property Name="Body" Type="IBlockOperation"> <Comments> <summary>Body of the anonymous function.</summary> </Comments> </Property> </Node> <Node Name="IObjectCreationOperation" Base="IOperation" ChildrenOrder="Arguments,Initializer" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents creation of an object instance. <para> Current usage: (1) C# new expression. (2) VB New expression. </para> </summary> </Comments> <Property Name="Constructor" Type="IMethodSymbol?"> <Comments> <summary>Constructor to be invoked on the created instance.</summary> </Comments> </Property> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?"> <Comments> <summary>Object or collection initializer, if any.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IArgumentOperation&gt;"> <Comments> <summary>Arguments of the object creation, excluding the instance argument. Arguments are in evaluation order.</summary> <remarks> If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. Default values are supplied for optional arguments missing in source. </remarks> </Comments> </Property> </Node> <Node Name="ITypeParameterObjectCreationOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a creation of a type parameter object, i.e. new T(), where T is a type parameter with new constraint. <para> Current usage: (1) C# type parameter object creation expression. (2) VB type parameter object creation expression. </para> </summary> </Comments> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?"> <Comments> <summary>Object or collection initializer, if any.</summary> </Comments> </Property> </Node> <Node Name="IArrayCreationOperation" Base="IOperation" ChildrenOrder="DimensionSizes,Initializer" HasType="true"> <Comments> <summary> Represents the creation of an array instance. <para> Current usage: (1) C# array creation expression. (2) VB array creation expression. </para> </summary> </Comments> <Property Name="DimensionSizes" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Sizes of the dimensions of the created array instance.</summary> </Comments> </Property> <Property Name="Initializer" Type="IArrayInitializerOperation?"> <Comments> <summary>Values of elements of the created array instance.</summary> </Comments> </Property> </Node> <Node Name="IInstanceReferenceOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an implicit/explicit reference to an instance. <para> Current usage: (1) C# this or base expression. (2) VB Me, MyClass, or MyBase expression. (3) C# object or collection or 'with' expression initializers. (4) VB With statements, object or collection initializers. </para> </summary> </Comments> <Property Name="ReferenceKind" Type="InstanceReferenceKind"> <Comments> <summary>The kind of reference that is being made.</summary> </Comments> </Property> </Node> <Node Name="IIsTypeOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an operation that tests if a value is of a specific type. <para> Current usage: (1) C# "is" operator expression. (2) VB "TypeOf" and "TypeOf IsNot" expression. </para> </summary> </Comments> <Property Name="ValueOperand" Type="IOperation"> <Comments> <summary>Value to test.</summary> </Comments> </Property> <Property Name="TypeOperand" Type="ITypeSymbol"> <Comments> <summary>Type for which to test.</summary> </Comments> </Property> <Property Name="IsNegated" Type="bool"> <Comments> <summary> Flag indicating if this is an "is not" type expression. True for VB "TypeOf ... IsNot ..." expression. False, otherwise. </summary> </Comments> </Property> </Node> <Node Name="IAwaitOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an await operation. <para> Current usage: (1) C# await expression. (2) VB await expression. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Awaited operation.</summary> </Comments> </Property> </Node> <AbstractNode Name="IAssignmentOperation" Base="IOperation"> <Comments> <summary> Represents a base interface for assignments. <para> Current usage: (1) C# simple, compound and deconstruction assignment expressions. (2) VB simple and compound assignment expressions. </para> </summary> </Comments> <Property Name="Target" Type="IOperation"> <Comments> <summary>Target of the assignment.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to be assigned to the target of the assignment.</summary> </Comments> </Property> </AbstractNode> <Node Name="ISimpleAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a simple assignment operation. <para> Current usage: (1) C# simple assignment expression. (2) VB simple assignment expression. </para> </summary> </Comments> <Property Name="IsRef" Type="bool"> <Comments> <summary>Is this a ref assignment</summary> </Comments> </Property> </Node> <Node Name="ICompoundAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true"> <Comments> <summary> Represents a compound assignment that mutates the target with the result of a binary operation. <para> Current usage: (1) C# compound assignment expression. (2) VB compound assignment expression. </para> </summary> </Comments> <Property Name="InConversion" Type="CommonConversion"> <Comments> <summary> Conversion applied to <see cref="IAssignmentOperation.Target" /> before the operation occurs. </summary> </Comments> </Property> <Property Name="OutConversion" Type="CommonConversion"> <Comments> <summary> Conversion applied to the result of the binary operation, before it is assigned back to <see cref="IAssignmentOperation.Target" />. </summary> </Comments> </Property> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>Kind of binary operation.</summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <see langword="true" /> if this assignment contains a 'lifted' binary operation. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <see langword="true" /> if overflow checking is performed for the arithmetic operation. </summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> </Node> <Node Name="IParenthesizedOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a parenthesized operation. <para> Current usage: (1) VB parenthesized expression. </para> </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Operand enclosed in parentheses.</summary> </Comments> </Property> </Node> <Node Name="IEventAssignmentOperation" Base="IOperation" ChildrenOrder="EventReference,HandlerValue" HasType="true"> <Comments> <summary> Represents a binding of an event. <para> Current usage: (1) C# event assignment expression. (2) VB Add/Remove handler statement. </para> </summary> </Comments> <Property Name="EventReference" Type="IOperation"> <Comments> <summary>Reference to the event being bound.</summary> </Comments> </Property> <Property Name="HandlerValue" Type="IOperation"> <Comments> <summary>Handler supplied for the event.</summary> </Comments> </Property> <Property Name="Adds" Type="bool"> <Comments> <summary>True for adding a binding, false for removing one.</summary> </Comments> </Property> </Node> <Node Name="IConditionalAccessOperation" Base="IOperation" ChildrenOrder="Operation,WhenNotNull" HasType="true"> <Comments> <summary> Represents a conditionally accessed operation. Note that <see cref="IConditionalAccessInstanceOperation" /> is used to refer to the value of <see cref="Operation" /> within <see cref="WhenNotNull" />. <para> Current usage: (1) C# conditional access expression (? or ?. operator). (2) VB conditional access expression (? or ?. operator). </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Operation that will be evaluated and accessed if non null.</summary> </Comments> </Property> <Property Name="WhenNotNull" Type="IOperation"> <Comments> <summary> Operation to be evaluated if <see cref="Operation" /> is non null. </summary> </Comments> </Property> </Node> <Node Name="IConditionalAccessInstanceOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents the value of a conditionally-accessed operation within <see cref="IConditionalAccessOperation.WhenNotNull" />. For a conditional access operation of the form <c>someExpr?.Member</c>, this operation is used as the InstanceReceiver for the right operation <c>Member</c>. See https://github.com/dotnet/roslyn/issues/21279#issuecomment-323153041 for more details. <para> Current usage: (1) C# conditional access instance expression. (2) VB conditional access instance expression. </para> </summary> </Comments> </Node> <Node Name="IInterpolatedStringOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents an interpolated string. <para> Current usage: (1) C# interpolated string expression. (2) VB interpolated string expression. </para> </summary> </Comments> <Property Name="Parts" Type="ImmutableArray&lt;IInterpolatedStringContentOperation&gt;"> <Comments> <summary> Constituent parts of interpolated string, each of which is an <see cref="IInterpolatedStringContentOperation" />. </summary> </Comments> </Property> </Node> <Node Name="IAnonymousObjectCreationOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a creation of anonymous object. <para> Current usage: (1) C# "new { ... }" expression (2) VB "New With { ... }" expression </para> </summary> </Comments> <Property Name="Initializers" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary> Property initializers. Each initializer is an <see cref="ISimpleAssignmentOperation" />, with an <see cref="IPropertyReferenceOperation" /> as the target whose Instance is an <see cref="IInstanceReferenceOperation" /> with <see cref="InstanceReferenceKind.ImplicitReceiver" /> kind. </summary> </Comments> </Property> </Node> <Node Name="IObjectOrCollectionInitializerOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an initialization for an object or collection creation. <para> Current usage: (1) C# object or collection initializer expression. (2) VB object or collection initializer expression. For example, object initializer "{ X = x }" within object creation "new Class() { X = x }" and collection initializer "{ x, y, 3 }" within collection creation "new MyList() { x, y, 3 }". </para> </summary> </Comments> <Property Name="Initializers" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Object member or collection initializers.</summary> </Comments> </Property> </Node> <Node Name="IMemberInitializerOperation" Base="IOperation" ChildrenOrder="InitializedMember,Initializer" HasType="true"> <Comments> <summary> Represents an initialization of member within an object initializer with a nested object or collection initializer. <para> Current usage: (1) C# nested member initializer expression. For example, given an object creation with initializer "new Class() { X = x, Y = { x, y, 3 }, Z = { X = z } }", member initializers for Y and Z, i.e. "Y = { x, y, 3 }", and "Z = { X = z }" are nested member initializers represented by this operation. </para> </summary> </Comments> <Property Name="InitializedMember" Type="IOperation"> <Comments> <summary> Initialized member reference <see cref="IMemberReferenceOperation" /> or an invalid operation for error cases. </summary> </Comments> </Property> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation"> <Comments> <summary>Member initializer.</summary> </Comments> </Property> </Node> <Node Name="ICollectionElementInitializerOperation" Base="IOperation" SkipClassGeneration="true"> <Obsolete Error="true">"ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation)</Obsolete> <Comments> <summary> Obsolete interface that used to represent a collection element initializer. It has been replaced by <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />, as appropriate. <para> Current usage: None. This API has been obsoleted in favor of <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />. </para> </summary> </Comments> <Property Name="AddMethod" Type="IMethodSymbol" /> <Property Name="Arguments" Type="ImmutableArray&lt;IOperation&gt;" /> <Property Name="IsDynamic" Type="bool" /> </Node> <Node Name="INameOfOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents an operation that gets a string value for the <see cref="Argument" /> name. <para> Current usage: (1) C# nameof expression. (2) VB NameOf expression. </para> </summary> </Comments> <Property Name="Argument" Type="IOperation"> <Comments> <summary>Argument to the name of operation.</summary> </Comments> </Property> </Node> <Node Name="ITupleOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a tuple with one or more elements. <para> Current usage: (1) C# tuple expression. (2) VB tuple expression. </para> </summary> </Comments> <Property Name="Elements" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Tuple elements.</summary> </Comments> </Property> <Property Name="NaturalType" Type="ITypeSymbol?"> <Comments> <summary> Natural type of the tuple, or null if tuple doesn't have a natural type. Natural type can be different from <see cref="IOperation.Type" /> depending on the conversion context, in which the tuple is used. </summary> </Comments> </Property> </Node> <Node Name="IDynamicObjectCreationOperation" Base="IOperation" SkipClassGeneration="true"> <Comments> <summary> Represents an object creation with a dynamically bound constructor. <para> Current usage: (1) C# "new" expression with dynamic argument(s). (2) VB late bound "New" expression. </para> </summary> </Comments> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?"> <Comments> <summary>Object or collection initializer, if any.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Dynamically bound arguments, excluding the instance argument.</summary> </Comments> </Property> </Node> <Node Name="IDynamicMemberReferenceOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a reference to a member of a class, struct, or module that is dynamically bound. <para> Current usage: (1) C# dynamic member reference expression. (2) VB late bound member reference expression. </para> </summary> </Comments> <Property Name="Instance" Type="IOperation?"> <Comments> <summary>Instance receiver, if it exists.</summary> </Comments> </Property> <Property Name="MemberName" Type="string"> <Comments> <summary>Referenced member.</summary> </Comments> </Property> <Property Name="TypeArguments" Type="ImmutableArray&lt;ITypeSymbol&gt;"> <Comments> <summary>Type arguments.</summary> </Comments> </Property> <Property Name="ContainingType" Type="ITypeSymbol?"> <Comments> <summary> The containing type of the referenced member, if different from type of the <see cref="Instance" />. </summary> </Comments> </Property> </Node> <Node Name="IDynamicInvocationOperation" Base="IOperation" SkipClassGeneration="true"> <Comments> <summary> Represents a invocation that is dynamically bound. <para> Current usage: (1) C# dynamic invocation expression. (2) C# dynamic collection element initializer. For example, in the following collection initializer: <code>new C() { do1, do2, do3 }</code> where the doX objects are of type dynamic, we'll have 3 <see cref="IDynamicInvocationOperation" /> with do1, do2, and do3 as their arguments. (3) VB late bound invocation expression. (4) VB dynamic collection element initializer. Similar to the C# example, <code>New C() From {do1, do2, do3}</code> will generate 3 <see cref="IDynamicInvocationOperation" /> nodes with do1, do2, and do3 as their arguments, respectively. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Dynamically or late bound operation.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Dynamically bound arguments, excluding the instance argument.</summary> </Comments> </Property> </Node> <Node Name="IDynamicIndexerAccessOperation" Base="IOperation" SkipClassGeneration="true"> <Comments> <summary> Represents an indexer access that is dynamically bound. <para> Current usage: (1) C# dynamic indexer access expression. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Dynamically indexed operation.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Dynamically bound arguments, excluding the instance argument.</summary> </Comments> </Property> </Node> <Node Name="ITranslatedQueryOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an unrolled/lowered query operation. For example, for a C# query expression "from x in set where x.Name != null select x.Name", the Operation tree has the following shape: ITranslatedQueryExpression IInvocationExpression ('Select' invocation for "select x.Name") IInvocationExpression ('Where' invocation for "where x.Name != null") IInvocationExpression ('From' invocation for "from x in set") <para> Current usage: (1) C# query expression. (2) VB query expression. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Underlying unrolled operation.</summary> </Comments> </Property> </Node> <Node Name="IDelegateCreationOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a delegate creation. This is created whenever a new delegate is created. <para> Current usage: (1) C# delegate creation expression. (2) VB delegate creation expression. </para> </summary> </Comments> <Property Name="Target" Type="IOperation"> <Comments> <summary>The lambda or method binding that this delegate is created from.</summary> </Comments> </Property> </Node> <Node Name="IDefaultValueOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a default value operation. <para> Current usage: (1) C# default value expression. </para> </summary> </Comments> </Node> <Node Name="ITypeOfOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an operation that gets <see cref="System.Type" /> for the given <see cref="TypeOperand" />. <para> Current usage: (1) C# typeof expression. (2) VB GetType expression. </para> </summary> </Comments> <Property Name="TypeOperand" Type="ITypeSymbol"> <Comments> <summary>Type operand.</summary> </Comments> </Property> </Node> <Node Name="ISizeOfOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents an operation to compute the size of a given type. <para> Current usage: (1) C# sizeof expression. </para> </summary> </Comments> <Property Name="TypeOperand" Type="ITypeSymbol"> <Comments> <summary>Type operand.</summary> </Comments> </Property> </Node> <Node Name="IAddressOfOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an operation that creates a pointer value by taking the address of a reference. <para> Current usage: (1) C# address of expression </para> </summary> </Comments> <Property Name="Reference" Type="IOperation"> <Comments> <summary>Addressed reference.</summary> </Comments> </Property> </Node> <Node Name="IIsPatternOperation" Base="IOperation" ChildrenOrder="Value,Pattern" HasType="true"> <Comments> <summary> Represents an operation that tests if a value matches a specific pattern. <para> Current usage: (1) C# is pattern expression. For example, "x is int i". </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Underlying operation to test.</summary> </Comments> </Property> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>Pattern.</summary> </Comments> </Property> </Node> <Node Name="IIncrementOrDecrementOperation" Base="IOperation" HasType="true"> <OperationKind> <Entry Name="Increment" Value="0x42" ExtraDescription="This is used as an increment operator"/> <Entry Name="Decrement" Value="0x44" ExtraDescription="This is used as a decrement operator"/> </OperationKind> <Comments> <summary> Represents an <see cref="OperationKind.Increment" /> or <see cref="OperationKind.Decrement" /> operation. Note that this operation is different from an <see cref="IUnaryOperation" /> as it mutates the <see cref="Target" />, while unary operator expression does not mutate it's operand. <para> Current usage: (1) C# increment expression or decrement expression. </para> </summary> </Comments> <Property Name="IsPostfix" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a postfix expression. <see langword="false" /> if this is a prefix expression. </summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a 'lifted' increment operator. When there is an operator that is defined to work on a value type, 'lifted' operators are created to work on the <see cref="System.Nullable{T}" /> versions of those value types. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <see langword="true" /> if overflow checking is performed for the arithmetic operation. </summary> </Comments> </Property> <Property Name="Target" Type="IOperation"> <Comments> <summary>Target of the assignment.</summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> </Node> <Node Name="IThrowOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an operation to throw an exception. <para> Current usage: (1) C# throw expression. (2) C# throw statement. (2) VB Throw statement. </para> </summary> </Comments> <Property Name="Exception" Type="IOperation?"> <Comments> <summary>Instance of an exception being thrown.</summary> </Comments> </Property> </Node> <Node Name="IDeconstructionAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true"> <Comments> <summary> Represents a assignment with a deconstruction. <para> Current usage: (1) C# deconstruction assignment expression. </para> </summary> </Comments> </Node> <Node Name="IDeclarationExpressionOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a declaration expression operation. Unlike a regular variable declaration <see cref="IVariableDeclaratorOperation" /> and <see cref="IVariableDeclarationOperation" />, this operation represents an "expression" declaring a variable. <para> Current usage: (1) C# declaration expression. For example, (a) "var (x, y)" is a deconstruction declaration expression with variables x and y. (b) "(var x, var y)" is a tuple expression with two declaration expressions. (c) "M(out var x);" is an invocation expression with an out "var x" declaration expression. </para> </summary> </Comments> <Property Name="Expression" Type="IOperation"> <Comments> <summary>Underlying expression.</summary> </Comments> </Property> </Node> <Node Name="IOmittedArgumentOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an argument value that has been omitted in an invocation. <para> Current usage: (1) VB omitted argument in an invocation expression. </para> </summary> </Comments> </Node> <AbstractNode Name="ISymbolInitializerOperation" Base="IOperation"> <Comments> <summary> Represents an initializer for a field, property, parameter or a local variable declaration. <para> Current usage: (1) C# field, property, parameter or local variable initializer. (2) VB field(s), property, parameter or local variable initializer. </para> </summary> </Comments> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Local declared in and scoped to the <see cref="Value" />. </summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Underlying initializer value.</summary> </Comments> </Property> </AbstractNode> <Node Name="IFieldInitializerOperation" Base="ISymbolInitializerOperation"> <Comments> <summary> Represents an initialization of a field. <para> Current usage: (1) C# field initializer with equals value clause. (2) VB field(s) initializer with equals value clause or AsNew clause. Multiple fields can be initialized with AsNew clause in VB. </para> </summary> </Comments> <Property Name="InitializedFields" Type="ImmutableArray&lt;IFieldSymbol&gt;"> <Comments> <summary>Initialized fields. There can be multiple fields for Visual Basic fields declared with AsNew clause.</summary> </Comments> </Property> </Node> <Node Name="IVariableInitializerOperation" Base="ISymbolInitializerOperation"> <Comments> <summary> Represents an initialization of a local variable. <para> Current usage: (1) C# local variable initializer with equals value clause. (2) VB local variable initializer with equals value clause or AsNew clause. </para> </summary> </Comments> </Node> <Node Name="IPropertyInitializerOperation" Base="ISymbolInitializerOperation"> <Comments> <summary> Represents an initialization of a property. <para> Current usage: (1) C# property initializer with equals value clause. (2) VB property initializer with equals value clause or AsNew clause. Multiple properties can be initialized with 'WithEvents' declaration with AsNew clause in VB. </para> </summary> </Comments> <Property Name="InitializedProperties" Type="ImmutableArray&lt;IPropertySymbol&gt;"> <Comments> <summary>Initialized properties. There can be multiple properties for Visual Basic 'WithEvents' declaration with AsNew clause.</summary> </Comments> </Property> </Node> <Node Name="IParameterInitializerOperation" Base="ISymbolInitializerOperation"> <Comments> <summary> Represents an initialization of a parameter at the point of declaration. <para> Current usage: (1) C# parameter initializer with equals value clause. (2) VB parameter initializer with equals value clause. </para> </summary> </Comments> <Property Name="Parameter" Type="IParameterSymbol"> <Comments> <summary>Initialized parameter.</summary> </Comments> </Property> </Node> <Node Name="IArrayInitializerOperation" Base="IOperation"> <Comments> <summary> Represents the initialization of an array instance. <para> Current usage: (1) C# array initializer. (2) VB array initializer. </para> </summary> </Comments> <Property Name="ElementValues" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Values to initialize array elements.</summary> </Comments> </Property> </Node> <Node Name="IVariableDeclaratorOperation" Base="IOperation" ChildrenOrder="IgnoredArguments,Initializer"> <Comments> <summary>Represents a single variable declarator and initializer.</summary> <para> Current Usage: (1) C# variable declarator (2) C# catch variable declaration (3) VB single variable declaration (4) VB catch variable declaration </para> <remarks> In VB, the initializer for this node is only ever used for explicit array bounds initializers. This node corresponds to the VariableDeclaratorSyntax in C# and the ModifiedIdentifierSyntax in VB. </remarks> </Comments> <Property Name="Symbol" Type="ILocalSymbol"> <Comments> <summary>Symbol declared by this variable declaration</summary> </Comments> </Property> <Property Name="Initializer" Type="IVariableInitializerOperation?"> <Comments> <summary>Optional initializer of the variable.</summary> <remarks> If this variable is in an <see cref="IVariableDeclarationOperation" />, the initializer may be located in the parent operation. Call <see cref="OperationExtensions.GetVariableInitializer(IVariableDeclaratorOperation)" /> to check in all locations. It is only possible to have initializers in both locations in VB invalid code scenarios. </remarks> </Comments> </Property> <Property Name="IgnoredArguments" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary> Additional arguments supplied to the declarator in error cases, ignored by the compiler. This only used for the C# case of DeclaredArgumentSyntax nodes on a VariableDeclaratorSyntax. </summary> </Comments> </Property> </Node> <Node Name="IVariableDeclarationOperation" Base="IOperation" ChildrenOrder="IgnoredDimensions,Declarators,Initializer"> <Comments> <summary>Represents a declarator that declares multiple individual variables.</summary> <para> Current Usage: (1) C# VariableDeclaration (2) C# fixed declarations (3) VB Dim statement declaration groups (4) VB Using statement variable declarations </para> <remarks> The initializer of this node is applied to all individual declarations in <see cref="Declarators" />. There cannot be initializers in both locations except in invalid code scenarios. In C#, this node will never have an initializer. This corresponds to the VariableDeclarationSyntax in C#, and the VariableDeclaratorSyntax in Visual Basic. </remarks> </Comments> <Property Name="Declarators" Type="ImmutableArray&lt;IVariableDeclaratorOperation&gt;"> <Comments> <summary>Individual variable declarations declared by this multiple declaration.</summary> <remarks> All <see cref="IVariableDeclarationGroupOperation" /> will have at least 1 <see cref="IVariableDeclarationOperation" />, even if the declaration group only declares 1 variable. </remarks> </Comments> </Property> <Property Name="Initializer" Type="IVariableInitializerOperation?"> <Comments> <summary>Optional initializer of the variable.</summary> <remarks>In C#, this will always be null.</remarks> </Comments> </Property> <Property Name="IgnoredDimensions" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary> Array dimensions supplied to an array declaration in error cases, ignored by the compiler. This is only used for the C# case of RankSpecifierSyntax nodes on an ArrayTypeSyntax. </summary> </Comments> </Property> </Node> <Node Name="IArgumentOperation" Base="IOperation"> <Comments> <summary> Represents an argument to a method invocation. <para> Current usage: (1) C# argument to an invocation expression, object creation expression, etc. (2) VB argument to an invocation expression, object creation expression, etc. </para> </summary> </Comments> <Property Name="ArgumentKind" Type="ArgumentKind"> <Comments> <summary>Kind of argument.</summary> </Comments> </Property> <Property Name="Parameter" Type="IParameterSymbol?"> <Comments> <summary>Parameter the argument matches. This can be null for __arglist parameters.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value supplied for the argument.</summary> </Comments> </Property> <Property Name="InConversion" Type="CommonConversion"> <Comments> <summary>Information of the conversion applied to the argument value passing it into the target method. Applicable only to VB Reference arguments.</summary> </Comments> </Property> <Property Name="OutConversion" Type="CommonConversion"> <Comments> <summary>Information of the conversion applied to the argument value after the invocation. Applicable only to VB Reference arguments.</summary> </Comments> </Property> </Node> <Node Name="ICatchClauseOperation" Base="IOperation" ChildrenOrder="ExceptionDeclarationOrExpression,Filter,Handler"> <Comments> <summary> Represents a catch clause. <para> Current usage: (1) C# catch clause. (2) VB Catch clause. </para> </summary> </Comments> <Property Name="ExceptionDeclarationOrExpression" Type="IOperation?"> <Comments> <summary> Optional source for exception. This could be any of the following operation: 1. Declaration for the local catch variable bound to the caught exception (C# and VB) OR 2. Null, indicating no declaration or expression (C# and VB) 3. Reference to an existing local or parameter (VB) OR 4. Other expression for error scenarios (VB) </summary> </Comments> </Property> <Property Name="ExceptionType" Type="ITypeSymbol"> <Comments> <summary>Type of the exception handled by the catch clause.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Locals declared by the <see cref="ExceptionDeclarationOrExpression" /> and/or <see cref="Filter" /> clause. </summary> </Comments> </Property> <Property Name="Filter" Type="IOperation?"> <Comments> <summary>Filter operation to be executed to determine whether to handle the exception.</summary> </Comments> </Property> <Property Name="Handler" Type="IBlockOperation"> <Comments> <summary>Body of the exception handler.</summary> </Comments> </Property> </Node> <Node Name="ISwitchCaseOperation" Base="IOperation" ChildrenOrder="Clauses,Body"> <Comments> <summary> Represents a switch case section with one or more case clauses to match and one or more operations to execute within the section. <para> Current usage: (1) C# switch section for one or more case clause and set of statements to execute. (2) VB case block with a case statement for one or more case clause and set of statements to execute. </para> </summary> </Comments> <Property Name="Clauses" Type="ImmutableArray&lt;ICaseClauseOperation&gt;"> <Comments> <summary>Clauses of the case.</summary> </Comments> </Property> <Property Name="Body" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>One or more operations to execute within the switch section.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Locals declared within the switch case section scoped to the section.</summary> </Comments> </Property> <Property Name="Condition" Type="IOperation?" Internal="true"> <Comments> <summary> Optional combined logical condition that accounts for all <see cref="Clauses"/>. An instance of <see cref="IPlaceholderOperation"/> with kind <see cref="PlaceholderKind.SwitchOperationExpression"/> is used to refer to the <see cref="ISwitchOperation.Value"/> in context of this expression. It is not part of <see cref="Children"/> list and likely contains duplicate nodes for nodes exposed by <see cref="Clauses"/>, like <see cref="ISingleValueCaseClauseOperation.Value"/>, etc. Never set for C# at the moment. </summary> </Comments> </Property> </Node> <AbstractNode Name="ICaseClauseOperation" Base="IOperation"> <OperationKind Include="true" ExtraDescription="This is further differentiated by &lt;see cref=&quot;ICaseClauseOperation.CaseKind&quot;/&gt;." /> <Comments> <summary> Represents a case clause. <para> Current usage: (1) C# case clause. (2) VB Case clause. </para> </summary> </Comments> <Property Name="CaseKind" Type="CaseKind" MakeAbstract="true"> <Comments> <summary>Kind of the clause.</summary> </Comments> </Property> <Property Name="Label" Type="ILabelSymbol?"> <Comments> <summary>Label associated with the case clause, if any.</summary> </Comments> </Property> </AbstractNode> <Node Name="IDefaultCaseClauseOperation" Base="ICaseClauseOperation"> <OperationKind Include="false" /> <Comments> <summary> Represents a default case clause. <para> Current usage: (1) C# default clause. (2) VB Case Else clause. </para> </summary> </Comments> </Node> <Node Name="IPatternCaseClauseOperation" Base="ICaseClauseOperation" ChildrenOrder="Pattern,Guard"> <OperationKind Include="false" /> <Comments> <summary> Represents a case clause with a pattern and an optional guard operation. <para> Current usage: (1) C# pattern case clause. </para> </summary> </Comments> <Property Name="Label" Type="ILabelSymbol" New="true"> <Comments> <!-- It would be a binary breaking change to remove this --> <summary> Label associated with the case clause. </summary> </Comments> </Property> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>Pattern associated with case clause.</summary> </Comments> </Property> <Property Name="Guard" Type="IOperation?"> <Comments> <summary>Guard associated with the pattern case clause.</summary> </Comments> </Property> </Node> <Node Name="IRangeCaseClauseOperation" Base="ICaseClauseOperation" ChildrenOrder="MinimumValue,MaximumValue"> <OperationKind Include="false" /> <Comments> <summary> Represents a case clause with range of values for comparison. <para> Current usage: (1) VB range case clause of the form "Case x To y". </para> </summary> </Comments> <Property Name="MinimumValue" Type="IOperation"> <Comments> <summary>Minimum value of the case range.</summary> </Comments> </Property> <Property Name="MaximumValue" Type="IOperation"> <Comments> <summary>Maximum value of the case range.</summary> </Comments> </Property> </Node> <Node Name="IRelationalCaseClauseOperation" Base="ICaseClauseOperation"> <OperationKind Include="false" /> <Comments> <summary> Represents a case clause with custom relational operator for comparison. <para> Current usage: (1) VB relational case clause of the form "Case Is op x". </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Case value.</summary> </Comments> </Property> <Property Name="Relation" Type="BinaryOperatorKind"> <Comments> <summary>Relational operator used to compare the switch value with the case value.</summary> </Comments> </Property> </Node> <Node Name="ISingleValueCaseClauseOperation" Base="ICaseClauseOperation"> <OperationKind Include="false" /> <Comments> <summary> Represents a case clause with a single value for comparison. <para> Current usage: (1) C# case clause of the form "case x" (2) VB case clause of the form "Case x". </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Case value.</summary> </Comments> </Property> </Node> <AbstractNode Name="IInterpolatedStringContentOperation" Base="IOperation"> <Comments> <summary> Represents a constituent part of an interpolated string. <para> Current usage: (1) C# interpolated string content. (2) VB interpolated string content. </para> </summary> </Comments> </AbstractNode> <Node Name="IInterpolatedStringTextOperation" Base="IInterpolatedStringContentOperation"> <Comments> <summary> Represents a constituent string literal part of an interpolated string operation. <para> Current usage: (1) C# interpolated string text. (2) VB interpolated string text. </para> </summary> </Comments> <Property Name="Text" Type="IOperation"> <Comments> <summary>Text content.</summary> </Comments> </Property> </Node> <Node Name="IInterpolationOperation" Base="IInterpolatedStringContentOperation" ChildrenOrder="Expression,Alignment,FormatString"> <Comments> <summary> Represents a constituent interpolation part of an interpolated string operation. <para> Current usage: (1) C# interpolation part. (2) VB interpolation part. </para> </summary> </Comments> <Property Name="Expression" Type="IOperation"> <Comments> <summary>Expression of the interpolation.</summary> </Comments> </Property> <Property Name="Alignment" Type="IOperation?"> <Comments> <summary>Optional alignment of the interpolation.</summary> </Comments> </Property> <Property Name="FormatString" Type="IOperation?"> <Comments> <summary>Optional format string of the interpolation.</summary> </Comments> </Property> </Node> <AbstractNode Name="IPatternOperation" Base="IOperation"> <Comments> <summary> Represents a pattern matching operation. <para> Current usage: (1) C# pattern. </para> </summary> </Comments> <Property Name="InputType" Type="ITypeSymbol"> <Comments> <summary>The input type to the pattern-matching operation.</summary> </Comments> </Property> <Property Name="NarrowedType" Type="ITypeSymbol"> <Comments> <summary>The narrowed type of the pattern-matching operation.</summary> </Comments> </Property> </AbstractNode> <Node Name="IConstantPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a pattern with a constant value. <para> Current usage: (1) C# constant pattern. </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Constant value of the pattern operation.</summary> </Comments> </Property> </Node> <Node Name="IDeclarationPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a pattern that declares a symbol. <para> Current usage: (1) C# declaration pattern. </para> </summary> </Comments> <Property Name="MatchedType" Type="ITypeSymbol?"> <Comments> <summary> The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#). </summary> </Comments> </Property> <Property Name="MatchesNull" Type="bool"> <Comments> <summary> True if the pattern is of a form that accepts null. For example, in C# the pattern `var x` will match a null input, while the pattern `string x` will not. </summary> </Comments> </Property> <Property Name="DeclaredSymbol" Type="ISymbol?"> <Comments> <summary>Symbol declared by the pattern, if any.</summary> </Comments> </Property> </Node> <Node Name="ITupleBinaryOperation" Base="IOperation" VisitorName="VisitTupleBinaryOperator" ChildrenOrder="LeftOperand,RightOperand" HasType="true"> <OperationKind> <Entry Name="TupleBinary" Value="0x57" /> <Entry Name="TupleBinaryOperator" Value="0x57" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;TupleBinary&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents a comparison of two operands that returns a bool type. <para> Current usage: (1) C# tuple binary operator expression. </para> </summary> </Comments> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>Kind of binary operation.</summary> </Comments> </Property> <Property Name="LeftOperand" Type="IOperation"> <Comments> <summary>Left operand.</summary> </Comments> </Property> <Property Name="RightOperand" Type="IOperation"> <Comments> <summary>Right operand.</summary> </Comments> </Property> </Node> <AbstractNode Name="IMethodBodyBaseOperation" Base="IOperation"> <Comments> <summary> Represents a method body operation. <para> Current usage: (1) C# method body </para> </summary> </Comments> <Property Name="BlockBody" Type="IBlockOperation?"> <Comments> <summary>Method body corresponding to BaseMethodDeclarationSyntax.Body or AccessorDeclarationSyntax.Body</summary> </Comments> </Property> <Property Name="ExpressionBody" Type="IBlockOperation?"> <Comments> <summary>Method body corresponding to BaseMethodDeclarationSyntax.ExpressionBody or AccessorDeclarationSyntax.ExpressionBody</summary> </Comments> </Property> </AbstractNode> <Node Name="IMethodBodyOperation" Base="IMethodBodyBaseOperation" VisitorName="VisitMethodBodyOperation" ChildrenOrder="BlockBody,ExpressionBody"> <OperationKind> <Entry Name="MethodBody" Value="0x58" /> <Entry Name="MethodBodyOperation" Value="0x58" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;MethodBody&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents a method body operation. <para> Current usage: (1) C# method body for non-constructor </para> </summary> </Comments> </Node> <Node Name="IConstructorBodyOperation" Base="IMethodBodyBaseOperation" VisitorName="VisitConstructorBodyOperation" ChildrenOrder="Initializer,BlockBody,ExpressionBody"> <OperationKind> <Entry Name="ConstructorBody" Value="0x59" /> <Entry Name="ConstructorBodyOperation" Value="0x59" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;ConstructorBody&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents a constructor method body operation. <para> Current usage: (1) C# method body for constructor declaration </para> </summary> </Comments> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Local declarations contained within the <see cref="Initializer" />.</summary> </Comments> </Property> <Property Name="Initializer" Type="IOperation?"> <Comments> <summary>Constructor initializer, if any.</summary> </Comments> </Property> </Node> <Node Name="IDiscardOperation" Base="IOperation" VisitorName="VisitDiscardOperation" HasType="true"> <Comments> <summary> Represents a discard operation. <para> Current usage: C# discard expressions </para> </summary> </Comments> <Property Name="DiscardSymbol" Type="IDiscardSymbol"> <Comments> <summary>The symbol of the discard operation.</summary> </Comments> </Property> </Node> <Node Name="IFlowCaptureOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true"> <Comments> <summary> Represents that an intermediate result is being captured. This node is produced only as part of a <see cref="ControlFlowGraph" />. </summary> </Comments> <Property Name="Id" Type="CaptureId"> <Comments> <summary>An id used to match references to the same intermediate result.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to be captured.</summary> </Comments> </Property> </Node> <Node Name="IFlowCaptureReferenceOperation" Base="IOperation" Namespace="FlowAnalysis" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a point of use of an intermediate result captured earlier. The fact of capturing the result is represented by <see cref="IFlowCaptureOperation" />. This node is produced only as part of a <see cref="ControlFlowGraph" />. </summary> </Comments> <Property Name="Id" Type="CaptureId"> <Comments> <summary>An id used to match references to the same intermediate result.</summary> </Comments> </Property> </Node> <Node Name="IIsNullOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents result of checking whether the <see cref="Operand" /> is null. For reference types this checks if the <see cref="Operand" /> is a null reference, for nullable types this checks if the <see cref="Operand" /> doesn’t have a value. The node is produced as part of a flow graph during rewrite of <see cref="ICoalesceOperation" /> and <see cref="IConditionalAccessOperation" /> nodes. </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Value to check.</summary> </Comments> </Property> </Node> <Node Name="ICaughtExceptionOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true"> <Comments> <summary> Represents a exception instance passed by an execution environment to an exception filter or handler. This node is produced only as part of a <see cref="ControlFlowGraph" />. </summary> </Comments> </Node> <Node Name="IStaticLocalInitializationSemaphoreOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true"> <Comments> <summary> Represents the check during initialization of a VB static local that is initialized on the first call of the function, and never again. If the semaphore operation returns true, the static local has not yet been initialized, and the initializer will be run. If it returns false, then the local has already been initialized, and the static local initializer region will be skipped. This node is produced only as part of a <see cref="ControlFlowGraph" />. </summary> </Comments> <Property Name="Local" Type="ILocalSymbol"> <Comments> <summary>The static local variable that is possibly initialized.</summary> </Comments> </Property> </Node> <Node Name="IFlowAnonymousFunctionOperation" Base="IOperation" Namespace="FlowAnalysis" SkipClassGeneration="true"> <Comments> <summary> Represents an anonymous function operation in context of a <see cref="ControlFlowGraph" />. <para> Current usage: (1) C# lambda expression. (2) VB anonymous delegate expression. </para> A <see cref="ControlFlowGraph" /> for the body of the anonymous function is available from the enclosing <see cref="ControlFlowGraph" />. </summary> </Comments> <Property Name="Symbol" Type="IMethodSymbol"> <Comments> <summary>Symbol of the anonymous function.</summary> </Comments> </Property> </Node> <Node Name="ICoalesceAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true"> <Comments> <summary> Represents a coalesce assignment operation with a target and a conditionally-evaluated value: (1) <see cref="IAssignmentOperation.Target" /> is evaluated for null. If it is null, <see cref="IAssignmentOperation.Value" /> is evaluated and assigned to target. (2) <see cref="IAssignmentOperation.Value" /> is conditionally evaluated if <see cref="IAssignmentOperation.Target" /> is null, and the result is assigned into <see cref="IAssignmentOperation.Target" />. The result of the entire expression is<see cref="IAssignmentOperation.Target" />, which is only evaluated once. <para> Current usage: (1) C# null-coalescing assignment operation <code>Target ??= Value</code>. </para> </summary> </Comments> </Node> <Node Name="IRangeOperation" Base="IOperation" VisitorName="VisitRangeOperation" ChildrenOrder="LeftOperand,RightOperand" HasType="true"> <Comments> <summary> Represents a range operation. <para> Current usage: (1) C# range expressions </para> </summary> </Comments> <Property Name="LeftOperand" Type="IOperation?"> <Comments> <summary>Left operand.</summary> </Comments> </Property> <Property Name="RightOperand" Type="IOperation?"> <Comments> <summary>Right operand.</summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <code>true</code> if this is a 'lifted' range operation. When there is an operator that is defined to work on a value type, 'lifted' operators are created to work on the <see cref="System.Nullable{T}" /> versions of those value types. </summary> </Comments> </Property> <Property Name="Method" Type="IMethodSymbol?"> <Comments> <summary> Factory method used to create this Range value. Can be null if appropriate symbol was not found. </summary> </Comments> </Property> </Node> <Node Name="IReDimOperation" Base="IOperation"> <Comments> <summary> Represents the ReDim operation to re-allocate storage space for array variables. <para> Current usage: (1) VB ReDim statement. </para> </summary> </Comments> <Property Name="Clauses" Type="ImmutableArray&lt;IReDimClauseOperation&gt;"> <Comments> <summary>Individual clauses of the ReDim operation.</summary> </Comments> </Property> <Property Name="Preserve" Type="bool"> <Comments> <summary>Modifier used to preserve the data in the existing array when you change the size of only the last dimension.</summary> </Comments> </Property> </Node> <Node Name="IReDimClauseOperation" Base="IOperation" ChildrenOrder="Operand,DimensionSizes"> <Comments> <summary> Represents an individual clause of an <see cref="IReDimOperation" /> to re-allocate storage space for a single array variable. <para> Current usage: (1) VB ReDim clause. </para> </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Operand whose storage space needs to be re-allocated.</summary> </Comments> </Property> <Property Name="DimensionSizes" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Sizes of the dimensions of the created array instance.</summary> </Comments> </Property> </Node> <Node Name="IRecursivePatternOperation" Base="IPatternOperation" ChildrenOrder="DeconstructionSubpatterns,PropertySubpatterns"> <Comments> <summary>Represents a C# recursive pattern.</summary> </Comments> <Property Name="MatchedType" Type="ITypeSymbol"> <Comments> <summary>The type accepted for the recursive pattern.</summary> </Comments> </Property> <Property Name="DeconstructSymbol" Type="ISymbol?"> <Comments> <summary> The symbol, if any, used for the fetching values for subpatterns. This is either a <code>Deconstruct</code> method, the type <code>System.Runtime.CompilerServices.ITuple</code>, or null (for example, in error cases or when matching a tuple type). </summary> </Comments> </Property> <Property Name="DeconstructionSubpatterns" Type="ImmutableArray&lt;IPatternOperation&gt;"> <Comments> <summary>This contains the patterns contained within a deconstruction or positional subpattern.</summary> </Comments> </Property> <Property Name="PropertySubpatterns" Type="ImmutableArray&lt;IPropertySubpatternOperation&gt;"> <Comments> <summary>This contains the (symbol, property) pairs within a property subpattern.</summary> </Comments> </Property> <Property Name="DeclaredSymbol" Type="ISymbol?"> <Comments> <summary>Symbol declared by the pattern.</summary> </Comments> </Property> </Node> <Node Name="IDiscardPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a discard pattern. <para> Current usage: C# discard pattern </para> </summary> </Comments> </Node> <Node Name="ISwitchExpressionOperation" Base="IOperation" ChildrenOrder="Value,Arms" HasType="true"> <Comments> <summary> Represents a switch expression. <para> Current usage: (1) C# switch expression. </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to be switched upon.</summary> </Comments> </Property> <Property Name="Arms" Type="ImmutableArray&lt;ISwitchExpressionArmOperation&gt;"> <Comments> <summary>Arms of the switch expression.</summary> </Comments> </Property> <Property Name="IsExhaustive" Type="bool"> <Comments> <summary>True if the switch expressions arms cover every possible input value.</summary> </Comments> </Property> </Node> <Node Name="ISwitchExpressionArmOperation" Base="IOperation" ChildrenOrder="Pattern,Guard,Value"> <Comments> <summary>Represents one arm of a switch expression.</summary> </Comments> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>The pattern to match.</summary> </Comments> </Property> <Property Name="Guard" Type="IOperation?"> <Comments> <summary>Guard (when clause expression) associated with the switch arm, if any.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Result value of the enclosing switch expression when this arm matches.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Locals declared within the switch arm (e.g. pattern locals and locals declared in the guard) scoped to the arm.</summary> </Comments> </Property> </Node> <Node Name="IPropertySubpatternOperation" Base="IOperation" ChildrenOrder="Member,Pattern"> <Comments> <summary> Represents an element of a property subpattern, which identifies a member to be matched and the pattern to match it against. </summary> </Comments> <Property Name="Member" Type="IOperation"> <Comments> <summary> The member being matched in a property subpattern. This can be a <see cref="IMemberReferenceOperation" /> in non-error cases, or an <see cref="IInvalidOperation" /> in error cases. </summary> </Comments> </Property> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>The pattern to which the member is matched in a property subpattern.</summary> </Comments> </Property> </Node> <Node Name="IAggregateQueryOperation" Base="IOperation" Internal="true" ChildrenOrder="Group,Aggregation" HasType="true"> <Comments> <summary>Represents a standalone VB query Aggregate operation with more than one item in Into clause.</summary> </Comments> <Property Name="Group" Type="IOperation" /> <Property Name="Aggregation" Type="IOperation" /> </Node> <Node Name="IFixedOperation" Base="IOperation" Internal="true" SkipInVisitor="true" ChildrenOrder="Variables,Body"> <!-- Making this public is tracked by https://github.com/dotnet/roslyn/issues/21281 --> <Comments> <summary>Represents a C# fixed statement.</summary> </Comments> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Locals declared.</summary> </Comments> </Property> <Property Name="Variables" Type="IVariableDeclarationGroupOperation"> <Comments> <summary>Variables to be fixed.</summary> </Comments> </Property> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the fixed, over which the variables are fixed.</summary> </Comments> </Property> </Node> <Node Name="INoPiaObjectCreationOperation" Base="IOperation" Internal="true" HasType="true"> <Comments> <summary> Represents a creation of an instance of a NoPia interface, i.e. new I(), where I is an embedded NoPia interface. <para> Current usage: (1) C# NoPia interface instance creation expression. (2) VB NoPia interface instance creation expression. </para> </summary> </Comments> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?"> <Comments> <summary>Object or collection initializer, if any.</summary> </Comments> </Property> </Node> <Node Name="IPlaceholderOperation" Base="IOperation" Internal="true" HasType="true"> <Comments> <summary> Represents a general placeholder when no more specific kind of placeholder is available. A placeholder is an expression whose meaning is inferred from context. </summary> </Comments> <Property Name="PlaceholderKind" Type="PlaceholderKind" /> </Node> <Node Name="IPointerIndirectionReferenceOperation" Base="IOperation" SkipClassGeneration="true" Internal="true" HasType="true"> <Comments> <summary> Represents a reference through a pointer. <para> Current usage: (1) C# pointer indirection reference expression. </para> </summary> </Comments> <Property Name="Pointer" Type="IOperation"> <Comments> <summary>Pointer to be dereferenced.</summary> </Comments> </Property> </Node> <Node Name="IWithStatementOperation" Base="IOperation" Internal="true" ChildrenOrder="Value,Body"> <Comments> <summary> Represents a <see cref="Body" /> of operations that are executed with implicit reference to the <see cref="Value" /> for member references. <para> Current usage: (1) VB With statement. </para> </summary> </Comments> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the with.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to whose members leading-dot-qualified references within the with body bind.</summary> </Comments> </Property> </Node> <Node Name="IUsingDeclarationOperation" Base="IOperation"> <Comments> <summary> Represents using variable declaration, with scope spanning across the parent <see cref="IBlockOperation"/>. <para> Current Usage: (1) C# using declaration (1) C# asynchronous using declaration </para> </summary> </Comments> <Property Name="DeclarationGroup" Type="IVariableDeclarationGroupOperation"> <Comments> <summary>The variables declared by this using declaration.</summary> </Comments> </Property> <Property Name="IsAsynchronous" Type="bool"> <Comments> <summary>True if this is an asynchronous using declaration.</summary> </Comments> </Property> <Property Name="DisposeInfo" Type="DisposeOperationInfo" Internal="true"> <Comments> <summary>Information about the method that will be invoked to dispose the declared instances when pattern based disposal is used.</summary> </Comments> </Property> </Node> <Node Name="INegatedPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a negated pattern. <para> Current usage: (1) C# negated pattern. </para> </summary> </Comments> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>The negated pattern.</summary> </Comments> </Property> </Node> <Node Name="IBinaryPatternOperation" Base="IPatternOperation" ChildrenOrder="LeftPattern,RightPattern"> <Comments> <summary> Represents a binary ("and" or "or") pattern. <para> Current usage: (1) C# "and" and "or" patterns. </para> </summary> </Comments> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>Kind of binary pattern; either <see cref="BinaryOperatorKind.And"/> or <see cref="BinaryOperatorKind.Or"/>.</summary> </Comments> </Property> <Property Name="LeftPattern" Type="IPatternOperation"> <Comments> <summary>The pattern on the left.</summary> </Comments> </Property> <Property Name="RightPattern" Type="IPatternOperation"> <Comments> <summary>The pattern on the right.</summary> </Comments> </Property> </Node> <Node Name="ITypePatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a pattern comparing the input with a given type. <para> Current usage: (1) C# type pattern. </para> </summary> </Comments> <Property Name="MatchedType" Type="ITypeSymbol"> <Comments> <summary> The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#). </summary> </Comments> </Property> </Node> <Node Name="IRelationalPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a pattern comparing the input with a constant value using a relational operator. <para> Current usage: (1) C# relational pattern. </para> </summary> </Comments> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>The kind of the relational operator.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Constant value of the pattern operation.</summary> </Comments> </Property> </Node> <Node Name="IWithOperation" Base="IOperation" ChildrenOrder="Operand,Initializer" HasType="true"> <Comments> <summary> Represents cloning of an object instance. <para> Current usage: (1) C# with expression. </para> </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Operand to be cloned.</summary> </Comments> </Property> <Property Name="CloneMethod" Type="IMethodSymbol?"> <Comments> <summary>Clone method to be invoked on the value. This can be null in error scenarios.</summary> </Comments> </Property> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation"> <Comments> <summary>With collection initializer.</summary> </Comments> </Property> </Node> </Tree>
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Tree Root="IOperation"> <!-- To regenerate the operation nodes, run eng/generate-compiler-code.cmd The operations in this file are _ordered_! If you change the order in here, you will affect the ordering in the generated OperationKind enum, which will break the public api analyzer. All new types should be put at the end of this file in order to ensure that the kind does not continue to change. UnusedOperationKinds indicates kinds that are currently skipped by the OperationKind enum. They can be used by future nodes by inserting those nodes at the correct point in the list. When implementing new operations, run tests with additional IOperation validation enabled. You can test with `Build.cmd -testIOperation`. Or to repro in VS, you can do `set ROSLYN_TEST_IOPERATION=true` then `devenv`. --> <UnusedOperationKinds> <Entry Value="0x1D"/> <Entry Value="0x62"/> <Entry Value="0x64"/> </UnusedOperationKinds> <Node Name="IInvalidOperation" Base="IOperation" SkipClassGeneration="true"> <Comments> <summary> Represents an invalid operation with one or more child operations. <para> Current usage: (1) C# invalid expression or invalid statement. (2) VB invalid expression or invalid statement. </para> </summary> </Comments> </Node> <Node Name="IBlockOperation" Base="IOperation"> <Comments> <summary> Represents a block containing a sequence of operations and local declarations. <para> Current usage: (1) C# "{ ... }" block statement. (2) VB implicit block statement for method bodies and other block scoped statements. </para> </summary> </Comments> <Property Name="Operations" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Operations contained within the block.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Local declarations contained within the block.</summary> </Comments> </Property> </Node> <Node Name="IVariableDeclarationGroupOperation" Base="IOperation"> <Comments> <summary>Represents a variable declaration statement.</summary> <para> Current Usage: (1) C# local declaration statement (2) C# fixed statement (3) C# using statement (4) C# using declaration (5) VB Dim statement (6) VB Using statement </para> </Comments> <Property Name="Declarations" Type="ImmutableArray&lt;IVariableDeclarationOperation&gt;"> <Comments> <summary>Variable declaration in the statement.</summary> <remarks> In C#, this will always be a single declaration, with all variables in <see cref="IVariableDeclarationOperation.Declarators" />. </remarks> </Comments> </Property> </Node> <Node Name="ISwitchOperation" Base="IOperation" ChildrenOrder="Value,Cases"> <Comments> <summary> Represents a switch operation with a value to be switched upon and switch cases. <para> Current usage: (1) C# switch statement. (2) VB Select Case statement. </para> </summary> </Comments> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Locals declared within the switch operation with scope spanning across all <see cref="Cases" />. </summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to be switched upon.</summary> </Comments> </Property> <Property Name="Cases" Type="ImmutableArray&lt;ISwitchCaseOperation&gt;"> <Comments> <summary>Cases of the switch.</summary> </Comments> </Property> <Property Name="ExitLabel" Type="ILabelSymbol"> <Comments> <summary>Exit label for the switch statement.</summary> </Comments> </Property> </Node> <AbstractNode Name="ILoopOperation" Base="IOperation"> <OperationKind Include="true" ExtraDescription="This is further differentiated by &lt;see cref=&quot;ILoopOperation.LoopKind&quot;/&gt;." /> <Comments> <summary> Represents a loop operation. <para> Current usage: (1) C# 'while', 'for', 'foreach' and 'do' loop statements (2) VB 'While', 'ForTo', 'ForEach', 'Do While' and 'Do Until' loop statements </para> </summary> </Comments> <Property Name="LoopKind" Type="LoopKind" MakeAbstract="true"> <Comments> <summary>Kind of the loop.</summary> </Comments> </Property> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the loop.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Declared locals.</summary> </Comments> </Property> <Property Name="ContinueLabel" Type="ILabelSymbol"> <Comments> <summary>Loop continue label.</summary> </Comments> </Property> <Property Name="ExitLabel" Type="ILabelSymbol"> <Comments> <summary>Loop exit/break label.</summary> </Comments> </Property> </AbstractNode> <Node Name="IForEachLoopOperation" Base="ILoopOperation" ChildrenOrder="Collection,LoopControlVariable,Body,NextVariables"> <OperationKind Include="false" /> <Comments> <summary> Represents a for each loop. <para> Current usage: (1) C# 'foreach' loop statement (2) VB 'For Each' loop statement </para> </summary> </Comments> <Property Name="LoopControlVariable" Type="IOperation"> <Comments> <summary>Refers to the operation for declaring a new local variable or reference an existing variable or an expression.</summary> </Comments> </Property> <Property Name="Collection" Type="IOperation"> <Comments> <summary>Collection value over which the loop iterates.</summary> </Comments> </Property> <Property Name="NextVariables" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary> Optional list of comma separated next variables at loop bottom in VB. This list is always empty for C#. </summary> </Comments> </Property> <Property Name="Info" Type="ForEachLoopOperationInfo?" Internal="true" /> <Property Name="IsAsynchronous" Type="bool"> <Comments> <summary> Whether this for each loop is asynchronous. Always false for VB. </summary> </Comments> </Property> </Node> <Node Name="IForLoopOperation" Base="ILoopOperation" ChildrenOrder="Before,Condition,Body,AtLoopBottom"> <OperationKind Include="false" /> <Comments> <summary> Represents a for loop. <para> Current usage: (1) C# 'for' loop statement </para> </summary> </Comments> <Property Name="Before" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>List of operations to execute before entry to the loop. For C#, this comes from the first clause of the for statement.</summary> </Comments> </Property> <Property Name="ConditionLocals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Locals declared within the loop Condition and are in scope throughout the <see cref="Condition" />, <see cref="ILoopOperation.Body" /> and <see cref="AtLoopBottom" />. They are considered to be declared per iteration. </summary> </Comments> </Property> <Property Name="Condition" Type="IOperation?"> <Comments> <summary>Condition of the loop. For C#, this comes from the second clause of the for statement.</summary> </Comments> </Property> <Property Name="AtLoopBottom" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>List of operations to execute at the bottom of the loop. For C#, this comes from the third clause of the for statement.</summary> </Comments> </Property> </Node> <Node Name="IForToLoopOperation" Base="ILoopOperation" ChildrenOrder="LoopControlVariable,InitialValue,LimitValue,StepValue,Body,NextVariables"> <OperationKind Include="false" /> <Comments> <summary> Represents a for to loop with loop control variable and initial, limit and step values for the control variable. <para> Current usage: (1) VB 'For ... To ... Step' loop statement </para> </summary> </Comments> <Property Name="LoopControlVariable" Type="IOperation"> <Comments> <summary>Refers to the operation for declaring a new local variable or reference an existing variable or an expression.</summary> </Comments> </Property> <Property Name="InitialValue" Type="IOperation"> <Comments> <summary>Operation for setting the initial value of the loop control variable. This comes from the expression between the 'For' and 'To' keywords.</summary> </Comments> </Property> <Property Name="LimitValue" Type="IOperation"> <Comments> <summary>Operation for the limit value of the loop control variable. This comes from the expression after the 'To' keyword.</summary> </Comments> </Property> <Property Name="StepValue" Type="IOperation"> <Comments> <summary> Operation for the step value of the loop control variable. This comes from the expression after the 'Step' keyword, or inferred by the compiler if 'Step' clause is omitted. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <code>true</code> if arithmetic operations behind this loop are 'checked'.</summary> </Comments> </Property> <Property Name="NextVariables" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Optional list of comma separated next variables at loop bottom.</summary> </Comments> </Property> <Property Name="Info" Type="(ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo)" Internal="true" /> </Node> <Node Name="IWhileLoopOperation" Base="ILoopOperation" SkipChildrenGeneration="true"> <OperationKind Include="false" /> <Comments> <summary> Represents a while or do while loop. <para> Current usage: (1) C# 'while' and 'do while' loop statements. (2) VB 'While', 'Do While' and 'Do Until' loop statements. </para> </summary> </Comments> <Property Name="Condition" Type="IOperation?"> <Comments> <summary>Condition of the loop. This can only be null in error scenarios.</summary> </Comments> </Property> <Property Name="ConditionIsTop" Type="bool"> <Comments> <summary> True if the <see cref="Condition" /> is evaluated at start of each loop iteration. False if it is evaluated at the end of each loop iteration. </summary> </Comments> </Property> <Property Name="ConditionIsUntil" Type="bool"> <Comments> <summary>True if the loop has 'Until' loop semantics and the loop is executed while <see cref="Condition" /> is false.</summary> </Comments> </Property> <Property Name="IgnoredCondition" Type="IOperation?"> <Comments> <summary> Additional conditional supplied for loop in error cases, which is ignored by the compiler. For example, for VB 'Do While' or 'Do Until' loop with syntax errors where both the top and bottom conditions are provided. The top condition is preferred and exposed as <see cref="Condition" /> and the bottom condition is ignored and exposed by this property. This property should be null for all non-error cases. </summary> </Comments> </Property> </Node> <Node Name="ILabeledOperation" Base="IOperation"> <Comments> <summary> Represents an operation with a label. <para> Current usage: (1) C# labeled statement. (2) VB label statement. </para> </summary> </Comments> <Property Name="Label" Type="ILabelSymbol"> <Comments> <summary>Label that can be the target of branches.</summary> </Comments> </Property> <Property Name="Operation" Type="IOperation?"> <Comments> <summary>Operation that has been labeled. In VB, this is always null.</summary> </Comments> </Property> </Node> <Node Name="IBranchOperation" Base="IOperation"> <Comments> <summary> Represents a branch operation. <para> Current usage: (1) C# goto, break, or continue statement. (2) VB GoTo, Exit ***, or Continue *** statement. </para> </summary> </Comments> <Property Name="Target" Type="ILabelSymbol"> <Comments> <summary>Label that is the target of the branch.</summary> </Comments> </Property> <Property Name="BranchKind" Type="BranchKind"> <Comments> <summary>Kind of the branch.</summary> </Comments> </Property> </Node> <Node Name="IEmptyOperation" Base="IOperation"> <Comments> <summary> Represents an empty or no-op operation. <para> Current usage: (1) C# empty statement. </para> </summary> </Comments> </Node> <Node Name="IReturnOperation" Base="IOperation"> <OperationKind> <Entry Name="Return" Value="0x9"/> <Entry Name="YieldBreak" Value="0xa" ExtraDescription="This has yield break semantics."/> <Entry Name="YieldReturn" Value="0xe" ExtraDescription="This has yield return semantics."/> </OperationKind> <Comments> <summary> Represents a return from the method with an optional return value. <para> Current usage: (1) C# return statement and yield statement. (2) VB Return statement. </para> </summary> </Comments> <Property Name="ReturnedValue" Type="IOperation?"> <Comments> <summary>Value to be returned.</summary> </Comments> </Property> </Node> <Node Name="ILockOperation" Base="IOperation" ChildrenOrder="LockedValue,Body"> <Comments> <summary> Represents a <see cref="Body" /> of operations that are executed while holding a lock onto the <see cref="LockedValue" />. <para> Current usage: (1) C# lock statement. (2) VB SyncLock statement. </para> </summary> </Comments> <Property Name="LockedValue" Type="IOperation"> <Comments> <summary>Operation producing a value to be locked.</summary> </Comments> </Property> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the lock, to be executed while holding the lock.</summary> </Comments> </Property> <Property Name="LockTakenSymbol" Type="ILocalSymbol?" Internal="true"/> </Node> <Node Name="ITryOperation" Base="IOperation" ChildrenOrder="Body,Catches,Finally"> <Comments> <summary> Represents a try operation for exception handling code with a body, catch clauses and a finally handler. <para> Current usage: (1) C# try statement. (2) VB Try statement. </para> </summary> </Comments> <Property Name="Body" Type="IBlockOperation"> <Comments> <summary>Body of the try, over which the handlers are active.</summary> </Comments> </Property> <Property Name="Catches" Type="ImmutableArray&lt;ICatchClauseOperation&gt;"> <Comments> <summary>Catch clauses of the try.</summary> </Comments> </Property> <Property Name="Finally" Type="IBlockOperation?"> <Comments> <summary>Finally handler of the try.</summary> </Comments> </Property> <Property Name="ExitLabel" Type="ILabelSymbol?"> <Comments> <summary>Exit label for the try. This will always be null for C#.</summary> </Comments> </Property> </Node> <Node Name="IUsingOperation" Base="IOperation" ChildrenOrder="Resources,Body"> <Comments> <summary> Represents a <see cref="Body" /> of operations that are executed while using disposable <see cref="Resources" />. <para> Current usage: (1) C# using statement. (2) VB Using statement. </para> </summary> </Comments> <Property Name="Resources" Type="IOperation"> <Comments> <summary>Declaration introduced or resource held by the using.</summary> </Comments> </Property> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the using, over which the resources of the using are maintained.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Locals declared within the <see cref="Resources" /> with scope spanning across this entire <see cref="IUsingOperation" />. </summary> </Comments> </Property> <Property Name="IsAsynchronous" Type="bool"> <Comments> <summary> Whether this using is asynchronous. Always false for VB. </summary> </Comments> </Property> <Property Name="DisposeInfo" Type="DisposeOperationInfo" Internal="true"> <Comments> <summary>Information about the method that will be invoked to dispose the <see cref="Resources" /> when pattern based disposal is used.</summary> </Comments> </Property> </Node> <Node Name="IExpressionStatementOperation" Base="IOperation"> <Comments> <summary> Represents an operation that drops the resulting value and the type of the underlying wrapped <see cref="Operation" />. <para> Current usage: (1) C# expression statement. (2) VB expression statement. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Underlying operation with a value and type.</summary> </Comments> </Property> </Node> <Node Name="ILocalFunctionOperation" Base="IOperation" ChildrenOrder="Body,IgnoredBody"> <Comments> <summary> Represents a local function defined within a method. <para> Current usage: (1) C# local function statement. </para> </summary> </Comments> <Property Name="Symbol" Type="IMethodSymbol"> <Comments> <summary>Local function symbol.</summary> </Comments> </Property> <Property Name="Body" Type="IBlockOperation?"> <Comments> <summary>Body of the local function.</summary> <remarks>This can be null in error scenarios, or when the method is an extern method.</remarks> </Comments> </Property> <Property Name="IgnoredBody" Type="IBlockOperation?"> <Comments> <summary>An extra body for the local function, if both a block body and expression body are specified in source.</summary> <remarks>This is only ever non-null in error situations.</remarks> </Comments> </Property> </Node> <Node Name="IStopOperation" Base="IOperation"> <Comments> <summary> Represents an operation to stop or suspend execution of code. <para> Current usage: (1) VB Stop statement. </para> </summary> </Comments> </Node> <Node Name="IEndOperation" Base="IOperation"> <Comments> <summary> Represents an operation that stops the execution of code abruptly. <para> Current usage: (1) VB End Statement. </para> </summary> </Comments> </Node> <Node Name="IRaiseEventOperation" Base="IOperation" ChildrenOrder="EventReference,Arguments"> <Comments> <summary> Represents an operation for raising an event. <para> Current usage: (1) VB raise event statement. </para> </summary> </Comments> <Property Name="EventReference" Type="IEventReferenceOperation"> <Comments> <summary>Reference to the event to be raised.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IArgumentOperation&gt;"> <Comments> <summary>Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order.</summary> <remarks> If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. Default values are supplied for optional arguments missing in source. </remarks> </Comments> </Property> </Node> <Node Name="ILiteralOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a textual literal numeric, string, etc. <para> Current usage: (1) C# literal expression. (2) VB literal expression. </para> </summary> </Comments> </Node> <Node Name="IConversionOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a type conversion. <para> Current usage: (1) C# conversion expression. (2) VB conversion expression. </para> </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Value to be converted.</summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?" SkipGeneration="true"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> <Property Name="Conversion" Type="CommonConversion"> <Comments> <summary>Gets the underlying common conversion information.</summary> <remarks> If you need conversion information that is language specific, use either <see cref="T:Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetConversion(IConversionOperation)" /> or <see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.GetConversion(IConversionOperation)" />. </remarks> </Comments> </Property> <Property Name="IsTryCast" Type="bool"> <Comments> <summary> False if the conversion will fail with a <see cref="InvalidCastException" /> at runtime if the cast fails. This is true for C#'s <c>as</c> operator and for VB's <c>TryCast</c> operator. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary>True if the conversion can fail at runtime with an overflow exception. This corresponds to C# checked and unchecked blocks.</summary> </Comments> </Property> </Node> <Node Name="IInvocationOperation" Base="IOperation" ChildrenOrder="Instance,Arguments" HasType="true"> <Comments> <summary> Represents an invocation of a method. <para> Current usage: (1) C# method invocation expression. (2) C# collection element initializer. For example, in the following collection initializer: <code>new C() { 1, 2, 3 }</code>, we will have 3 <see cref="IInvocationOperation" /> nodes, each of which will be a call to the corresponding Add method with either 1, 2, 3 as the argument. (3) VB method invocation expression. (4) VB collection element initializer. Similar to the C# example, <code>New C() From {1, 2, 3}</code> will have 3 <see cref="IInvocationOperation" /> nodes with 1, 2, and 3 as their arguments, respectively. </para> </summary> </Comments> <Property Name="TargetMethod" Type="IMethodSymbol"> <Comments> <summary>Method to be invoked.</summary> </Comments> </Property> <Property Name="Instance" Type="IOperation?"> <Comments> <summary>'This' or 'Me' instance to be supplied to the method, or null if the method is static.</summary> </Comments> </Property> <Property Name="IsVirtual" Type="bool"> <Comments> <summary>True if the invocation uses a virtual mechanism, and false otherwise.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IArgumentOperation&gt;"> <Comments> <summary>Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order.</summary> <remarks> If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. Default values are supplied for optional arguments missing in source. </remarks> </Comments> </Property> </Node> <Node Name="IArrayElementReferenceOperation" Base="IOperation" ChildrenOrder="ArrayReference,Indices" HasType="true"> <Comments> <summary> Represents a reference to an array element. <para> Current usage: (1) C# array element reference expression. (2) VB array element reference expression. </para> </summary> </Comments> <Property Name="ArrayReference" Type="IOperation"> <Comments> <summary>Array to be indexed.</summary> </Comments> </Property> <Property Name="Indices" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Indices that specify an individual element.</summary> </Comments> </Property> </Node> <Node Name="ILocalReferenceOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a reference to a declared local variable. <para> Current usage: (1) C# local reference expression. (2) VB local reference expression. </para> </summary> </Comments> <Property Name="Local" Type="ILocalSymbol"> <Comments> <summary>Referenced local variable.</summary> </Comments> </Property> <Property Name="IsDeclaration" Type="bool"> <Comments> <summary> True if this reference is also the declaration site of this variable. This is true in out variable declarations and in deconstruction operations where a new variable is being declared. </summary> </Comments> </Property> </Node> <Node Name="IParameterReferenceOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a reference to a parameter. <para> Current usage: (1) C# parameter reference expression. (2) VB parameter reference expression. </para> </summary> </Comments> <Property Name="Parameter" Type="IParameterSymbol"> <Comments> <summary>Referenced parameter.</summary> </Comments> </Property> </Node> <AbstractNode Name="IMemberReferenceOperation" Base="IOperation" > <Comments> <summary> Represents a reference to a member of a class, struct, or interface. <para> Current usage: (1) C# member reference expression. (2) VB member reference expression. </para> </summary> </Comments> <Property Name="Instance" Type="IOperation?"> <Comments> <summary>Instance of the type. Null if the reference is to a static/shared member.</summary> </Comments> </Property> <Property Name="Member" Type="ISymbol" SkipGeneration="true"> <Comments> <summary>Referenced member.</summary> </Comments> </Property> </AbstractNode> <Node Name="IFieldReferenceOperation" Base="IMemberReferenceOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a reference to a field. <para> Current usage: (1) C# field reference expression. (2) VB field reference expression. </para> </summary> </Comments> <Property Name="Field" Type="IFieldSymbol"> <Comments> <summary>Referenced field.</summary> </Comments> </Property> <Property Name="IsDeclaration" Type="bool"> <Comments> <summary>If the field reference is also where the field was declared.</summary> <remarks> This is only ever true in CSharp scripts, where a top-level statement creates a new variable in a reference, such as an out variable declaration or a deconstruction declaration. </remarks> </Comments> </Property> </Node> <Node Name="IMethodReferenceOperation" Base="IMemberReferenceOperation" HasType="true"> <Comments> <summary> Represents a reference to a method other than as the target of an invocation. <para> Current usage: (1) C# method reference expression. (2) VB method reference expression. </para> </summary> </Comments> <Property Name="Method" Type="IMethodSymbol"> <Comments> <summary>Referenced method.</summary> </Comments> </Property> <Property Name="IsVirtual" Type="bool"> <Comments> <summary>Indicates whether the reference uses virtual semantics.</summary> </Comments> </Property> </Node> <Node Name="IPropertyReferenceOperation" Base="IMemberReferenceOperation" ChildrenOrder="Instance,Arguments" HasType="true"> <Comments> <summary> Represents a reference to a property. <para> Current usage: (1) C# property reference expression. (2) VB property reference expression. </para> </summary> </Comments> <Property Name="Property" Type="IPropertySymbol"> <Comments> <summary>Referenced property.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IArgumentOperation&gt;"> <Comments> <summary>Arguments of the indexer property reference, excluding the instance argument. Arguments are in evaluation order.</summary> <remarks> If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. Default values are supplied for optional arguments missing in source. </remarks> </Comments> </Property> </Node> <Node Name="IEventReferenceOperation" Base="IMemberReferenceOperation" HasType="true"> <Comments> <summary> Represents a reference to an event. <para> Current usage: (1) C# event reference expression. (2) VB event reference expression. </para> </summary> </Comments> <Property Name="Event" Type="IEventSymbol"> <Comments> <summary>Referenced event.</summary> </Comments> </Property> </Node> <Node Name="IUnaryOperation" Base="IOperation" VisitorName="VisitUnaryOperator" HasType="true" HasConstantValue="true"> <OperationKind> <Entry Name="Unary" Value="0x1f" /> <Entry Name="UnaryOperator" Value="0x1f" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;Unary&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents an operation with one operand and a unary operator. <para> Current usage: (1) C# unary operation expression. (2) VB unary operation expression. </para> </summary> </Comments> <Property Name="OperatorKind" Type="UnaryOperatorKind"> <Comments> <summary>Kind of unary operation.</summary> </Comments> </Property> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Operand.</summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a 'lifted' unary operator. When there is an operator that is defined to work on a value type, 'lifted' operators are created to work on the <see cref="System.Nullable{T}" /> versions of those value types. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <see langword="true" /> if overflow checking is performed for the arithmetic operation. </summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> </Node> <Node Name="IBinaryOperation" Base="IOperation" VisitorName="VisitBinaryOperator" ChildrenOrder="LeftOperand,RightOperand" HasType="true" HasConstantValue="true"> <OperationKind> <Entry Name="Binary" Value="0x20" /> <Entry Name="BinaryOperator" Value="0x20" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;Binary&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents an operation with two operands and a binary operator that produces a result with a non-null type. <para> Current usage: (1) C# binary operator expression. (2) VB binary operator expression. </para> </summary> </Comments> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>Kind of binary operation.</summary> </Comments> </Property> <Property Name="LeftOperand" Type="IOperation"> <Comments> <summary>Left operand.</summary> </Comments> </Property> <Property Name="RightOperand" Type="IOperation"> <Comments> <summary>Right operand.</summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a 'lifted' binary operator. When there is an operator that is defined to work on a value type, 'lifted' operators are created to work on the <see cref="System.Nullable{T}" /> versions of those value types. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a 'checked' binary operator. </summary> </Comments> </Property> <Property Name="IsCompareText" Type="bool"> <Comments> <summary> <see langword="true" /> if the comparison is text based for string or object comparison in VB. </summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> <Property Name="UnaryOperatorMethod" Type="IMethodSymbol?" Internal="true"> <Comments> <summary> True/False operator method used for short circuiting. https://github.com/dotnet/roslyn/issues/27598 tracks exposing this information through public API </summary> </Comments> </Property> </Node> <Node Name="IConditionalOperation" Base="IOperation" ChildrenOrder="Condition,WhenTrue,WhenFalse" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a conditional operation with: (1) <see cref="Condition" /> to be tested, (2) <see cref="WhenTrue" /> operation to be executed when <see cref="Condition" /> is true and (3) <see cref="WhenFalse" /> operation to be executed when the <see cref="Condition" /> is false. <para> Current usage: (1) C# ternary expression "a ? b : c" and if statement. (2) VB ternary expression "If(a, b, c)" and If Else statement. </para> </summary> </Comments> <Property Name="Condition" Type="IOperation"> <Comments> <summary>Condition to be tested.</summary> </Comments> </Property> <Property Name="WhenTrue" Type="IOperation"> <Comments> <summary> Operation to be executed if the <see cref="Condition" /> is true. </summary> </Comments> </Property> <Property Name="WhenFalse" Type="IOperation?"> <Comments> <summary> Operation to be executed if the <see cref="Condition" /> is false. </summary> </Comments> </Property> <Property Name="IsRef" Type="bool"> <Comments> <summary>Is result a managed reference</summary> </Comments> </Property> </Node> <Node Name="ICoalesceOperation" Base="IOperation" ChildrenOrder="Value,WhenNull" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a coalesce operation with two operands: (1) <see cref="Value" />, which is the first operand that is unconditionally evaluated and is the result of the operation if non null. (2) <see cref="WhenNull" />, which is the second operand that is conditionally evaluated and is the result of the operation if <see cref="Value" /> is null. <para> Current usage: (1) C# null-coalescing expression "Value ?? WhenNull". (2) VB binary conditional expression "If(Value, WhenNull)". </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Operation to be unconditionally evaluated.</summary> </Comments> </Property> <Property Name="WhenNull" Type="IOperation"> <Comments> <summary> Operation to be conditionally evaluated if <see cref="Value" /> evaluates to null/Nothing. </summary> </Comments> </Property> <Property Name="ValueConversion" Type="CommonConversion"> <Comments> <summary> Conversion associated with <see cref="Value" /> when it is not null/Nothing. Identity if result type of the operation is the same as type of <see cref="Value" />. Otherwise, if type of <see cref="Value" /> is nullable, then conversion is applied to an unwrapped <see cref="Value" />, otherwise to the <see cref="Value" /> itself. </summary> </Comments> </Property> </Node> <Node Name="IAnonymousFunctionOperation" Base="IOperation"> <!-- IAnonymousFunctionOperations do not have a type, users must look at the IConversionOperation on top of this node to get the type of lambda, matching SemanticModel.GetType behavior. --> <Comments> <summary> Represents an anonymous function operation. <para> Current usage: (1) C# lambda expression. (2) VB anonymous delegate expression. </para> </summary> </Comments> <Property Name="Symbol" Type="IMethodSymbol"> <Comments> <summary>Symbol of the anonymous function.</summary> </Comments> </Property> <Property Name="Body" Type="IBlockOperation"> <Comments> <summary>Body of the anonymous function.</summary> </Comments> </Property> </Node> <Node Name="IObjectCreationOperation" Base="IOperation" ChildrenOrder="Arguments,Initializer" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents creation of an object instance. <para> Current usage: (1) C# new expression. (2) VB New expression. </para> </summary> </Comments> <Property Name="Constructor" Type="IMethodSymbol?"> <Comments> <summary>Constructor to be invoked on the created instance.</summary> </Comments> </Property> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?"> <Comments> <summary>Object or collection initializer, if any.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IArgumentOperation&gt;"> <Comments> <summary>Arguments of the object creation, excluding the instance argument. Arguments are in evaluation order.</summary> <remarks> If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays. Default values are supplied for optional arguments missing in source. </remarks> </Comments> </Property> </Node> <Node Name="ITypeParameterObjectCreationOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a creation of a type parameter object, i.e. new T(), where T is a type parameter with new constraint. <para> Current usage: (1) C# type parameter object creation expression. (2) VB type parameter object creation expression. </para> </summary> </Comments> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?"> <Comments> <summary>Object or collection initializer, if any.</summary> </Comments> </Property> </Node> <Node Name="IArrayCreationOperation" Base="IOperation" ChildrenOrder="DimensionSizes,Initializer" HasType="true"> <Comments> <summary> Represents the creation of an array instance. <para> Current usage: (1) C# array creation expression. (2) VB array creation expression. </para> </summary> </Comments> <Property Name="DimensionSizes" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Sizes of the dimensions of the created array instance.</summary> </Comments> </Property> <Property Name="Initializer" Type="IArrayInitializerOperation?"> <Comments> <summary>Values of elements of the created array instance.</summary> </Comments> </Property> </Node> <Node Name="IInstanceReferenceOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an implicit/explicit reference to an instance. <para> Current usage: (1) C# this or base expression. (2) VB Me, MyClass, or MyBase expression. (3) C# object or collection or 'with' expression initializers. (4) VB With statements, object or collection initializers. </para> </summary> </Comments> <Property Name="ReferenceKind" Type="InstanceReferenceKind"> <Comments> <summary>The kind of reference that is being made.</summary> </Comments> </Property> </Node> <Node Name="IIsTypeOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an operation that tests if a value is of a specific type. <para> Current usage: (1) C# "is" operator expression. (2) VB "TypeOf" and "TypeOf IsNot" expression. </para> </summary> </Comments> <Property Name="ValueOperand" Type="IOperation"> <Comments> <summary>Value to test.</summary> </Comments> </Property> <Property Name="TypeOperand" Type="ITypeSymbol"> <Comments> <summary>Type for which to test.</summary> </Comments> </Property> <Property Name="IsNegated" Type="bool"> <Comments> <summary> Flag indicating if this is an "is not" type expression. True for VB "TypeOf ... IsNot ..." expression. False, otherwise. </summary> </Comments> </Property> </Node> <Node Name="IAwaitOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an await operation. <para> Current usage: (1) C# await expression. (2) VB await expression. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Awaited operation.</summary> </Comments> </Property> </Node> <AbstractNode Name="IAssignmentOperation" Base="IOperation"> <Comments> <summary> Represents a base interface for assignments. <para> Current usage: (1) C# simple, compound and deconstruction assignment expressions. (2) VB simple and compound assignment expressions. </para> </summary> </Comments> <Property Name="Target" Type="IOperation"> <Comments> <summary>Target of the assignment.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to be assigned to the target of the assignment.</summary> </Comments> </Property> </AbstractNode> <Node Name="ISimpleAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a simple assignment operation. <para> Current usage: (1) C# simple assignment expression. (2) VB simple assignment expression. </para> </summary> </Comments> <Property Name="IsRef" Type="bool"> <Comments> <summary>Is this a ref assignment</summary> </Comments> </Property> </Node> <Node Name="ICompoundAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true"> <Comments> <summary> Represents a compound assignment that mutates the target with the result of a binary operation. <para> Current usage: (1) C# compound assignment expression. (2) VB compound assignment expression. </para> </summary> </Comments> <Property Name="InConversion" Type="CommonConversion"> <Comments> <summary> Conversion applied to <see cref="IAssignmentOperation.Target" /> before the operation occurs. </summary> </Comments> </Property> <Property Name="OutConversion" Type="CommonConversion"> <Comments> <summary> Conversion applied to the result of the binary operation, before it is assigned back to <see cref="IAssignmentOperation.Target" />. </summary> </Comments> </Property> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>Kind of binary operation.</summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <see langword="true" /> if this assignment contains a 'lifted' binary operation. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <see langword="true" /> if overflow checking is performed for the arithmetic operation. </summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> </Node> <Node Name="IParenthesizedOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a parenthesized operation. <para> Current usage: (1) VB parenthesized expression. </para> </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Operand enclosed in parentheses.</summary> </Comments> </Property> </Node> <Node Name="IEventAssignmentOperation" Base="IOperation" ChildrenOrder="EventReference,HandlerValue" HasType="true"> <Comments> <summary> Represents a binding of an event. <para> Current usage: (1) C# event assignment expression. (2) VB Add/Remove handler statement. </para> </summary> </Comments> <Property Name="EventReference" Type="IOperation"> <Comments> <summary>Reference to the event being bound.</summary> </Comments> </Property> <Property Name="HandlerValue" Type="IOperation"> <Comments> <summary>Handler supplied for the event.</summary> </Comments> </Property> <Property Name="Adds" Type="bool"> <Comments> <summary>True for adding a binding, false for removing one.</summary> </Comments> </Property> </Node> <Node Name="IConditionalAccessOperation" Base="IOperation" ChildrenOrder="Operation,WhenNotNull" HasType="true"> <Comments> <summary> Represents a conditionally accessed operation. Note that <see cref="IConditionalAccessInstanceOperation" /> is used to refer to the value of <see cref="Operation" /> within <see cref="WhenNotNull" />. <para> Current usage: (1) C# conditional access expression (? or ?. operator). (2) VB conditional access expression (? or ?. operator). </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Operation that will be evaluated and accessed if non null.</summary> </Comments> </Property> <Property Name="WhenNotNull" Type="IOperation"> <Comments> <summary> Operation to be evaluated if <see cref="Operation" /> is non null. </summary> </Comments> </Property> </Node> <Node Name="IConditionalAccessInstanceOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents the value of a conditionally-accessed operation within <see cref="IConditionalAccessOperation.WhenNotNull" />. For a conditional access operation of the form <c>someExpr?.Member</c>, this operation is used as the InstanceReceiver for the right operation <c>Member</c>. See https://github.com/dotnet/roslyn/issues/21279#issuecomment-323153041 for more details. <para> Current usage: (1) C# conditional access instance expression. (2) VB conditional access instance expression. </para> </summary> </Comments> </Node> <Node Name="IInterpolatedStringOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents an interpolated string. <para> Current usage: (1) C# interpolated string expression. (2) VB interpolated string expression. </para> </summary> </Comments> <Property Name="Parts" Type="ImmutableArray&lt;IInterpolatedStringContentOperation&gt;"> <Comments> <summary> Constituent parts of interpolated string, each of which is an <see cref="IInterpolatedStringContentOperation" />. </summary> </Comments> </Property> </Node> <Node Name="IAnonymousObjectCreationOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a creation of anonymous object. <para> Current usage: (1) C# "new { ... }" expression (2) VB "New With { ... }" expression </para> </summary> </Comments> <Property Name="Initializers" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary> Property initializers. Each initializer is an <see cref="ISimpleAssignmentOperation" />, with an <see cref="IPropertyReferenceOperation" /> as the target whose Instance is an <see cref="IInstanceReferenceOperation" /> with <see cref="InstanceReferenceKind.ImplicitReceiver" /> kind. </summary> </Comments> </Property> </Node> <Node Name="IObjectOrCollectionInitializerOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an initialization for an object or collection creation. <para> Current usage: (1) C# object or collection initializer expression. (2) VB object or collection initializer expression. For example, object initializer "{ X = x }" within object creation "new Class() { X = x }" and collection initializer "{ x, y, 3 }" within collection creation "new MyList() { x, y, 3 }". </para> </summary> </Comments> <Property Name="Initializers" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Object member or collection initializers.</summary> </Comments> </Property> </Node> <Node Name="IMemberInitializerOperation" Base="IOperation" ChildrenOrder="InitializedMember,Initializer" HasType="true"> <Comments> <summary> Represents an initialization of member within an object initializer with a nested object or collection initializer. <para> Current usage: (1) C# nested member initializer expression. For example, given an object creation with initializer "new Class() { X = x, Y = { x, y, 3 }, Z = { X = z } }", member initializers for Y and Z, i.e. "Y = { x, y, 3 }", and "Z = { X = z }" are nested member initializers represented by this operation. </para> </summary> </Comments> <Property Name="InitializedMember" Type="IOperation"> <Comments> <summary> Initialized member reference <see cref="IMemberReferenceOperation" /> or an invalid operation for error cases. </summary> </Comments> </Property> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation"> <Comments> <summary>Member initializer.</summary> </Comments> </Property> </Node> <Node Name="ICollectionElementInitializerOperation" Base="IOperation" SkipClassGeneration="true"> <Obsolete Error="true">"ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation)</Obsolete> <Comments> <summary> Obsolete interface that used to represent a collection element initializer. It has been replaced by <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />, as appropriate. <para> Current usage: None. This API has been obsoleted in favor of <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />. </para> </summary> </Comments> <Property Name="AddMethod" Type="IMethodSymbol" /> <Property Name="Arguments" Type="ImmutableArray&lt;IOperation&gt;" /> <Property Name="IsDynamic" Type="bool" /> </Node> <Node Name="INameOfOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents an operation that gets a string value for the <see cref="Argument" /> name. <para> Current usage: (1) C# nameof expression. (2) VB NameOf expression. </para> </summary> </Comments> <Property Name="Argument" Type="IOperation"> <Comments> <summary>Argument to the name of operation.</summary> </Comments> </Property> </Node> <Node Name="ITupleOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a tuple with one or more elements. <para> Current usage: (1) C# tuple expression. (2) VB tuple expression. </para> </summary> </Comments> <Property Name="Elements" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Tuple elements.</summary> </Comments> </Property> <Property Name="NaturalType" Type="ITypeSymbol?"> <Comments> <summary> Natural type of the tuple, or null if tuple doesn't have a natural type. Natural type can be different from <see cref="IOperation.Type" /> depending on the conversion context, in which the tuple is used. </summary> </Comments> </Property> </Node> <Node Name="IDynamicObjectCreationOperation" Base="IOperation" SkipClassGeneration="true"> <Comments> <summary> Represents an object creation with a dynamically bound constructor. <para> Current usage: (1) C# "new" expression with dynamic argument(s). (2) VB late bound "New" expression. </para> </summary> </Comments> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?"> <Comments> <summary>Object or collection initializer, if any.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Dynamically bound arguments, excluding the instance argument.</summary> </Comments> </Property> </Node> <Node Name="IDynamicMemberReferenceOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a reference to a member of a class, struct, or module that is dynamically bound. <para> Current usage: (1) C# dynamic member reference expression. (2) VB late bound member reference expression. </para> </summary> </Comments> <Property Name="Instance" Type="IOperation?"> <Comments> <summary>Instance receiver, if it exists.</summary> </Comments> </Property> <Property Name="MemberName" Type="string"> <Comments> <summary>Referenced member.</summary> </Comments> </Property> <Property Name="TypeArguments" Type="ImmutableArray&lt;ITypeSymbol&gt;"> <Comments> <summary>Type arguments.</summary> </Comments> </Property> <Property Name="ContainingType" Type="ITypeSymbol?"> <Comments> <summary> The containing type of the referenced member, if different from type of the <see cref="Instance" />. </summary> </Comments> </Property> </Node> <Node Name="IDynamicInvocationOperation" Base="IOperation" SkipClassGeneration="true"> <Comments> <summary> Represents a invocation that is dynamically bound. <para> Current usage: (1) C# dynamic invocation expression. (2) C# dynamic collection element initializer. For example, in the following collection initializer: <code>new C() { do1, do2, do3 }</code> where the doX objects are of type dynamic, we'll have 3 <see cref="IDynamicInvocationOperation" /> with do1, do2, and do3 as their arguments. (3) VB late bound invocation expression. (4) VB dynamic collection element initializer. Similar to the C# example, <code>New C() From {do1, do2, do3}</code> will generate 3 <see cref="IDynamicInvocationOperation" /> nodes with do1, do2, and do3 as their arguments, respectively. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Dynamically or late bound operation.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Dynamically bound arguments, excluding the instance argument.</summary> </Comments> </Property> </Node> <Node Name="IDynamicIndexerAccessOperation" Base="IOperation" SkipClassGeneration="true"> <Comments> <summary> Represents an indexer access that is dynamically bound. <para> Current usage: (1) C# dynamic indexer access expression. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Dynamically indexed operation.</summary> </Comments> </Property> <Property Name="Arguments" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Dynamically bound arguments, excluding the instance argument.</summary> </Comments> </Property> </Node> <Node Name="ITranslatedQueryOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an unrolled/lowered query operation. For example, for a C# query expression "from x in set where x.Name != null select x.Name", the Operation tree has the following shape: ITranslatedQueryExpression IInvocationExpression ('Select' invocation for "select x.Name") IInvocationExpression ('Where' invocation for "where x.Name != null") IInvocationExpression ('From' invocation for "from x in set") <para> Current usage: (1) C# query expression. (2) VB query expression. </para> </summary> </Comments> <Property Name="Operation" Type="IOperation"> <Comments> <summary>Underlying unrolled operation.</summary> </Comments> </Property> </Node> <Node Name="IDelegateCreationOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a delegate creation. This is created whenever a new delegate is created. <para> Current usage: (1) C# delegate creation expression. (2) VB delegate creation expression. </para> </summary> </Comments> <Property Name="Target" Type="IOperation"> <Comments> <summary>The lambda or method binding that this delegate is created from.</summary> </Comments> </Property> </Node> <Node Name="IDefaultValueOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a default value operation. <para> Current usage: (1) C# default value expression. </para> </summary> </Comments> </Node> <Node Name="ITypeOfOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an operation that gets <see cref="System.Type" /> for the given <see cref="TypeOperand" />. <para> Current usage: (1) C# typeof expression. (2) VB GetType expression. </para> </summary> </Comments> <Property Name="TypeOperand" Type="ITypeSymbol"> <Comments> <summary>Type operand.</summary> </Comments> </Property> </Node> <Node Name="ISizeOfOperation" Base="IOperation" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents an operation to compute the size of a given type. <para> Current usage: (1) C# sizeof expression. </para> </summary> </Comments> <Property Name="TypeOperand" Type="ITypeSymbol"> <Comments> <summary>Type operand.</summary> </Comments> </Property> </Node> <Node Name="IAddressOfOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an operation that creates a pointer value by taking the address of a reference. <para> Current usage: (1) C# address of expression </para> </summary> </Comments> <Property Name="Reference" Type="IOperation"> <Comments> <summary>Addressed reference.</summary> </Comments> </Property> </Node> <Node Name="IIsPatternOperation" Base="IOperation" ChildrenOrder="Value,Pattern" HasType="true"> <Comments> <summary> Represents an operation that tests if a value matches a specific pattern. <para> Current usage: (1) C# is pattern expression. For example, "x is int i". </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Underlying operation to test.</summary> </Comments> </Property> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>Pattern.</summary> </Comments> </Property> </Node> <Node Name="IIncrementOrDecrementOperation" Base="IOperation" HasType="true"> <OperationKind> <Entry Name="Increment" Value="0x42" ExtraDescription="This is used as an increment operator"/> <Entry Name="Decrement" Value="0x44" ExtraDescription="This is used as a decrement operator"/> </OperationKind> <Comments> <summary> Represents an <see cref="OperationKind.Increment" /> or <see cref="OperationKind.Decrement" /> operation. Note that this operation is different from an <see cref="IUnaryOperation" /> as it mutates the <see cref="Target" />, while unary operator expression does not mutate it's operand. <para> Current usage: (1) C# increment expression or decrement expression. </para> </summary> </Comments> <Property Name="IsPostfix" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a postfix expression. <see langword="false" /> if this is a prefix expression. </summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <see langword="true" /> if this is a 'lifted' increment operator. When there is an operator that is defined to work on a value type, 'lifted' operators are created to work on the <see cref="System.Nullable{T}" /> versions of those value types. </summary> </Comments> </Property> <Property Name="IsChecked" Type="bool"> <Comments> <summary> <see langword="true" /> if overflow checking is performed for the arithmetic operation. </summary> </Comments> </Property> <Property Name="Target" Type="IOperation"> <Comments> <summary>Target of the assignment.</summary> </Comments> </Property> <Property Name="OperatorMethod" Type="IMethodSymbol?"> <Comments> <summary>Operator method used by the operation, null if the operation does not use an operator method.</summary> </Comments> </Property> </Node> <Node Name="IThrowOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an operation to throw an exception. <para> Current usage: (1) C# throw expression. (2) C# throw statement. (2) VB Throw statement. </para> </summary> </Comments> <Property Name="Exception" Type="IOperation?"> <Comments> <summary>Instance of an exception being thrown.</summary> </Comments> </Property> </Node> <Node Name="IDeconstructionAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true"> <Comments> <summary> Represents a assignment with a deconstruction. <para> Current usage: (1) C# deconstruction assignment expression. </para> </summary> </Comments> </Node> <Node Name="IDeclarationExpressionOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents a declaration expression operation. Unlike a regular variable declaration <see cref="IVariableDeclaratorOperation" /> and <see cref="IVariableDeclarationOperation" />, this operation represents an "expression" declaring a variable. <para> Current usage: (1) C# declaration expression. For example, (a) "var (x, y)" is a deconstruction declaration expression with variables x and y. (b) "(var x, var y)" is a tuple expression with two declaration expressions. (c) "M(out var x);" is an invocation expression with an out "var x" declaration expression. </para> </summary> </Comments> <Property Name="Expression" Type="IOperation"> <Comments> <summary>Underlying expression.</summary> </Comments> </Property> </Node> <Node Name="IOmittedArgumentOperation" Base="IOperation" HasType="true"> <Comments> <summary> Represents an argument value that has been omitted in an invocation. <para> Current usage: (1) VB omitted argument in an invocation expression. </para> </summary> </Comments> </Node> <AbstractNode Name="ISymbolInitializerOperation" Base="IOperation"> <Comments> <summary> Represents an initializer for a field, property, parameter or a local variable declaration. <para> Current usage: (1) C# field, property, parameter or local variable initializer. (2) VB field(s), property, parameter or local variable initializer. </para> </summary> </Comments> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Local declared in and scoped to the <see cref="Value" />. </summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Underlying initializer value.</summary> </Comments> </Property> </AbstractNode> <Node Name="IFieldInitializerOperation" Base="ISymbolInitializerOperation"> <Comments> <summary> Represents an initialization of a field. <para> Current usage: (1) C# field initializer with equals value clause. (2) VB field(s) initializer with equals value clause or AsNew clause. Multiple fields can be initialized with AsNew clause in VB. </para> </summary> </Comments> <Property Name="InitializedFields" Type="ImmutableArray&lt;IFieldSymbol&gt;"> <Comments> <summary>Initialized fields. There can be multiple fields for Visual Basic fields declared with AsNew clause.</summary> </Comments> </Property> </Node> <Node Name="IVariableInitializerOperation" Base="ISymbolInitializerOperation"> <Comments> <summary> Represents an initialization of a local variable. <para> Current usage: (1) C# local variable initializer with equals value clause. (2) VB local variable initializer with equals value clause or AsNew clause. </para> </summary> </Comments> </Node> <Node Name="IPropertyInitializerOperation" Base="ISymbolInitializerOperation"> <Comments> <summary> Represents an initialization of a property. <para> Current usage: (1) C# property initializer with equals value clause. (2) VB property initializer with equals value clause or AsNew clause. Multiple properties can be initialized with 'WithEvents' declaration with AsNew clause in VB. </para> </summary> </Comments> <Property Name="InitializedProperties" Type="ImmutableArray&lt;IPropertySymbol&gt;"> <Comments> <summary>Initialized properties. There can be multiple properties for Visual Basic 'WithEvents' declaration with AsNew clause.</summary> </Comments> </Property> </Node> <Node Name="IParameterInitializerOperation" Base="ISymbolInitializerOperation"> <Comments> <summary> Represents an initialization of a parameter at the point of declaration. <para> Current usage: (1) C# parameter initializer with equals value clause. (2) VB parameter initializer with equals value clause. </para> </summary> </Comments> <Property Name="Parameter" Type="IParameterSymbol"> <Comments> <summary>Initialized parameter.</summary> </Comments> </Property> </Node> <Node Name="IArrayInitializerOperation" Base="IOperation"> <Comments> <summary> Represents the initialization of an array instance. <para> Current usage: (1) C# array initializer. (2) VB array initializer. </para> </summary> </Comments> <Property Name="ElementValues" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Values to initialize array elements.</summary> </Comments> </Property> </Node> <Node Name="IVariableDeclaratorOperation" Base="IOperation" ChildrenOrder="IgnoredArguments,Initializer"> <Comments> <summary>Represents a single variable declarator and initializer.</summary> <para> Current Usage: (1) C# variable declarator (2) C# catch variable declaration (3) VB single variable declaration (4) VB catch variable declaration </para> <remarks> In VB, the initializer for this node is only ever used for explicit array bounds initializers. This node corresponds to the VariableDeclaratorSyntax in C# and the ModifiedIdentifierSyntax in VB. </remarks> </Comments> <Property Name="Symbol" Type="ILocalSymbol"> <Comments> <summary>Symbol declared by this variable declaration</summary> </Comments> </Property> <Property Name="Initializer" Type="IVariableInitializerOperation?"> <Comments> <summary>Optional initializer of the variable.</summary> <remarks> If this variable is in an <see cref="IVariableDeclarationOperation" />, the initializer may be located in the parent operation. Call <see cref="OperationExtensions.GetVariableInitializer(IVariableDeclaratorOperation)" /> to check in all locations. It is only possible to have initializers in both locations in VB invalid code scenarios. </remarks> </Comments> </Property> <Property Name="IgnoredArguments" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary> Additional arguments supplied to the declarator in error cases, ignored by the compiler. This only used for the C# case of DeclaredArgumentSyntax nodes on a VariableDeclaratorSyntax. </summary> </Comments> </Property> </Node> <Node Name="IVariableDeclarationOperation" Base="IOperation" ChildrenOrder="IgnoredDimensions,Declarators,Initializer"> <Comments> <summary>Represents a declarator that declares multiple individual variables.</summary> <para> Current Usage: (1) C# VariableDeclaration (2) C# fixed declarations (3) VB Dim statement declaration groups (4) VB Using statement variable declarations </para> <remarks> The initializer of this node is applied to all individual declarations in <see cref="Declarators" />. There cannot be initializers in both locations except in invalid code scenarios. In C#, this node will never have an initializer. This corresponds to the VariableDeclarationSyntax in C#, and the VariableDeclaratorSyntax in Visual Basic. </remarks> </Comments> <Property Name="Declarators" Type="ImmutableArray&lt;IVariableDeclaratorOperation&gt;"> <Comments> <summary>Individual variable declarations declared by this multiple declaration.</summary> <remarks> All <see cref="IVariableDeclarationGroupOperation" /> will have at least 1 <see cref="IVariableDeclarationOperation" />, even if the declaration group only declares 1 variable. </remarks> </Comments> </Property> <Property Name="Initializer" Type="IVariableInitializerOperation?"> <Comments> <summary>Optional initializer of the variable.</summary> <remarks>In C#, this will always be null.</remarks> </Comments> </Property> <Property Name="IgnoredDimensions" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary> Array dimensions supplied to an array declaration in error cases, ignored by the compiler. This is only used for the C# case of RankSpecifierSyntax nodes on an ArrayTypeSyntax. </summary> </Comments> </Property> </Node> <Node Name="IArgumentOperation" Base="IOperation"> <Comments> <summary> Represents an argument to a method invocation. <para> Current usage: (1) C# argument to an invocation expression, object creation expression, etc. (2) VB argument to an invocation expression, object creation expression, etc. </para> </summary> </Comments> <Property Name="ArgumentKind" Type="ArgumentKind"> <Comments> <summary>Kind of argument.</summary> </Comments> </Property> <Property Name="Parameter" Type="IParameterSymbol?"> <Comments> <summary>Parameter the argument matches. This can be null for __arglist parameters.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value supplied for the argument.</summary> </Comments> </Property> <Property Name="InConversion" Type="CommonConversion"> <Comments> <summary>Information of the conversion applied to the argument value passing it into the target method. Applicable only to VB Reference arguments.</summary> </Comments> </Property> <Property Name="OutConversion" Type="CommonConversion"> <Comments> <summary>Information of the conversion applied to the argument value after the invocation. Applicable only to VB Reference arguments.</summary> </Comments> </Property> </Node> <Node Name="ICatchClauseOperation" Base="IOperation" ChildrenOrder="ExceptionDeclarationOrExpression,Filter,Handler"> <Comments> <summary> Represents a catch clause. <para> Current usage: (1) C# catch clause. (2) VB Catch clause. </para> </summary> </Comments> <Property Name="ExceptionDeclarationOrExpression" Type="IOperation?"> <Comments> <summary> Optional source for exception. This could be any of the following operation: 1. Declaration for the local catch variable bound to the caught exception (C# and VB) OR 2. Null, indicating no declaration or expression (C# and VB) 3. Reference to an existing local or parameter (VB) OR 4. Other expression for error scenarios (VB) </summary> </Comments> </Property> <Property Name="ExceptionType" Type="ITypeSymbol"> <Comments> <summary>Type of the exception handled by the catch clause.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary> Locals declared by the <see cref="ExceptionDeclarationOrExpression" /> and/or <see cref="Filter" /> clause. </summary> </Comments> </Property> <Property Name="Filter" Type="IOperation?"> <Comments> <summary>Filter operation to be executed to determine whether to handle the exception.</summary> </Comments> </Property> <Property Name="Handler" Type="IBlockOperation"> <Comments> <summary>Body of the exception handler.</summary> </Comments> </Property> </Node> <Node Name="ISwitchCaseOperation" Base="IOperation" ChildrenOrder="Clauses,Body"> <Comments> <summary> Represents a switch case section with one or more case clauses to match and one or more operations to execute within the section. <para> Current usage: (1) C# switch section for one or more case clause and set of statements to execute. (2) VB case block with a case statement for one or more case clause and set of statements to execute. </para> </summary> </Comments> <Property Name="Clauses" Type="ImmutableArray&lt;ICaseClauseOperation&gt;"> <Comments> <summary>Clauses of the case.</summary> </Comments> </Property> <Property Name="Body" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>One or more operations to execute within the switch section.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Locals declared within the switch case section scoped to the section.</summary> </Comments> </Property> <Property Name="Condition" Type="IOperation?" Internal="true"> <Comments> <summary> Optional combined logical condition that accounts for all <see cref="Clauses"/>. An instance of <see cref="IPlaceholderOperation"/> with kind <see cref="PlaceholderKind.SwitchOperationExpression"/> is used to refer to the <see cref="ISwitchOperation.Value"/> in context of this expression. It is not part of <see cref="Children"/> list and likely contains duplicate nodes for nodes exposed by <see cref="Clauses"/>, like <see cref="ISingleValueCaseClauseOperation.Value"/>, etc. Never set for C# at the moment. </summary> </Comments> </Property> </Node> <AbstractNode Name="ICaseClauseOperation" Base="IOperation"> <OperationKind Include="true" ExtraDescription="This is further differentiated by &lt;see cref=&quot;ICaseClauseOperation.CaseKind&quot;/&gt;." /> <Comments> <summary> Represents a case clause. <para> Current usage: (1) C# case clause. (2) VB Case clause. </para> </summary> </Comments> <Property Name="CaseKind" Type="CaseKind" MakeAbstract="true"> <Comments> <summary>Kind of the clause.</summary> </Comments> </Property> <Property Name="Label" Type="ILabelSymbol?"> <Comments> <summary>Label associated with the case clause, if any.</summary> </Comments> </Property> </AbstractNode> <Node Name="IDefaultCaseClauseOperation" Base="ICaseClauseOperation"> <OperationKind Include="false" /> <Comments> <summary> Represents a default case clause. <para> Current usage: (1) C# default clause. (2) VB Case Else clause. </para> </summary> </Comments> </Node> <Node Name="IPatternCaseClauseOperation" Base="ICaseClauseOperation" ChildrenOrder="Pattern,Guard"> <OperationKind Include="false" /> <Comments> <summary> Represents a case clause with a pattern and an optional guard operation. <para> Current usage: (1) C# pattern case clause. </para> </summary> </Comments> <Property Name="Label" Type="ILabelSymbol" New="true"> <Comments> <!-- It would be a binary breaking change to remove this --> <summary> Label associated with the case clause. </summary> </Comments> </Property> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>Pattern associated with case clause.</summary> </Comments> </Property> <Property Name="Guard" Type="IOperation?"> <Comments> <summary>Guard associated with the pattern case clause.</summary> </Comments> </Property> </Node> <Node Name="IRangeCaseClauseOperation" Base="ICaseClauseOperation" ChildrenOrder="MinimumValue,MaximumValue"> <OperationKind Include="false" /> <Comments> <summary> Represents a case clause with range of values for comparison. <para> Current usage: (1) VB range case clause of the form "Case x To y". </para> </summary> </Comments> <Property Name="MinimumValue" Type="IOperation"> <Comments> <summary>Minimum value of the case range.</summary> </Comments> </Property> <Property Name="MaximumValue" Type="IOperation"> <Comments> <summary>Maximum value of the case range.</summary> </Comments> </Property> </Node> <Node Name="IRelationalCaseClauseOperation" Base="ICaseClauseOperation"> <OperationKind Include="false" /> <Comments> <summary> Represents a case clause with custom relational operator for comparison. <para> Current usage: (1) VB relational case clause of the form "Case Is op x". </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Case value.</summary> </Comments> </Property> <Property Name="Relation" Type="BinaryOperatorKind"> <Comments> <summary>Relational operator used to compare the switch value with the case value.</summary> </Comments> </Property> </Node> <Node Name="ISingleValueCaseClauseOperation" Base="ICaseClauseOperation"> <OperationKind Include="false" /> <Comments> <summary> Represents a case clause with a single value for comparison. <para> Current usage: (1) C# case clause of the form "case x" (2) VB case clause of the form "Case x". </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Case value.</summary> </Comments> </Property> </Node> <AbstractNode Name="IInterpolatedStringContentOperation" Base="IOperation"> <Comments> <summary> Represents a constituent part of an interpolated string. <para> Current usage: (1) C# interpolated string content. (2) VB interpolated string content. </para> </summary> </Comments> </AbstractNode> <Node Name="IInterpolatedStringTextOperation" Base="IInterpolatedStringContentOperation"> <Comments> <summary> Represents a constituent string literal part of an interpolated string operation. <para> Current usage: (1) C# interpolated string text. (2) VB interpolated string text. </para> </summary> </Comments> <Property Name="Text" Type="IOperation"> <Comments> <summary>Text content.</summary> </Comments> </Property> </Node> <Node Name="IInterpolationOperation" Base="IInterpolatedStringContentOperation" ChildrenOrder="Expression,Alignment,FormatString"> <Comments> <summary> Represents a constituent interpolation part of an interpolated string operation. <para> Current usage: (1) C# interpolation part. (2) VB interpolation part. </para> </summary> </Comments> <Property Name="Expression" Type="IOperation"> <Comments> <summary>Expression of the interpolation.</summary> </Comments> </Property> <Property Name="Alignment" Type="IOperation?"> <Comments> <summary>Optional alignment of the interpolation.</summary> </Comments> </Property> <Property Name="FormatString" Type="IOperation?"> <Comments> <summary>Optional format string of the interpolation.</summary> </Comments> </Property> </Node> <AbstractNode Name="IPatternOperation" Base="IOperation"> <Comments> <summary> Represents a pattern matching operation. <para> Current usage: (1) C# pattern. </para> </summary> </Comments> <Property Name="InputType" Type="ITypeSymbol"> <Comments> <summary>The input type to the pattern-matching operation.</summary> </Comments> </Property> <Property Name="NarrowedType" Type="ITypeSymbol"> <Comments> <summary>The narrowed type of the pattern-matching operation.</summary> </Comments> </Property> </AbstractNode> <Node Name="IConstantPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a pattern with a constant value. <para> Current usage: (1) C# constant pattern. </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Constant value of the pattern operation.</summary> </Comments> </Property> </Node> <Node Name="IDeclarationPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a pattern that declares a symbol. <para> Current usage: (1) C# declaration pattern. </para> </summary> </Comments> <Property Name="MatchedType" Type="ITypeSymbol?"> <Comments> <summary> The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#). </summary> </Comments> </Property> <Property Name="MatchesNull" Type="bool"> <Comments> <summary> True if the pattern is of a form that accepts null. For example, in C# the pattern `var x` will match a null input, while the pattern `string x` will not. </summary> </Comments> </Property> <Property Name="DeclaredSymbol" Type="ISymbol?"> <Comments> <summary>Symbol declared by the pattern, if any.</summary> </Comments> </Property> </Node> <Node Name="ITupleBinaryOperation" Base="IOperation" VisitorName="VisitTupleBinaryOperator" ChildrenOrder="LeftOperand,RightOperand" HasType="true"> <OperationKind> <Entry Name="TupleBinary" Value="0x57" /> <Entry Name="TupleBinaryOperator" Value="0x57" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;TupleBinary&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents a comparison of two operands that returns a bool type. <para> Current usage: (1) C# tuple binary operator expression. </para> </summary> </Comments> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>Kind of binary operation.</summary> </Comments> </Property> <Property Name="LeftOperand" Type="IOperation"> <Comments> <summary>Left operand.</summary> </Comments> </Property> <Property Name="RightOperand" Type="IOperation"> <Comments> <summary>Right operand.</summary> </Comments> </Property> </Node> <AbstractNode Name="IMethodBodyBaseOperation" Base="IOperation"> <Comments> <summary> Represents a method body operation. <para> Current usage: (1) C# method body </para> </summary> </Comments> <Property Name="BlockBody" Type="IBlockOperation?"> <Comments> <summary>Method body corresponding to BaseMethodDeclarationSyntax.Body or AccessorDeclarationSyntax.Body</summary> </Comments> </Property> <Property Name="ExpressionBody" Type="IBlockOperation?"> <Comments> <summary>Method body corresponding to BaseMethodDeclarationSyntax.ExpressionBody or AccessorDeclarationSyntax.ExpressionBody</summary> </Comments> </Property> </AbstractNode> <Node Name="IMethodBodyOperation" Base="IMethodBodyBaseOperation" VisitorName="VisitMethodBodyOperation" ChildrenOrder="BlockBody,ExpressionBody"> <OperationKind> <Entry Name="MethodBody" Value="0x58" /> <Entry Name="MethodBodyOperation" Value="0x58" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;MethodBody&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents a method body operation. <para> Current usage: (1) C# method body for non-constructor </para> </summary> </Comments> </Node> <Node Name="IConstructorBodyOperation" Base="IMethodBodyBaseOperation" VisitorName="VisitConstructorBodyOperation" ChildrenOrder="Initializer,BlockBody,ExpressionBody"> <OperationKind> <Entry Name="ConstructorBody" Value="0x59" /> <Entry Name="ConstructorBodyOperation" Value="0x59" EditorBrowsable="false" ExtraDescription="Use &lt;see cref=&quot;ConstructorBody&quot;/&gt; instead." /> </OperationKind> <Comments> <summary> Represents a constructor method body operation. <para> Current usage: (1) C# method body for constructor declaration </para> </summary> </Comments> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Local declarations contained within the <see cref="Initializer" />.</summary> </Comments> </Property> <Property Name="Initializer" Type="IOperation?"> <Comments> <summary>Constructor initializer, if any.</summary> </Comments> </Property> </Node> <Node Name="IDiscardOperation" Base="IOperation" VisitorName="VisitDiscardOperation" HasType="true"> <Comments> <summary> Represents a discard operation. <para> Current usage: C# discard expressions </para> </summary> </Comments> <Property Name="DiscardSymbol" Type="IDiscardSymbol"> <Comments> <summary>The symbol of the discard operation.</summary> </Comments> </Property> </Node> <Node Name="IFlowCaptureOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true"> <Comments> <summary> Represents that an intermediate result is being captured. This node is produced only as part of a <see cref="ControlFlowGraph" />. </summary> </Comments> <Property Name="Id" Type="CaptureId"> <Comments> <summary>An id used to match references to the same intermediate result.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to be captured.</summary> </Comments> </Property> </Node> <Node Name="IFlowCaptureReferenceOperation" Base="IOperation" Namespace="FlowAnalysis" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents a point of use of an intermediate result captured earlier. The fact of capturing the result is represented by <see cref="IFlowCaptureOperation" />. This node is produced only as part of a <see cref="ControlFlowGraph" />. </summary> </Comments> <Property Name="Id" Type="CaptureId"> <Comments> <summary>An id used to match references to the same intermediate result.</summary> </Comments> </Property> </Node> <Node Name="IIsNullOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true" HasConstantValue="true"> <Comments> <summary> Represents result of checking whether the <see cref="Operand" /> is null. For reference types this checks if the <see cref="Operand" /> is a null reference, for nullable types this checks if the <see cref="Operand" /> doesn’t have a value. The node is produced as part of a flow graph during rewrite of <see cref="ICoalesceOperation" /> and <see cref="IConditionalAccessOperation" /> nodes. </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Value to check.</summary> </Comments> </Property> </Node> <Node Name="ICaughtExceptionOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true"> <Comments> <summary> Represents a exception instance passed by an execution environment to an exception filter or handler. This node is produced only as part of a <see cref="ControlFlowGraph" />. </summary> </Comments> </Node> <Node Name="IStaticLocalInitializationSemaphoreOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true"> <Comments> <summary> Represents the check during initialization of a VB static local that is initialized on the first call of the function, and never again. If the semaphore operation returns true, the static local has not yet been initialized, and the initializer will be run. If it returns false, then the local has already been initialized, and the static local initializer region will be skipped. This node is produced only as part of a <see cref="ControlFlowGraph" />. </summary> </Comments> <Property Name="Local" Type="ILocalSymbol"> <Comments> <summary>The static local variable that is possibly initialized.</summary> </Comments> </Property> </Node> <Node Name="IFlowAnonymousFunctionOperation" Base="IOperation" Namespace="FlowAnalysis" SkipClassGeneration="true"> <Comments> <summary> Represents an anonymous function operation in context of a <see cref="ControlFlowGraph" />. <para> Current usage: (1) C# lambda expression. (2) VB anonymous delegate expression. </para> A <see cref="ControlFlowGraph" /> for the body of the anonymous function is available from the enclosing <see cref="ControlFlowGraph" />. </summary> </Comments> <Property Name="Symbol" Type="IMethodSymbol"> <Comments> <summary>Symbol of the anonymous function.</summary> </Comments> </Property> </Node> <Node Name="ICoalesceAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true"> <Comments> <summary> Represents a coalesce assignment operation with a target and a conditionally-evaluated value: (1) <see cref="IAssignmentOperation.Target" /> is evaluated for null. If it is null, <see cref="IAssignmentOperation.Value" /> is evaluated and assigned to target. (2) <see cref="IAssignmentOperation.Value" /> is conditionally evaluated if <see cref="IAssignmentOperation.Target" /> is null, and the result is assigned into <see cref="IAssignmentOperation.Target" />. The result of the entire expression is<see cref="IAssignmentOperation.Target" />, which is only evaluated once. <para> Current usage: (1) C# null-coalescing assignment operation <code>Target ??= Value</code>. </para> </summary> </Comments> </Node> <Node Name="IRangeOperation" Base="IOperation" VisitorName="VisitRangeOperation" ChildrenOrder="LeftOperand,RightOperand" HasType="true"> <Comments> <summary> Represents a range operation. <para> Current usage: (1) C# range expressions </para> </summary> </Comments> <Property Name="LeftOperand" Type="IOperation?"> <Comments> <summary>Left operand.</summary> </Comments> </Property> <Property Name="RightOperand" Type="IOperation?"> <Comments> <summary>Right operand.</summary> </Comments> </Property> <Property Name="IsLifted" Type="bool"> <Comments> <summary> <code>true</code> if this is a 'lifted' range operation. When there is an operator that is defined to work on a value type, 'lifted' operators are created to work on the <see cref="System.Nullable{T}" /> versions of those value types. </summary> </Comments> </Property> <Property Name="Method" Type="IMethodSymbol?"> <Comments> <summary> Factory method used to create this Range value. Can be null if appropriate symbol was not found. </summary> </Comments> </Property> </Node> <Node Name="IReDimOperation" Base="IOperation"> <Comments> <summary> Represents the ReDim operation to re-allocate storage space for array variables. <para> Current usage: (1) VB ReDim statement. </para> </summary> </Comments> <Property Name="Clauses" Type="ImmutableArray&lt;IReDimClauseOperation&gt;"> <Comments> <summary>Individual clauses of the ReDim operation.</summary> </Comments> </Property> <Property Name="Preserve" Type="bool"> <Comments> <summary>Modifier used to preserve the data in the existing array when you change the size of only the last dimension.</summary> </Comments> </Property> </Node> <Node Name="IReDimClauseOperation" Base="IOperation" ChildrenOrder="Operand,DimensionSizes"> <Comments> <summary> Represents an individual clause of an <see cref="IReDimOperation" /> to re-allocate storage space for a single array variable. <para> Current usage: (1) VB ReDim clause. </para> </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Operand whose storage space needs to be re-allocated.</summary> </Comments> </Property> <Property Name="DimensionSizes" Type="ImmutableArray&lt;IOperation&gt;"> <Comments> <summary>Sizes of the dimensions of the created array instance.</summary> </Comments> </Property> </Node> <Node Name="IRecursivePatternOperation" Base="IPatternOperation" ChildrenOrder="DeconstructionSubpatterns,PropertySubpatterns"> <Comments> <summary>Represents a C# recursive pattern.</summary> </Comments> <Property Name="MatchedType" Type="ITypeSymbol"> <Comments> <summary>The type accepted for the recursive pattern.</summary> </Comments> </Property> <Property Name="DeconstructSymbol" Type="ISymbol?"> <Comments> <summary> The symbol, if any, used for the fetching values for subpatterns. This is either a <code>Deconstruct</code> method, the type <code>System.Runtime.CompilerServices.ITuple</code>, or null (for example, in error cases or when matching a tuple type). </summary> </Comments> </Property> <Property Name="DeconstructionSubpatterns" Type="ImmutableArray&lt;IPatternOperation&gt;"> <Comments> <summary>This contains the patterns contained within a deconstruction or positional subpattern.</summary> </Comments> </Property> <Property Name="PropertySubpatterns" Type="ImmutableArray&lt;IPropertySubpatternOperation&gt;"> <Comments> <summary>This contains the (symbol, property) pairs within a property subpattern.</summary> </Comments> </Property> <Property Name="DeclaredSymbol" Type="ISymbol?"> <Comments> <summary>Symbol declared by the pattern.</summary> </Comments> </Property> </Node> <Node Name="IDiscardPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a discard pattern. <para> Current usage: C# discard pattern </para> </summary> </Comments> </Node> <Node Name="ISwitchExpressionOperation" Base="IOperation" ChildrenOrder="Value,Arms" HasType="true"> <Comments> <summary> Represents a switch expression. <para> Current usage: (1) C# switch expression. </para> </summary> </Comments> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to be switched upon.</summary> </Comments> </Property> <Property Name="Arms" Type="ImmutableArray&lt;ISwitchExpressionArmOperation&gt;"> <Comments> <summary>Arms of the switch expression.</summary> </Comments> </Property> <Property Name="IsExhaustive" Type="bool"> <Comments> <summary>True if the switch expressions arms cover every possible input value.</summary> </Comments> </Property> </Node> <Node Name="ISwitchExpressionArmOperation" Base="IOperation" ChildrenOrder="Pattern,Guard,Value"> <Comments> <summary>Represents one arm of a switch expression.</summary> </Comments> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>The pattern to match.</summary> </Comments> </Property> <Property Name="Guard" Type="IOperation?"> <Comments> <summary>Guard (when clause expression) associated with the switch arm, if any.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Result value of the enclosing switch expression when this arm matches.</summary> </Comments> </Property> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Locals declared within the switch arm (e.g. pattern locals and locals declared in the guard) scoped to the arm.</summary> </Comments> </Property> </Node> <Node Name="IPropertySubpatternOperation" Base="IOperation" ChildrenOrder="Member,Pattern"> <Comments> <summary> Represents an element of a property subpattern, which identifies a member to be matched and the pattern to match it against. </summary> </Comments> <Property Name="Member" Type="IOperation"> <Comments> <summary> The member being matched in a property subpattern. This can be a <see cref="IMemberReferenceOperation" /> in non-error cases, or an <see cref="IInvalidOperation" /> in error cases. </summary> </Comments> </Property> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>The pattern to which the member is matched in a property subpattern.</summary> </Comments> </Property> </Node> <Node Name="IAggregateQueryOperation" Base="IOperation" Internal="true" ChildrenOrder="Group,Aggregation" HasType="true"> <Comments> <summary>Represents a standalone VB query Aggregate operation with more than one item in Into clause.</summary> </Comments> <Property Name="Group" Type="IOperation" /> <Property Name="Aggregation" Type="IOperation" /> </Node> <Node Name="IFixedOperation" Base="IOperation" Internal="true" SkipInVisitor="true" ChildrenOrder="Variables,Body"> <!-- Making this public is tracked by https://github.com/dotnet/roslyn/issues/21281 --> <Comments> <summary>Represents a C# fixed statement.</summary> </Comments> <Property Name="Locals" Type="ImmutableArray&lt;ILocalSymbol&gt;"> <Comments> <summary>Locals declared.</summary> </Comments> </Property> <Property Name="Variables" Type="IVariableDeclarationGroupOperation"> <Comments> <summary>Variables to be fixed.</summary> </Comments> </Property> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the fixed, over which the variables are fixed.</summary> </Comments> </Property> </Node> <Node Name="INoPiaObjectCreationOperation" Base="IOperation" Internal="true" HasType="true"> <Comments> <summary> Represents a creation of an instance of a NoPia interface, i.e. new I(), where I is an embedded NoPia interface. <para> Current usage: (1) C# NoPia interface instance creation expression. (2) VB NoPia interface instance creation expression. </para> </summary> </Comments> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?"> <Comments> <summary>Object or collection initializer, if any.</summary> </Comments> </Property> </Node> <Node Name="IPlaceholderOperation" Base="IOperation" Internal="true" HasType="true"> <Comments> <summary> Represents a general placeholder when no more specific kind of placeholder is available. A placeholder is an expression whose meaning is inferred from context. </summary> </Comments> <Property Name="PlaceholderKind" Type="PlaceholderKind" /> </Node> <Node Name="IPointerIndirectionReferenceOperation" Base="IOperation" SkipClassGeneration="true" Internal="true" HasType="true"> <Comments> <summary> Represents a reference through a pointer. <para> Current usage: (1) C# pointer indirection reference expression. </para> </summary> </Comments> <Property Name="Pointer" Type="IOperation"> <Comments> <summary>Pointer to be dereferenced.</summary> </Comments> </Property> </Node> <Node Name="IWithStatementOperation" Base="IOperation" Internal="true" ChildrenOrder="Value,Body"> <Comments> <summary> Represents a <see cref="Body" /> of operations that are executed with implicit reference to the <see cref="Value" /> for member references. <para> Current usage: (1) VB With statement. </para> </summary> </Comments> <Property Name="Body" Type="IOperation"> <Comments> <summary>Body of the with.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Value to whose members leading-dot-qualified references within the with body bind.</summary> </Comments> </Property> </Node> <Node Name="IUsingDeclarationOperation" Base="IOperation"> <Comments> <summary> Represents using variable declaration, with scope spanning across the parent <see cref="IBlockOperation"/>. <para> Current Usage: (1) C# using declaration (1) C# asynchronous using declaration </para> </summary> </Comments> <Property Name="DeclarationGroup" Type="IVariableDeclarationGroupOperation"> <Comments> <summary>The variables declared by this using declaration.</summary> </Comments> </Property> <Property Name="IsAsynchronous" Type="bool"> <Comments> <summary>True if this is an asynchronous using declaration.</summary> </Comments> </Property> <Property Name="DisposeInfo" Type="DisposeOperationInfo" Internal="true"> <Comments> <summary>Information about the method that will be invoked to dispose the declared instances when pattern based disposal is used.</summary> </Comments> </Property> </Node> <Node Name="INegatedPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a negated pattern. <para> Current usage: (1) C# negated pattern. </para> </summary> </Comments> <Property Name="Pattern" Type="IPatternOperation"> <Comments> <summary>The negated pattern.</summary> </Comments> </Property> </Node> <Node Name="IBinaryPatternOperation" Base="IPatternOperation" ChildrenOrder="LeftPattern,RightPattern"> <Comments> <summary> Represents a binary ("and" or "or") pattern. <para> Current usage: (1) C# "and" and "or" patterns. </para> </summary> </Comments> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>Kind of binary pattern; either <see cref="BinaryOperatorKind.And"/> or <see cref="BinaryOperatorKind.Or"/>.</summary> </Comments> </Property> <Property Name="LeftPattern" Type="IPatternOperation"> <Comments> <summary>The pattern on the left.</summary> </Comments> </Property> <Property Name="RightPattern" Type="IPatternOperation"> <Comments> <summary>The pattern on the right.</summary> </Comments> </Property> </Node> <Node Name="ITypePatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a pattern comparing the input with a given type. <para> Current usage: (1) C# type pattern. </para> </summary> </Comments> <Property Name="MatchedType" Type="ITypeSymbol"> <Comments> <summary> The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#). </summary> </Comments> </Property> </Node> <Node Name="IRelationalPatternOperation" Base="IPatternOperation"> <Comments> <summary> Represents a pattern comparing the input with a constant value using a relational operator. <para> Current usage: (1) C# relational pattern. </para> </summary> </Comments> <Property Name="OperatorKind" Type="BinaryOperatorKind"> <Comments> <summary>The kind of the relational operator.</summary> </Comments> </Property> <Property Name="Value" Type="IOperation"> <Comments> <summary>Constant value of the pattern operation.</summary> </Comments> </Property> </Node> <Node Name="IWithOperation" Base="IOperation" ChildrenOrder="Operand,Initializer" HasType="true"> <Comments> <summary> Represents cloning of an object instance. <para> Current usage: (1) C# with expression. </para> </summary> </Comments> <Property Name="Operand" Type="IOperation"> <Comments> <summary>Operand to be cloned.</summary> </Comments> </Property> <Property Name="CloneMethod" Type="IMethodSymbol?"> <Comments> <summary>Clone method to be invoked on the value. This can be null in error scenarios.</summary> </Comments> </Property> <Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation"> <Comments> <summary>With collection initializer.</summary> </Comments> </Property> </Node> <Node Name="IInterpolatedStringHandlerCreationOperation" Base="IOperation" ChildrenOrder="HandlerCreation,Content" HasType="true"> <Comments> <summary>Represents an interpolated string converted to a custom interpolated string handler type.</summary> </Comments> <Property Name="HandlerCreation" Type="IOperation"> <Comments> <summary> The construction of the interpolated string handler instance. This can be an <see cref="IObjectCreationOperation"/> for valid code, and <see cref="IDynamicObjectCreationOperation"/> or <see cref="IInvalidOperation"/> for invalid code. </summary> </Comments> </Property> <Property Name="HandlerCreationHasSuccessParameter" Type="bool"> <Comments> <summary> True if the last parameter of <see cref="HandlerCreation"/> is an out <see langword="bool"/> parameter that will be checked before executing the code in <see cref="Content"/>. False otherwise. </summary> </Comments> </Property> <Property Name="HandlerAppendCallsReturnBool" Type="bool"> <Comments> <summary> True if the AppendLiteral or AppendFormatted calls in nested <see cref="IInterpolatedStringOperation.Parts"/> return <see langword="bool"/>. When that is true, each part will be conditional on the return of the part before it, only being executed when the Append call returns true. False otherwise. </summary> <remarks> when this is true and <see cref="HandlerCreationHasSuccessParameter"/> is true, then the first part in nested <see cref="IInterpolatedStringOperation.Parts"/> is conditionally run. If this is true and <see cref="HandlerCreationHasSuccessParameter"/> is false, then the first part is unconditionally run. <br/> Just because this is true or false does not guarantee that all Append calls actually do return boolean values, as there could be dynamic calls or errors. It only governs what the compiler was expecting, based on the first calls it did see. </remarks> </Comments> </Property> <Property Name="Content" Type="IOperation"> <Comments> <summary> The interpolated string expression or addition operation that makes up the content of this string. This is either an <see cref="IInterpolatedStringOperation"/> or an <see cref="IInterpolatedStringAdditionOperation"/> operation. </summary> </Comments> </Property> </Node> <Node Name="IInterpolatedStringAdditionOperation" Base="IOperation" ChildrenOrder="Left,Right"> <Comments> <summary> Represents an addition of multiple interpolated string literals being converted to an interpolated string handler type. </summary> </Comments> <Property Name="Left" Type="IOperation"> <Comments> <summary> The interpolated string expression or addition operation on the left side of the operator. This is either an <see cref="IInterpolatedStringOperation"/> or an <see cref="IInterpolatedStringAdditionOperation"/> operation. </summary> </Comments> </Property> <Property Name="Right" Type="IOperation"> <Comments> <summary> The interpolated string expression or addition operation on the right side of the operator. This is either an <see cref="IInterpolatedStringOperation"/> or an <see cref="IInterpolatedStringAdditionOperation"/> operation. </summary> </Comments> </Property> </Node> <Node Name="IInterpolatedStringAppendOperation" Base="IInterpolatedStringContentOperation"> <OperationKind> <Entry Name="InterpolatedStringAppendLiteral" Value="0x74" ExtraDescription="This append is of a literal component"/> <Entry Name="InterpolatedStringAppendFormatted" Value="0x75" ExtraDescription="This append is of an interpolation component"/> <Entry Name="InterpolatedStringAppendInvalid" Value="0x76" ExtraDescription="This append is invalid"/> </OperationKind> <Comments> <summary>Represents a call to either AppendLiteral or AppendFormatted as part of an interpolated string handler conversion.</summary> </Comments> <Property Name="AppendCall" Type="IOperation"> <Comments> <summary> If this interpolated string is subject to an interpolated string handler conversion, the construction of the interpolated string handler instance. This can be an <see cref="IInvocationOperation"/> or <see cref="IDynamicInvocationOperation"/> for valid code, and <see cref="IInvalidOperation"/> for invalid code. </summary> </Comments> </Property> </Node> <Node Name="IInterpolatedStringHandlerArgumentPlaceholderOperation" Base="IOperation"> <Comments> <summary>Represents an argument from the method call, indexer access, or constructor invocation that is creating the containing <see cref="IInterpolatedStringHandlerCreationOperation"/></summary> </Comments> <Property Name="ArgumentIndex" Type="int"> <Comments> <summary> The index of the argument of the method call, indexer, or object creation containing the interpolated string handler conversion this placeholder is referencing. -1 if <see cref="PlaceholderKind" /> is anything other than <see cref="InterpolatedStringArgumentPlaceholderKind.CallsiteArgument"/>. </summary> </Comments> </Property> <Property Name="PlaceholderKind" Type="InterpolatedStringArgumentPlaceholderKind"> <Comments> <summary> The component this placeholder represents. </summary> </Comments> </Property> </Node> </Tree>
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/Operations/OperationMapBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { internal static class OperationMapBuilder { /// <summary> /// Populates a empty dictionary of SyntaxNode->IOperation, where every key corresponds to an explicit IOperation node. /// If there is a SyntaxNode with more than one explicit IOperation, this will throw. /// </summary> internal static void AddToMap(IOperation root, Dictionary<SyntaxNode, IOperation> dictionary) { Debug.Assert(dictionary.Count == 0); Walker.Instance.Visit(root, dictionary); } private sealed class Walker : OperationWalker<Dictionary<SyntaxNode, IOperation>> { internal static readonly Walker Instance = new Walker(); public override object? DefaultVisit(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { RecordOperation(operation, argument); return base.DefaultVisit(operation, argument); } public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary<SyntaxNode, IOperation> argument) { // In order to handle very large nested operators, we implement manual iteration here. Our operations are not order sensitive, // so we don't need to maintain a stack, just iterate through every level. while (true) { RecordOperation(operation, argument); Visit(operation.RightOperand, argument); if (operation.LeftOperand is IBinaryOperation nested) { operation = nested; } else { Visit(operation.LeftOperand, argument); break; } } return null; } internal override object? VisitNoneOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { // OperationWalker skips these nodes by default, to avoid having public consumers deal with NoneOperation. // we need to deal with it here, however, so delegate to DefaultVisit. return DefaultVisit(operation, argument); } private static void RecordOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { if (!operation.IsImplicit) { // IOperation invariant is that all there is at most 1 non-implicit node per syntax node. argument.Add(operation.Syntax, operation); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { internal static class OperationMapBuilder { /// <summary> /// Populates a empty dictionary of SyntaxNode->IOperation, where every key corresponds to an explicit IOperation node. /// If there is a SyntaxNode with more than one explicit IOperation, this will throw. /// </summary> internal static void AddToMap(IOperation root, Dictionary<SyntaxNode, IOperation> dictionary) { Debug.Assert(dictionary.Count == 0); Walker.Instance.Visit(root, dictionary); } private sealed class Walker : OperationWalker<Dictionary<SyntaxNode, IOperation>> { internal static readonly Walker Instance = new Walker(); public override object? DefaultVisit(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { RecordOperation(operation, argument); return base.DefaultVisit(operation, argument); } public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary<SyntaxNode, IOperation> argument) { // In order to handle very large nested operators, we implement manual iteration here. Our operations are not order sensitive, // so we don't need to maintain a stack, just iterate through every level. while (true) { RecordOperation(operation, argument); Visit(operation.RightOperand, argument); if (operation.LeftOperand is IBinaryOperation nested) { operation = nested; } else { Visit(operation.LeftOperand, argument); break; } } return null; } internal override object? VisitNoneOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { // OperationWalker skips these nodes by default, to avoid having public consumers deal with NoneOperation. // we need to deal with it here, however, so delegate to DefaultVisit. return DefaultVisit(operation, argument); } private static void RecordOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { if (!operation.IsImplicit) { // IOperation invariant is that all there is at most 1 non-implicit node per syntax node. Debug.Assert(!argument.ContainsKey(operation.Syntax), $"Duplicate operation node for {operation.Syntax}. Existing node is {(argument.TryGetValue(operation.Syntax, out var original) ? original.Kind : null)}, new node is {operation.Kind}."); argument.Add(operation.Syntax, operation); } } } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/PublicAPI.Unshipped.txt
*REMOVED*Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode! other) -> bool abstract Microsoft.CodeAnalysis.SyntaxTree.GetLineMappings(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.LineMapping>! const Microsoft.CodeAnalysis.WellKnownMemberNames.PrintMembersMethodName = "PrintMembers" -> string! Microsoft.CodeAnalysis.Compilation.EmitDifference(Microsoft.CodeAnalysis.Emit.EmitBaseline! baseline, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Emit.SemanticEdit>! edits, System.Func<Microsoft.CodeAnalysis.ISymbol!, bool>! isAddedSymbol, System.IO.Stream! metadataStream, System.IO.Stream! ilStream, System.IO.Stream! pdbStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult! Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.ChangedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.MethodDefinitionHandle> Microsoft.CodeAnalysis.Emit.SemanticEditKind.Replace = 4 -> Microsoft.CodeAnalysis.Emit.SemanticEditKind Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]! Microsoft.CodeAnalysis.GeneratorDriver.ReplaceAdditionalText(Microsoft.CodeAnalysis.AdditionalText! oldText, Microsoft.CodeAnalysis.AdditionalText! newText) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedAnalyzerConfigOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedParseOptions(Microsoft.CodeAnalysis.ParseOptions! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriverOptions Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions() -> void Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions(Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind disabledOutputs) -> void Microsoft.CodeAnalysis.GeneratorExtensions Microsoft.CodeAnalysis.IFieldSymbol.FixedSize.get -> int Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver? Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext Microsoft.CodeAnalysis.GeneratorSyntaxContext.GeneratorSyntaxContext() -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext.Node.get -> Microsoft.CodeAnalysis.SyntaxNode! Microsoft.CodeAnalysis.GeneratorSyntaxContext.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel! Microsoft.CodeAnalysis.IIncrementalGenerator Microsoft.CodeAnalysis.IIncrementalGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void Microsoft.CodeAnalysis.IMethodSymbol.IsPartialDefinition.get -> bool Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AdditionalTextsProvider.get -> Microsoft.CodeAnalysis.IncrementalValuesProvider<Microsoft.CodeAnalysis.AdditionalText!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AnalyzerConfigOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.CompilationProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Compilation!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.IncrementalGeneratorInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.MetadataReferencesProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.MetadataReference!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.ParseOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.ParseOptions!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(System.Action<Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.SyntaxProvider.get -> Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Implementation = 4 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.None = 0 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.PostInit = 2 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Source = 1 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.IncrementalGeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalValueProvider<TValue> Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>.IncrementalValueProvider() -> void Microsoft.CodeAnalysis.IncrementalValueProviderExtensions Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues> Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>.IncrementalValuesProvider() -> void Microsoft.CodeAnalysis.ISymbol.MetadataToken.get -> int Microsoft.CodeAnalysis.ISyntaxContextReceiver Microsoft.CodeAnalysis.ISyntaxContextReceiver.OnVisitSyntaxNode(Microsoft.CodeAnalysis.GeneratorSyntaxContext context) -> void Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForPostInitialization(System.Action<Microsoft.CodeAnalysis.GeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.GeneratorPostInitializationContext.GeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IMethodSymbol.MethodImplementationFlags.get -> System.Reflection.MethodImplAttributes Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool Microsoft.CodeAnalysis.LineMapping Microsoft.CodeAnalysis.LineMapping.CharacterOffset.get -> int? Microsoft.CodeAnalysis.LineMapping.Equals(Microsoft.CodeAnalysis.LineMapping other) -> bool Microsoft.CodeAnalysis.LineMapping.IsHidden.get -> bool Microsoft.CodeAnalysis.LineMapping.LineMapping() -> void Microsoft.CodeAnalysis.LineMapping.LineMapping(Microsoft.CodeAnalysis.Text.LinePositionSpan span, int? characterOffset, Microsoft.CodeAnalysis.FileLinePositionSpan mappedSpan) -> void Microsoft.CodeAnalysis.LineMapping.MappedSpan.get -> Microsoft.CodeAnalysis.FileLinePositionSpan Microsoft.CodeAnalysis.LineMapping.Span.get -> Microsoft.CodeAnalysis.Text.LinePositionSpan Microsoft.CodeAnalysis.SymbolDisplayMiscellaneousOptions.CollapseTupleTypes = 512 -> Microsoft.CodeAnalysis.SymbolDisplayMiscellaneousOptions override Microsoft.CodeAnalysis.LineMapping.Equals(object? obj) -> bool override Microsoft.CodeAnalysis.LineMapping.GetHashCode() -> int override Microsoft.CodeAnalysis.LineMapping.ToString() -> string? Microsoft.CodeAnalysis.Operations.ISwitchExpressionOperation.IsExhaustive.get -> bool Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument> Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.OperationWalker() -> void Microsoft.CodeAnalysis.SourceProductionContext Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.SourceProductionContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.SourceProductionContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic! diagnostic) -> void Microsoft.CodeAnalysis.SourceProductionContext.SourceProductionContext() -> void Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordClassName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string! Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordStructName = 32 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind Microsoft.CodeAnalysis.SyntaxContextReceiverCreator Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNode.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNodeOrToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNodeOrToken other) -> bool Microsoft.CodeAnalysis.SyntaxToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxToken token) -> bool Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.SyntaxValueProvider.CreateSyntaxProvider<T>(System.Func<Microsoft.CodeAnalysis.SyntaxNode!, System.Threading.CancellationToken, bool>! predicate, System.Func<Microsoft.CodeAnalysis.GeneratorSyntaxContext, System.Threading.CancellationToken, T>! transform) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<T> Microsoft.CodeAnalysis.SyntaxValueProvider.SyntaxValueProvider() -> void override Microsoft.CodeAnalysis.Text.TextChangeRange.ToString() -> string! readonly Microsoft.CodeAnalysis.GeneratorDriverOptions.DisabledOutputs -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> int static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> bool override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVisit(Microsoft.CodeAnalysis.IOperation! operation, TArgument argument) -> object? override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object? static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator !=(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator ==(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator! static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type! static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Where<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, bool>! predicate) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> abstract Microsoft.CodeAnalysis.Compilation.GetUsedAssemblyReferences(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.MetadataReference!>
*REMOVED*Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode! other) -> bool abstract Microsoft.CodeAnalysis.SyntaxTree.GetLineMappings(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.LineMapping>! const Microsoft.CodeAnalysis.WellKnownMemberNames.PrintMembersMethodName = "PrintMembers" -> string! Microsoft.CodeAnalysis.Compilation.EmitDifference(Microsoft.CodeAnalysis.Emit.EmitBaseline! baseline, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Emit.SemanticEdit>! edits, System.Func<Microsoft.CodeAnalysis.ISymbol!, bool>! isAddedSymbol, System.IO.Stream! metadataStream, System.IO.Stream! ilStream, System.IO.Stream! pdbStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult! Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.ChangedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.MethodDefinitionHandle> Microsoft.CodeAnalysis.Emit.SemanticEditKind.Replace = 4 -> Microsoft.CodeAnalysis.Emit.SemanticEditKind Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]! Microsoft.CodeAnalysis.GeneratorDriver.ReplaceAdditionalText(Microsoft.CodeAnalysis.AdditionalText! oldText, Microsoft.CodeAnalysis.AdditionalText! newText) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedAnalyzerConfigOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedParseOptions(Microsoft.CodeAnalysis.ParseOptions! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriverOptions Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions() -> void Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions(Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind disabledOutputs) -> void Microsoft.CodeAnalysis.GeneratorExtensions Microsoft.CodeAnalysis.IFieldSymbol.FixedSize.get -> int Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver? Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext Microsoft.CodeAnalysis.GeneratorSyntaxContext.GeneratorSyntaxContext() -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext.Node.get -> Microsoft.CodeAnalysis.SyntaxNode! Microsoft.CodeAnalysis.GeneratorSyntaxContext.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel! Microsoft.CodeAnalysis.IIncrementalGenerator Microsoft.CodeAnalysis.IIncrementalGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void Microsoft.CodeAnalysis.IMethodSymbol.IsPartialDefinition.get -> bool Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AdditionalTextsProvider.get -> Microsoft.CodeAnalysis.IncrementalValuesProvider<Microsoft.CodeAnalysis.AdditionalText!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AnalyzerConfigOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.CompilationProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Compilation!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.IncrementalGeneratorInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.MetadataReferencesProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.MetadataReference!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.ParseOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.ParseOptions!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(System.Action<Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.SyntaxProvider.get -> Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Implementation = 4 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.None = 0 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.PostInit = 2 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Source = 1 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.IncrementalGeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalValueProvider<TValue> Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>.IncrementalValueProvider() -> void Microsoft.CodeAnalysis.IncrementalValueProviderExtensions Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues> Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>.IncrementalValuesProvider() -> void Microsoft.CodeAnalysis.ISymbol.MetadataToken.get -> int Microsoft.CodeAnalysis.ISyntaxContextReceiver Microsoft.CodeAnalysis.ISyntaxContextReceiver.OnVisitSyntaxNode(Microsoft.CodeAnalysis.GeneratorSyntaxContext context) -> void Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForPostInitialization(System.Action<Microsoft.CodeAnalysis.GeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.GeneratorPostInitializationContext.GeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IMethodSymbol.MethodImplementationFlags.get -> System.Reflection.MethodImplAttributes Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool Microsoft.CodeAnalysis.LineMapping Microsoft.CodeAnalysis.LineMapping.CharacterOffset.get -> int? Microsoft.CodeAnalysis.LineMapping.Equals(Microsoft.CodeAnalysis.LineMapping other) -> bool Microsoft.CodeAnalysis.LineMapping.IsHidden.get -> bool Microsoft.CodeAnalysis.LineMapping.LineMapping() -> void Microsoft.CodeAnalysis.LineMapping.LineMapping(Microsoft.CodeAnalysis.Text.LinePositionSpan span, int? characterOffset, Microsoft.CodeAnalysis.FileLinePositionSpan mappedSpan) -> void Microsoft.CodeAnalysis.LineMapping.MappedSpan.get -> Microsoft.CodeAnalysis.FileLinePositionSpan Microsoft.CodeAnalysis.LineMapping.Span.get -> Microsoft.CodeAnalysis.Text.LinePositionSpan Microsoft.CodeAnalysis.OperationKind.InterpolatedStringAddition = 115 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.OperationKind.InterpolatedStringAppendFormatted = 117 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.OperationKind.InterpolatedStringAppendInvalid = 118 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.OperationKind.InterpolatedStringAppendLiteral = 116 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.OperationKind.InterpolatedStringHandlerArgumentPlaceholder = 119 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.OperationKind.InterpolatedStringHandlerCreation = 114 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.Operations.IInterpolatedStringAdditionOperation Microsoft.CodeAnalysis.Operations.IInterpolatedStringAdditionOperation.Left.get -> Microsoft.CodeAnalysis.IOperation! Microsoft.CodeAnalysis.Operations.IInterpolatedStringAdditionOperation.Right.get -> Microsoft.CodeAnalysis.IOperation! Microsoft.CodeAnalysis.Operations.IInterpolatedStringAppendOperation Microsoft.CodeAnalysis.Operations.IInterpolatedStringAppendOperation.AppendCall.get -> Microsoft.CodeAnalysis.IOperation! Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerArgumentPlaceholderOperation Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerArgumentPlaceholderOperation.ArgumentIndex.get -> int Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerArgumentPlaceholderOperation.PlaceholderKind.get -> Microsoft.CodeAnalysis.Operations.InterpolatedStringArgumentPlaceholderKind Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerCreationOperation Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerCreationOperation.Content.get -> Microsoft.CodeAnalysis.IOperation! Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerCreationOperation.HandlerAppendCallsReturnBool.get -> bool Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerCreationOperation.HandlerCreation.get -> Microsoft.CodeAnalysis.IOperation! Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerCreationOperation.HandlerCreationHasSuccessParameter.get -> bool Microsoft.CodeAnalysis.Operations.InstanceReferenceKind.InterpolatedStringHandler = 3 -> Microsoft.CodeAnalysis.Operations.InstanceReferenceKind Microsoft.CodeAnalysis.Operations.InterpolatedStringArgumentPlaceholderKind Microsoft.CodeAnalysis.Operations.InterpolatedStringArgumentPlaceholderKind.CallsiteArgument = 0 -> Microsoft.CodeAnalysis.Operations.InterpolatedStringArgumentPlaceholderKind Microsoft.CodeAnalysis.Operations.InterpolatedStringArgumentPlaceholderKind.CallsiteReceiver = 1 -> Microsoft.CodeAnalysis.Operations.InterpolatedStringArgumentPlaceholderKind Microsoft.CodeAnalysis.Operations.InterpolatedStringArgumentPlaceholderKind.TrailingValidityArgument = 2 -> Microsoft.CodeAnalysis.Operations.InterpolatedStringArgumentPlaceholderKind Microsoft.CodeAnalysis.SymbolDisplayMiscellaneousOptions.CollapseTupleTypes = 512 -> Microsoft.CodeAnalysis.SymbolDisplayMiscellaneousOptions override Microsoft.CodeAnalysis.LineMapping.Equals(object? obj) -> bool override Microsoft.CodeAnalysis.LineMapping.GetHashCode() -> int override Microsoft.CodeAnalysis.LineMapping.ToString() -> string? Microsoft.CodeAnalysis.Operations.ISwitchExpressionOperation.IsExhaustive.get -> bool Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument> Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.OperationWalker() -> void Microsoft.CodeAnalysis.SourceProductionContext Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.SourceProductionContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.SourceProductionContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic! diagnostic) -> void Microsoft.CodeAnalysis.SourceProductionContext.SourceProductionContext() -> void Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordClassName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string! Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordStructName = 32 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind Microsoft.CodeAnalysis.SyntaxContextReceiverCreator Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNode.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNodeOrToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNodeOrToken other) -> bool Microsoft.CodeAnalysis.SyntaxToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxToken token) -> bool Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.SyntaxValueProvider.CreateSyntaxProvider<T>(System.Func<Microsoft.CodeAnalysis.SyntaxNode!, System.Threading.CancellationToken, bool>! predicate, System.Func<Microsoft.CodeAnalysis.GeneratorSyntaxContext, System.Threading.CancellationToken, T>! transform) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<T> Microsoft.CodeAnalysis.SyntaxValueProvider.SyntaxValueProvider() -> void override Microsoft.CodeAnalysis.Text.TextChangeRange.ToString() -> string! readonly Microsoft.CodeAnalysis.GeneratorDriverOptions.DisabledOutputs -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> int static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> bool override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVisit(Microsoft.CodeAnalysis.IOperation! operation, TArgument argument) -> object? override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object? static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator !=(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator ==(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator! static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type! static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Where<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, bool>! predicate) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> abstract Microsoft.CodeAnalysis.Compilation.GetUsedAssemblyReferences(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.MetadataReference!> virtual Microsoft.CodeAnalysis.Operations.OperationVisitor.VisitInterpolatedStringAddition(Microsoft.CodeAnalysis.Operations.IInterpolatedStringAdditionOperation! operation) -> void virtual Microsoft.CodeAnalysis.Operations.OperationVisitor.VisitInterpolatedStringAppend(Microsoft.CodeAnalysis.Operations.IInterpolatedStringAppendOperation! operation) -> void virtual Microsoft.CodeAnalysis.Operations.OperationVisitor.VisitInterpolatedStringHandlerArgumentPlaceholder(Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerArgumentPlaceholderOperation! operation) -> void virtual Microsoft.CodeAnalysis.Operations.OperationVisitor.VisitInterpolatedStringHandlerCreation(Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerCreationOperation! operation) -> void virtual Microsoft.CodeAnalysis.Operations.OperationVisitor<TArgument, TResult>.VisitInterpolatedStringAddition(Microsoft.CodeAnalysis.Operations.IInterpolatedStringAdditionOperation! operation, TArgument argument) -> TResult? virtual Microsoft.CodeAnalysis.Operations.OperationVisitor<TArgument, TResult>.VisitInterpolatedStringAppend(Microsoft.CodeAnalysis.Operations.IInterpolatedStringAppendOperation! operation, TArgument argument) -> TResult? virtual Microsoft.CodeAnalysis.Operations.OperationVisitor<TArgument, TResult>.VisitInterpolatedStringHandlerArgumentPlaceholder(Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerArgumentPlaceholderOperation! operation, TArgument argument) -> TResult? virtual Microsoft.CodeAnalysis.Operations.OperationVisitor<TArgument, TResult>.VisitInterpolatedStringHandlerCreation(Microsoft.CodeAnalysis.Operations.IInterpolatedStringHandlerCreationOperation! operation, TArgument argument) -> TResult?
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Test/Core/Compilation/ControlFlowGraphVerifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.VisualBasic.Syntax; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class ControlFlowGraphVerifier { public static (ControlFlowGraph graph, ISymbol associatedSymbol) GetControlFlowGraph(SyntaxNode syntaxNode, SemanticModel model) { IOperation operationRoot = model.GetOperation(syntaxNode); // Workaround for unit tests designed to work on IBlockOperation with ConstructorBodyOperation/MethodBodyOperation parent. operationRoot = operationRoot.Kind == OperationKind.Block && (operationRoot.Parent?.Kind == OperationKind.ConstructorBody || operationRoot.Parent?.Kind == OperationKind.MethodBody) ? operationRoot.Parent : operationRoot; TestOperationVisitor.VerifySubTree(operationRoot); ControlFlowGraph graph; switch (operationRoot) { case IBlockOperation blockOperation: graph = ControlFlowGraph.Create(blockOperation); break; case IMethodBodyOperation methodBodyOperation: graph = ControlFlowGraph.Create(methodBodyOperation); break; case IConstructorBodyOperation constructorBodyOperation: graph = ControlFlowGraph.Create(constructorBodyOperation); break; case IFieldInitializerOperation fieldInitializerOperation: graph = ControlFlowGraph.Create(fieldInitializerOperation); break; case IPropertyInitializerOperation propertyInitializerOperation: graph = ControlFlowGraph.Create(propertyInitializerOperation); break; case IParameterInitializerOperation parameterInitializerOperation: graph = ControlFlowGraph.Create(parameterInitializerOperation); break; default: return default; } Assert.NotNull(graph); Assert.Same(operationRoot, graph.OriginalOperation); var declaredSymbol = model.GetDeclaredSymbol(operationRoot.Syntax); return (graph, declaredSymbol); } public static void VerifyGraph(Compilation compilation, string expectedFlowGraph, ControlFlowGraph graph, ISymbol associatedSymbol) { var actualFlowGraph = GetFlowGraph(compilation, graph, associatedSymbol); OperationTreeVerifier.Verify(expectedFlowGraph, actualFlowGraph); // Basic block reachability analysis verification using a test-only dataflow analyzer // that uses the dataflow analysis engine linked from the Workspaces layer. // This provides test coverage for Workspace layer dataflow analysis engine // for all ControlFlowGraphs created in compiler layer's flow analysis unit tests. var reachabilityVector = BasicBlockReachabilityDataFlowAnalyzer.Run(graph); for (int i = 0; i < graph.Blocks.Length; i++) { Assert.Equal(graph.Blocks[i].IsReachable, reachabilityVector[i]); } } public static string GetFlowGraph(Compilation compilation, ControlFlowGraph graph, ISymbol associatedSymbol) { var pooledBuilder = PooledObjects.PooledStringBuilder.GetInstance(); var stringBuilder = pooledBuilder.Builder; GetFlowGraph(pooledBuilder.Builder, compilation, graph, enclosing: null, idSuffix: "", indent: 0, associatedSymbol); return pooledBuilder.ToStringAndFree(); } private static void GetFlowGraph(System.Text.StringBuilder stringBuilder, Compilation compilation, ControlFlowGraph graph, ControlFlowRegion enclosing, string idSuffix, int indent, ISymbol associatedSymbol) { ImmutableArray<BasicBlock> blocks = graph.Blocks; var visitor = TestOperationVisitor.Singleton; ControlFlowRegion currentRegion = graph.Root; bool lastPrintedBlockIsInCurrentRegion = true; PooledDictionary<ControlFlowRegion, int> regionMap = buildRegionMap(); var localFunctionsMap = PooledDictionary<IMethodSymbol, ControlFlowGraph>.GetInstance(); var anonymousFunctionsMap = PooledDictionary<IFlowAnonymousFunctionOperation, ControlFlowGraph>.GetInstance(); var referencedLocalsAndMethods = PooledHashSet<ISymbol>.GetInstance(); var referencedCaptureIds = PooledHashSet<CaptureId>.GetInstance(); for (int i = 0; i < blocks.Length; i++) { var block = blocks[i]; Assert.Equal(i, block.Ordinal); switch (block.Kind) { case BasicBlockKind.Block: Assert.NotEqual(0, i); Assert.NotEqual(blocks.Length - 1, i); break; case BasicBlockKind.Entry: Assert.Equal(0, i); Assert.Empty(block.Operations); Assert.Empty(block.Predecessors); Assert.Null(block.BranchValue); Assert.NotNull(block.FallThroughSuccessor); Assert.NotNull(block.FallThroughSuccessor.Destination); Assert.Null(block.ConditionalSuccessor); Assert.Same(graph.Root, currentRegion); Assert.Same(currentRegion, block.EnclosingRegion); Assert.Equal(0, currentRegion.FirstBlockOrdinal); Assert.Same(enclosing, currentRegion.EnclosingRegion); Assert.Null(currentRegion.ExceptionType); Assert.Empty(currentRegion.Locals); Assert.Empty(currentRegion.LocalFunctions); Assert.Empty(currentRegion.CaptureIds); Assert.Equal(ControlFlowRegionKind.Root, currentRegion.Kind); Assert.True(block.IsReachable); break; case BasicBlockKind.Exit: Assert.Equal(blocks.Length - 1, i); Assert.Empty(block.Operations); Assert.Null(block.FallThroughSuccessor); Assert.Null(block.ConditionalSuccessor); Assert.Null(block.BranchValue); Assert.Same(graph.Root, currentRegion); Assert.Same(currentRegion, block.EnclosingRegion); Assert.Equal(i, currentRegion.LastBlockOrdinal); break; default: Assert.False(true, $"Unexpected block kind {block.Kind}"); break; } if (block.EnclosingRegion != currentRegion) { enterRegions(block.EnclosingRegion, block.Ordinal); } if (!lastPrintedBlockIsInCurrentRegion) { stringBuilder.AppendLine(); } appendLine($"Block[{getBlockId(block)}] - {block.Kind}{(block.IsReachable ? "" : " [UnReachable]")}"); var predecessors = block.Predecessors; if (!predecessors.IsEmpty) { appendIndent(); stringBuilder.Append(" Predecessors:"); int previousPredecessorOrdinal = -1; for (var predecessorIndex = 0; predecessorIndex < predecessors.Length; predecessorIndex++) { var predecessorBranch = predecessors[predecessorIndex]; Assert.Same(block, predecessorBranch.Destination); var predecessor = predecessorBranch.Source; Assert.True(previousPredecessorOrdinal < predecessor.Ordinal); previousPredecessorOrdinal = predecessor.Ordinal; Assert.Same(blocks[predecessor.Ordinal], predecessor); if (predecessorBranch.IsConditionalSuccessor) { Assert.Same(predecessor.ConditionalSuccessor, predecessorBranch); Assert.NotEqual(ControlFlowConditionKind.None, predecessor.ConditionKind); } else { Assert.Same(predecessor.FallThroughSuccessor, predecessorBranch); } stringBuilder.Append($" [{getBlockId(predecessor)}"); if (predecessorIndex < predecessors.Length - 1 && predecessors[predecessorIndex + 1].Source == predecessor) { // Multiple branches from same predecessor - one must be conditional and other fall through. Assert.True(predecessorBranch.IsConditionalSuccessor); predecessorIndex++; predecessorBranch = predecessors[predecessorIndex]; Assert.Same(predecessor.FallThroughSuccessor, predecessorBranch); Assert.False(predecessorBranch.IsConditionalSuccessor); stringBuilder.Append("*2"); } stringBuilder.Append("]"); } stringBuilder.AppendLine(); } else if (block.Kind != BasicBlockKind.Entry) { appendLine(" Predecessors (0)"); } var statements = block.Operations; appendLine($" Statements ({statements.Length})"); foreach (var statement in statements) { validateRoot(statement); stringBuilder.AppendLine(getOperationTree(statement)); } ControlFlowBranch conditionalBranch = block.ConditionalSuccessor; if (block.ConditionKind != ControlFlowConditionKind.None) { Assert.NotNull(conditionalBranch); Assert.True(conditionalBranch.IsConditionalSuccessor); Assert.Same(block, conditionalBranch.Source); if (conditionalBranch.Destination != null) { Assert.Same(blocks[conditionalBranch.Destination.Ordinal], conditionalBranch.Destination); } Assert.NotEqual(ControlFlowBranchSemantics.Return, conditionalBranch.Semantics); Assert.NotEqual(ControlFlowBranchSemantics.Throw, conditionalBranch.Semantics); Assert.NotEqual(ControlFlowBranchSemantics.StructuredExceptionHandling, conditionalBranch.Semantics); Assert.True(block.ConditionKind == ControlFlowConditionKind.WhenTrue || block.ConditionKind == ControlFlowConditionKind.WhenFalse); string jumpIfTrue = block.ConditionKind == ControlFlowConditionKind.WhenTrue ? "True" : "False"; appendLine($" Jump if {jumpIfTrue} ({conditionalBranch.Semantics}) to Block[{getDestinationString(ref conditionalBranch)}]"); IOperation value = block.BranchValue; Assert.NotNull(value); validateRoot(value); stringBuilder.Append(getOperationTree(value)); validateBranch(block, conditionalBranch); stringBuilder.AppendLine(); } else { Assert.Null(conditionalBranch); Assert.Equal(ControlFlowConditionKind.None, block.ConditionKind); } ControlFlowBranch nextBranch = block.FallThroughSuccessor; if (block.Kind == BasicBlockKind.Exit) { Assert.Null(nextBranch); Assert.Null(block.BranchValue); } else { Assert.NotNull(nextBranch); Assert.False(nextBranch.IsConditionalSuccessor); Assert.Same(block, nextBranch.Source); if (nextBranch.Destination != null) { Assert.Same(blocks[nextBranch.Destination.Ordinal], nextBranch.Destination); } if (nextBranch.Semantics == ControlFlowBranchSemantics.StructuredExceptionHandling) { Assert.Null(nextBranch.Destination); Assert.Equal(block.EnclosingRegion.LastBlockOrdinal, block.Ordinal); Assert.True(block.EnclosingRegion.Kind == ControlFlowRegionKind.Filter || block.EnclosingRegion.Kind == ControlFlowRegionKind.Finally); } appendLine($" Next ({nextBranch.Semantics}) Block[{getDestinationString(ref nextBranch)}]"); IOperation value = block.ConditionKind == ControlFlowConditionKind.None ? block.BranchValue : null; if (value != null) { Assert.True(ControlFlowBranchSemantics.Return == nextBranch.Semantics || ControlFlowBranchSemantics.Throw == nextBranch.Semantics); validateRoot(value); stringBuilder.Append(getOperationTree(value)); } else { Assert.NotEqual(ControlFlowBranchSemantics.Return, nextBranch.Semantics); Assert.NotEqual(ControlFlowBranchSemantics.Throw, nextBranch.Semantics); } validateBranch(block, nextBranch); } if (currentRegion.LastBlockOrdinal == block.Ordinal && i != blocks.Length - 1) { leaveRegions(block.EnclosingRegion, block.Ordinal); } else { lastPrintedBlockIsInCurrentRegion = true; } } foreach (IMethodSymbol m in graph.LocalFunctions) { ControlFlowGraph g = localFunctionsMap[m]; Assert.Same(g, graph.GetLocalFunctionControlFlowGraph(m)); Assert.Same(g, graph.GetLocalFunctionControlFlowGraphInScope(m)); Assert.Same(graph, g.Parent); } Assert.Equal(graph.LocalFunctions.Length, localFunctionsMap.Count); foreach (KeyValuePair<IFlowAnonymousFunctionOperation, ControlFlowGraph> pair in anonymousFunctionsMap) { Assert.Same(pair.Value, graph.GetAnonymousFunctionControlFlowGraph(pair.Key)); Assert.Same(pair.Value, graph.GetAnonymousFunctionControlFlowGraphInScope(pair.Key)); Assert.Same(graph, pair.Value.Parent); } bool doCaptureVerification = true; if (graph.OriginalOperation.Language == LanguageNames.VisualBasic) { var model = compilation.GetSemanticModel(graph.OriginalOperation.Syntax.SyntaxTree); if (model.GetDiagnostics(graph.OriginalOperation.Syntax.Span). Any(d => d.Code == (int)VisualBasic.ERRID.ERR_GotoIntoWith || d.Code == (int)VisualBasic.ERRID.ERR_GotoIntoFor || d.Code == (int)VisualBasic.ERRID.ERR_GotoIntoSyncLock || d.Code == (int)VisualBasic.ERRID.ERR_GotoIntoUsing)) { // Invalid branches like that are often causing reports about // using captures before they are initialized. doCaptureVerification = false; } } Func<string> finalGraph = () => stringBuilder.ToString(); if (doCaptureVerification) { verifyCaptures(finalGraph); } foreach (var block in blocks) { validateLifetimeOfReferences(block, finalGraph); } regionMap.Free(); localFunctionsMap.Free(); anonymousFunctionsMap.Free(); referencedLocalsAndMethods.Free(); referencedCaptureIds.Free(); return; void verifyCaptures(Func<string> finalGraph) { var longLivedIds = PooledHashSet<CaptureId>.GetInstance(); var referencedIds = PooledHashSet<CaptureId>.GetInstance(); var entryStates = ArrayBuilder<PooledHashSet<CaptureId>>.GetInstance(blocks.Length, fillWithValue: null); var regions = ArrayBuilder<ControlFlowRegion>.GetInstance(); for (int i = 1; i < blocks.Length - 1; i++) { BasicBlock block = blocks[i]; PooledHashSet<CaptureId> currentState = entryStates[i] ?? PooledHashSet<CaptureId>.GetInstance(); entryStates[i] = null; foreach (ControlFlowBranch predecessor in block.Predecessors) { if (predecessor.Source.Ordinal >= i) { foreach (ControlFlowRegion region in predecessor.EnteringRegions) { if (region.FirstBlockOrdinal != block.Ordinal) { foreach (CaptureId id in region.CaptureIds) { AssertTrueWithGraph(currentState.Contains(id), $"Backward branch from [{getBlockId(predecessor.Source)}] to [{getBlockId(block)}] before capture [{id.Value}] is initialized.", finalGraph); } } } } } for (var j = 0; j < block.Operations.Length; j++) { var operation = block.Operations[j]; if (operation is IFlowCaptureOperation capture) { assertCaptureReferences(currentState, capture.Value, block, j, longLivedIds, referencedIds, finalGraph); AssertTrueWithGraph(currentState.Add(capture.Id), $"Operation [{j}] in [{getBlockId(block)}] re-initialized capture [{capture.Id.Value}]", finalGraph); } else { assertCaptureReferences(currentState, operation, block, j, longLivedIds, referencedIds, finalGraph); } } if (block.BranchValue != null) { assertCaptureReferences(currentState, block.BranchValue, block, block.Operations.Length, longLivedIds, referencedIds, finalGraph); if (block.ConditionalSuccessor != null) { adjustEntryStateForDestination(entryStates, block.ConditionalSuccessor, currentState); } } adjustEntryStateForDestination(entryStates, block.FallThroughSuccessor, currentState); if (blocks[i + 1].Predecessors.IsEmpty) { adjustAndGetEntryState(entryStates, blocks[i + 1], currentState); } verifyLeftRegions(block, longLivedIds, referencedIds, regions, finalGraph); currentState.Free(); } foreach (PooledHashSet<CaptureId> state in entryStates) { state?.Free(); } entryStates.Free(); longLivedIds.Free(); referencedIds.Free(); regions.Free(); } void verifyLeftRegions(BasicBlock block, PooledHashSet<CaptureId> longLivedIds, PooledHashSet<CaptureId> referencedIds, ArrayBuilder<ControlFlowRegion> regions, Func<string> finalGraph) { regions.Clear(); { ControlFlowRegion region = block.EnclosingRegion; while (region.LastBlockOrdinal == block.Ordinal) { regions.Add(region); region = region.EnclosingRegion; } } if (block.ConditionalSuccessor != null && block.ConditionalSuccessor.LeavingRegions.Length > regions.Count) { regions.Clear(); regions.AddRange(block.ConditionalSuccessor.LeavingRegions); } if (block.FallThroughSuccessor.LeavingRegions.Length > regions.Count) { regions.Clear(); regions.AddRange(block.FallThroughSuccessor.LeavingRegions); } if (regions.Count > 0) { IOperation lastOperation = null; for (int i = block.Ordinal; i > 0 && lastOperation == null; i--) { lastOperation = blocks[i].BranchValue ?? blocks[i].Operations.LastOrDefault(); } var referencedInLastOperation = PooledHashSet<CaptureId>.GetInstance(); if (lastOperation != null) { foreach (IFlowCaptureReferenceOperation reference in lastOperation.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { referencedInLastOperation.Add(reference.Id); } } foreach (ControlFlowRegion region in regions) { foreach (CaptureId id in region.CaptureIds) { if (referencedInLastOperation.Contains(id) || longLivedIds.Contains(id) || isCSharpEmptyObjectInitializerCapture(region, block, id) || isWithStatementTargetCapture(region, block, id) || isSwitchTargetCapture(region, block, id) || isForEachEnumeratorCapture(region, block, id) || isConditionalXMLAccessReceiverCapture(region, block, id) || isConditionalAccessCaptureUsedAfterNullCheck(lastOperation, region, block, id) || (referencedIds.Contains(id) && isAggregateGroupCapture(lastOperation, region, block, id))) { continue; } if (region.LastBlockOrdinal != block.Ordinal && referencedIds.Contains(id)) { continue; } IFlowCaptureReferenceOperation[] referencesAfter = getFlowCaptureReferenceOperationsInRegion(region, block.Ordinal + 1).Where(r => r.Id.Equals(id)).ToArray(); AssertTrueWithGraph(referencesAfter.Length > 0 && referencesAfter.All(r => isLongLivedCaptureReferenceSyntax(r.Syntax)), $"Capture [{id.Value}] is not used in region [{getRegionId(region)}] before leaving it after block [{getBlockId(block)}]", finalGraph); } } referencedInLastOperation.Free(); } } bool isCSharpEmptyObjectInitializerCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { if (graph.OriginalOperation.Language != LanguageNames.CSharp) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)candidate.Syntax); CSharpSyntaxNode parent = syntax; do { parent = parent.Parent; } while (parent != null && parent.Kind() != CSharp.SyntaxKind.SimpleAssignmentExpression); if (parent is AssignmentExpressionSyntax assignment && assignment.Parent?.Kind() == CSharp.SyntaxKind.ObjectInitializerExpression && assignment.Left.DescendantNodesAndSelf().Contains(syntax) && assignment.Right is InitializerExpressionSyntax initializer && initializer.Kind() == CSharp.SyntaxKind.ObjectInitializerExpression && !initializer.Expressions.Any()) { return true; } break; } } return false; } bool isWithStatementTargetCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { if (graph.OriginalOperation.Language != LanguageNames.VisualBasic) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); VisualBasicSyntaxNode parent = syntax.Parent; if (parent is WithStatementSyntax with && with.Expression == syntax) { return true; } break; } } return false; } bool isConditionalXMLAccessReceiverCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { if (graph.OriginalOperation.Language != LanguageNames.VisualBasic) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); VisualBasicSyntaxNode parent = syntax.Parent; if (parent is VisualBasic.Syntax.ConditionalAccessExpressionSyntax conditional && conditional.Expression == syntax && conditional.WhenNotNull.DescendantNodesAndSelf(). Any(n => n.IsKind(VisualBasic.SyntaxKind.XmlElementAccessExpression) || n.IsKind(VisualBasic.SyntaxKind.XmlDescendantAccessExpression) || n.IsKind(VisualBasic.SyntaxKind.XmlAttributeAccessExpression))) { // https://github.com/dotnet/roslyn/issues/27564: It looks like there is a bug in IOperation tree around XmlMemberAccessExpressionSyntax, // a None operation is created and all children are dropped. return true; } break; } } return false; } bool isEmptySwitchExpressionResult(IFlowCaptureReferenceOperation reference) { return reference.Syntax is CSharp.Syntax.SwitchExpressionSyntax switchExpr && switchExpr.Arms.Count == 0; } bool isSwitchTargetCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { switch (candidate.Language) { case LanguageNames.CSharp: { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)candidate.Syntax); if (syntax.Parent is CSharp.Syntax.SwitchStatementSyntax switchStmt && switchStmt.Expression == syntax) { return true; } if (syntax.Parent is CSharp.Syntax.SwitchExpressionSyntax switchExpr && switchExpr.GoverningExpression == syntax) { return true; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); if (syntax.Parent is VisualBasic.Syntax.SelectStatementSyntax switchStmt && switchStmt.Expression == syntax) { return true; } } break; } break; } } return false; } bool isForEachEnumeratorCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { switch (candidate.Language) { case LanguageNames.CSharp: { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)candidate.Syntax); if (syntax.Parent is CSharp.Syntax.CommonForEachStatementSyntax forEach && forEach.Expression == syntax) { return true; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); if (syntax.Parent is VisualBasic.Syntax.ForEachStatementSyntax forEach && forEach.Expression == syntax) { return true; } } break; } break; } } return false; } bool isAggregateGroupCapture(IOperation operation, ControlFlowRegion region, BasicBlock block, CaptureId id) { if (graph.OriginalOperation.Language != LanguageNames.VisualBasic) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); foreach (ITranslatedQueryOperation query in operation.DescendantsAndSelf().OfType<ITranslatedQueryOperation>()) { if (query.Syntax is VisualBasic.Syntax.QueryExpressionSyntax querySyntax && querySyntax.Clauses.AsSingleton() is VisualBasic.Syntax.AggregateClauseSyntax aggregate && aggregate.AggregateKeyword.SpanStart < candidate.Syntax.SpanStart && aggregate.IntoKeyword.SpanStart > candidate.Syntax.SpanStart && query.Operation.Kind == OperationKind.AnonymousObjectCreation) { return true; } } break; } } return false; } void adjustEntryStateForDestination(ArrayBuilder<PooledHashSet<CaptureId>> entryStates, ControlFlowBranch branch, PooledHashSet<CaptureId> state) { if (branch.Destination != null) { if (branch.Destination.Ordinal > branch.Source.Ordinal) { PooledHashSet<CaptureId> entryState = adjustAndGetEntryState(entryStates, branch.Destination, state); foreach (ControlFlowRegion region in branch.LeavingRegions) { entryState.RemoveAll(region.CaptureIds); } } } else if (branch.Semantics == ControlFlowBranchSemantics.Throw || branch.Semantics == ControlFlowBranchSemantics.Rethrow || branch.Semantics == ControlFlowBranchSemantics.Error || branch.Semantics == ControlFlowBranchSemantics.StructuredExceptionHandling) { ControlFlowRegion region = branch.Source.EnclosingRegion; while (region.Kind != ControlFlowRegionKind.Root) { if (region.Kind == ControlFlowRegionKind.Try && region.EnclosingRegion.Kind == ControlFlowRegionKind.TryAndFinally) { Debug.Assert(region.EnclosingRegion.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); adjustAndGetEntryState(entryStates, blocks[region.EnclosingRegion.NestedRegions[1].FirstBlockOrdinal], state); } region = region.EnclosingRegion; } } foreach (ControlFlowRegion @finally in branch.FinallyRegions) { adjustAndGetEntryState(entryStates, blocks[@finally.FirstBlockOrdinal], state); } } PooledHashSet<CaptureId> adjustAndGetEntryState(ArrayBuilder<PooledHashSet<CaptureId>> entryStates, BasicBlock block, PooledHashSet<CaptureId> state) { PooledHashSet<CaptureId> entryState = entryStates[block.Ordinal]; if (entryState == null) { entryState = PooledHashSet<CaptureId>.GetInstance(); entryState.AddAll(state); entryStates[block.Ordinal] = entryState; } else { entryState.RemoveWhere(id => !state.Contains(id)); } return entryState; } void assertCaptureReferences( PooledHashSet<CaptureId> state, IOperation operation, BasicBlock block, int operationIndex, PooledHashSet<CaptureId> longLivedIds, PooledHashSet<CaptureId> referencedIds, Func<string> finalGraph) { foreach (IFlowCaptureReferenceOperation reference in operation.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { CaptureId id = reference.Id; referencedIds.Add(id); if (isLongLivedCaptureReference(reference, block.EnclosingRegion)) { longLivedIds.Add(id); } AssertTrueWithGraph(state.Contains(id) || isCaptureFromEnclosingGraph(id) || isEmptySwitchExpressionResult(reference), $"Operation [{operationIndex}] in [{getBlockId(block)}] uses not initialized capture [{id.Value}].", finalGraph); // Except for a few specific scenarios, any references to captures should either be long-lived capture references, // or they should come from the enclosing region. AssertTrueWithGraph(block.EnclosingRegion.CaptureIds.Contains(id) || longLivedIds.Contains(id) || ((isFirstOperandOfDynamicOrUserDefinedLogicalOperator(reference) || isIncrementedNullableForToLoopControlVariable(reference) || isConditionalAccessReceiver(reference) || isCoalesceAssignmentTarget(reference) || isObjectInitializerInitializedObjectTarget(reference)) && block.EnclosingRegion.EnclosingRegion.CaptureIds.Contains(id)), $"Operation [{operationIndex}] in [{getBlockId(block)}] uses capture [{id.Value}] from another region. Should the regions be merged?", finalGraph); } } bool isConditionalAccessReceiver(IFlowCaptureReferenceOperation reference) { SyntaxNode captureReferenceSyntax = reference.Syntax; switch (captureReferenceSyntax.Language) { case LanguageNames.CSharp: { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)captureReferenceSyntax); if (syntax.Parent is CSharp.Syntax.ConditionalAccessExpressionSyntax access && access.Expression == syntax) { return true; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)captureReferenceSyntax); if (syntax.Parent is VisualBasic.Syntax.ConditionalAccessExpressionSyntax access && access.Expression == syntax) { return true; } } break; } return false; } bool isCoalesceAssignmentTarget(IFlowCaptureReferenceOperation reference) { if (reference.Language != LanguageNames.CSharp) { return false; } CSharpSyntaxNode referenceSyntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)reference.Syntax); return referenceSyntax.Parent is AssignmentExpressionSyntax conditionalAccess && conditionalAccess.IsKind(CSharp.SyntaxKind.CoalesceAssignmentExpression) && conditionalAccess.Left == referenceSyntax; } bool isObjectInitializerInitializedObjectTarget(IFlowCaptureReferenceOperation reference) { if (reference.Language != LanguageNames.CSharp) { return false; } CSharpSyntaxNode referenceSyntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)reference.Syntax); return referenceSyntax.Parent is CSharp.Syntax.AssignmentExpressionSyntax { RawKind: (int)CSharp.SyntaxKind.SimpleAssignmentExpression, Parent: InitializerExpressionSyntax { Parent: CSharp.Syntax.ObjectCreationExpressionSyntax }, Left: var left } && left == referenceSyntax; } bool isFirstOperandOfDynamicOrUserDefinedLogicalOperator(IFlowCaptureReferenceOperation reference) { if (reference.Parent is IBinaryOperation binOp) { if (binOp.LeftOperand == reference && (binOp.OperatorKind == Operations.BinaryOperatorKind.And || binOp.OperatorKind == Operations.BinaryOperatorKind.Or) && (binOp.OperatorMethod != null || (ITypeSymbolHelpers.IsDynamicType(binOp.Type) && (ITypeSymbolHelpers.IsDynamicType(binOp.LeftOperand.Type) || ITypeSymbolHelpers.IsDynamicType(binOp.RightOperand.Type))))) { if (reference.Language == LanguageNames.CSharp) { if (binOp.Syntax is CSharp.Syntax.BinaryExpressionSyntax binOpSyntax && (binOpSyntax.Kind() == CSharp.SyntaxKind.LogicalAndExpression || binOpSyntax.Kind() == CSharp.SyntaxKind.LogicalOrExpression) && binOpSyntax.Left == applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)reference.Syntax) && binOpSyntax.Right == applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)binOp.RightOperand.Syntax)) { return true; } } else if (reference.Language == LanguageNames.VisualBasic) { var referenceSyntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)reference.Syntax); if (binOp.Syntax is VisualBasic.Syntax.BinaryExpressionSyntax binOpSyntax && (binOpSyntax.Kind() == VisualBasic.SyntaxKind.AndAlsoExpression || binOpSyntax.Kind() == VisualBasic.SyntaxKind.OrElseExpression) && binOpSyntax.Left == referenceSyntax && binOpSyntax.Right == applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)binOp.RightOperand.Syntax)) { return true; } else if (binOp.Syntax is VisualBasic.Syntax.RangeCaseClauseSyntax range && binOp.OperatorKind == Operations.BinaryOperatorKind.And && range.LowerBound == referenceSyntax && range.UpperBound == applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)binOp.RightOperand.Syntax)) { return true; } else if (binOp.Syntax is VisualBasic.Syntax.CaseStatementSyntax caseStmt && binOp.OperatorKind == Operations.BinaryOperatorKind.Or && caseStmt.Cases.Count > 1 && (caseStmt == referenceSyntax || caseStmt.Cases.Contains(referenceSyntax as CaseClauseSyntax)) && caseStmt.Cases.Contains(applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)binOp.RightOperand.Syntax) as CaseClauseSyntax)) { return true; } } } } return false; } bool isIncrementedNullableForToLoopControlVariable(IFlowCaptureReferenceOperation reference) { if (reference.Parent is ISimpleAssignmentOperation assignment && assignment.IsImplicit && assignment.Target == reference && ITypeSymbolHelpers.IsNullableType(reference.Type) && assignment.Syntax.Parent is VisualBasic.Syntax.ForStatementSyntax forStmt && assignment.Syntax == forStmt.ControlVariable && reference.Syntax == assignment.Syntax && assignment.Value.Syntax == forStmt.StepClause.StepValue) { return true; } return false; } bool isLongLivedCaptureReference(IFlowCaptureReferenceOperation reference, ControlFlowRegion region) { if (isLongLivedCaptureReferenceSyntax(reference.Syntax)) { return true; } return isCaptureFromEnclosingGraph(reference.Id); } bool isCaptureFromEnclosingGraph(CaptureId id) { ControlFlowRegion region = graph.Root.EnclosingRegion; while (region != null) { if (region.CaptureIds.Contains(id)) { return true; } region = region.EnclosingRegion; } return false; } bool isConditionalAccessCaptureUsedAfterNullCheck(IOperation operation, ControlFlowRegion region, BasicBlock block, CaptureId id) { SyntaxNode whenNotNull = null; if (operation.Parent == null && operation is IsNullOperation isNull && isNull.Operand.Kind == OperationKind.FlowCaptureReference) { switch (isNull.Operand.Language) { case LanguageNames.CSharp: { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)isNull.Operand.Syntax); if (syntax.Parent is CSharp.Syntax.ConditionalAccessExpressionSyntax access && access.Expression == syntax) { whenNotNull = access.WhenNotNull; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)isNull.Operand.Syntax); if (syntax.Parent is VisualBasic.Syntax.ConditionalAccessExpressionSyntax access && access.Expression == syntax) { whenNotNull = access.WhenNotNull; } } break; } } if (whenNotNull == null) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, region.LastBlockOrdinal)) { if (candidate.Id.Equals(id)) { if (whenNotNull.Contains(candidate.Syntax)) { return true; } break; } } return false; } bool isLongLivedCaptureReferenceSyntax(SyntaxNode captureReferenceSyntax) { switch (captureReferenceSyntax.Language) { case LanguageNames.CSharp: { var syntax = (CSharpSyntaxNode)captureReferenceSyntax; switch (syntax.Kind()) { case CSharp.SyntaxKind.ObjectCreationExpression: case CSharp.SyntaxKind.ImplicitObjectCreationExpression: if (((CSharp.Syntax.BaseObjectCreationExpressionSyntax)syntax).Initializer?.Expressions.Any() == true) { return true; } break; } if (syntax.Parent is CSharp.Syntax.WithExpressionSyntax withExpr && withExpr.Initializer.Expressions.Any() && withExpr.Expression == (object)syntax) { return true; } syntax = applyParenthesizedOrNullSuppressionIfAnyCS(syntax); if (syntax.Parent?.Parent is CSharp.Syntax.UsingStatementSyntax usingStmt && usingStmt.Declaration == syntax.Parent) { return true; } CSharpSyntaxNode parent = syntax.Parent; switch (parent?.Kind()) { case CSharp.SyntaxKind.ForEachStatement: case CSharp.SyntaxKind.ForEachVariableStatement: if (((CommonForEachStatementSyntax)parent).Expression == syntax) { return true; } break; case CSharp.SyntaxKind.Argument: if ((parent = parent.Parent)?.Kind() == CSharp.SyntaxKind.BracketedArgumentList && (parent = parent.Parent)?.Kind() == CSharp.SyntaxKind.ImplicitElementAccess && parent.Parent is AssignmentExpressionSyntax assignment && assignment.Kind() == CSharp.SyntaxKind.SimpleAssignmentExpression && assignment.Left == parent && assignment.Parent?.Kind() == CSharp.SyntaxKind.ObjectInitializerExpression && (assignment.Right.Kind() == CSharp.SyntaxKind.CollectionInitializerExpression || assignment.Right.Kind() == CSharp.SyntaxKind.ObjectInitializerExpression)) { return true; } break; case CSharp.SyntaxKind.LockStatement: if (((LockStatementSyntax)syntax.Parent).Expression == syntax) { return true; } break; case CSharp.SyntaxKind.UsingStatement: if (((CSharp.Syntax.UsingStatementSyntax)syntax.Parent).Expression == syntax) { return true; } break; case CSharp.SyntaxKind.SwitchStatement: if (((CSharp.Syntax.SwitchStatementSyntax)syntax.Parent).Expression == syntax) { return true; } break; case CSharp.SyntaxKind.SwitchExpression: if (((CSharp.Syntax.SwitchExpressionSyntax)syntax.Parent).GoverningExpression == syntax) { return true; } break; case CSharp.SyntaxKind.CoalesceAssignmentExpression: if (((AssignmentExpressionSyntax)syntax.Parent).Left == syntax) { return true; } break; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)captureReferenceSyntax); switch (syntax.Kind()) { case VisualBasic.SyntaxKind.ForStatement: case VisualBasic.SyntaxKind.ForBlock: return true; case VisualBasic.SyntaxKind.ObjectCreationExpression: var objCreation = (VisualBasic.Syntax.ObjectCreationExpressionSyntax)syntax; if ((objCreation.Initializer is VisualBasic.Syntax.ObjectMemberInitializerSyntax memberInit && memberInit.Initializers.Any()) || (objCreation.Initializer is VisualBasic.Syntax.ObjectCollectionInitializerSyntax collectionInit && collectionInit.Initializer.Initializers.Any())) { return true; } break; } VisualBasicSyntaxNode parent = syntax.Parent; switch (parent?.Kind()) { case VisualBasic.SyntaxKind.ForEachStatement: if (((VisualBasic.Syntax.ForEachStatementSyntax)parent).Expression == syntax) { return true; } break; case VisualBasic.SyntaxKind.ForStatement: if (((VisualBasic.Syntax.ForStatementSyntax)parent).ToValue == syntax) { return true; } break; case VisualBasic.SyntaxKind.ForStepClause: if (((ForStepClauseSyntax)parent).StepValue == syntax) { return true; } break; case VisualBasic.SyntaxKind.SyncLockStatement: if (((VisualBasic.Syntax.SyncLockStatementSyntax)parent).Expression == syntax) { return true; } break; case VisualBasic.SyntaxKind.UsingStatement: if (((VisualBasic.Syntax.UsingStatementSyntax)parent).Expression == syntax) { return true; } break; case VisualBasic.SyntaxKind.WithStatement: if (((VisualBasic.Syntax.WithStatementSyntax)parent).Expression == syntax) { return true; } break; case VisualBasic.SyntaxKind.SelectStatement: if (((VisualBasic.Syntax.SelectStatementSyntax)parent).Expression == syntax) { return true; } break; } } break; } return false; } CSharpSyntaxNode applyParenthesizedOrNullSuppressionIfAnyCS(CSharpSyntaxNode syntax) { while (syntax.Parent is CSharp.Syntax.ParenthesizedExpressionSyntax or PostfixUnaryExpressionSyntax { OperatorToken: { RawKind: (int)CSharp.SyntaxKind.ExclamationToken } }) { syntax = syntax.Parent; } return syntax; } VisualBasicSyntaxNode applyParenthesizedIfAnyVB(VisualBasicSyntaxNode syntax) { while (syntax.Parent?.Kind() == VisualBasic.SyntaxKind.ParenthesizedExpression) { syntax = syntax.Parent; } return syntax; } IEnumerable<IFlowCaptureOperation> getFlowCaptureOperationsFromBlocksInRegion(ControlFlowRegion region, int lastBlockOrdinal) { Debug.Assert(lastBlockOrdinal <= region.LastBlockOrdinal); for (int i = lastBlockOrdinal; i >= region.FirstBlockOrdinal; i--) { for (var j = blocks[i].Operations.Length - 1; j >= 0; j--) { if (blocks[i].Operations[j] is IFlowCaptureOperation capture) { yield return capture; } } } } IEnumerable<IFlowCaptureReferenceOperation> getFlowCaptureReferenceOperationsInRegion(ControlFlowRegion region, int firstBlockOrdinal) { Debug.Assert(firstBlockOrdinal >= region.FirstBlockOrdinal); for (int i = firstBlockOrdinal; i <= region.LastBlockOrdinal; i++) { BasicBlock block = blocks[i]; foreach (IOperation operation in block.Operations) { foreach (IFlowCaptureReferenceOperation reference in operation.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { yield return reference; } } if (block.BranchValue != null) { foreach (IFlowCaptureReferenceOperation reference in block.BranchValue.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { yield return reference; } } } } string getDestinationString(ref ControlFlowBranch branch) { return branch.Destination != null ? getBlockId(branch.Destination) : "null"; } PooledObjects.PooledDictionary<ControlFlowRegion, int> buildRegionMap() { var result = PooledObjects.PooledDictionary<ControlFlowRegion, int>.GetInstance(); int ordinal = 0; visit(graph.Root); void visit(ControlFlowRegion region) { result.Add(region, ordinal++); foreach (ControlFlowRegion r in region.NestedRegions) { visit(r); } } return result; } void appendLine(string line) { appendIndent(); stringBuilder.AppendLine(line); } void appendIndent() { stringBuilder.Append(' ', indent); } void printLocals(ControlFlowRegion region) { if (!region.Locals.IsEmpty) { appendIndent(); stringBuilder.Append("Locals:"); foreach (ILocalSymbol local in region.Locals) { stringBuilder.Append($" [{local.ToTestDisplayString()}]"); } stringBuilder.AppendLine(); } if (!region.LocalFunctions.IsEmpty) { appendIndent(); stringBuilder.Append("Methods:"); foreach (IMethodSymbol method in region.LocalFunctions) { stringBuilder.Append($" [{method.ToTestDisplayString()}]"); } stringBuilder.AppendLine(); } if (!region.CaptureIds.IsEmpty) { appendIndent(); stringBuilder.Append("CaptureIds:"); foreach (CaptureId id in region.CaptureIds) { stringBuilder.Append($" [{id.Value}]"); } stringBuilder.AppendLine(); } } void enterRegions(ControlFlowRegion region, int firstBlockOrdinal) { if (region.FirstBlockOrdinal != firstBlockOrdinal) { Assert.Same(currentRegion, region); if (lastPrintedBlockIsInCurrentRegion) { stringBuilder.AppendLine(); } return; } enterRegions(region.EnclosingRegion, firstBlockOrdinal); currentRegion = region; lastPrintedBlockIsInCurrentRegion = true; switch (region.Kind) { case ControlFlowRegionKind.Filter: Assert.Empty(region.Locals); Assert.Empty(region.LocalFunctions); Assert.Equal(firstBlockOrdinal, region.EnclosingRegion.FirstBlockOrdinal); Assert.Same(region.ExceptionType, region.EnclosingRegion.ExceptionType); enterRegion($".filter {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.Try: Assert.Null(region.ExceptionType); Assert.Equal(firstBlockOrdinal, region.EnclosingRegion.FirstBlockOrdinal); enterRegion($".try {{{getRegionId(region.EnclosingRegion)}, {getRegionId(region)}}}"); break; case ControlFlowRegionKind.FilterAndHandler: enterRegion($".catch {{{getRegionId(region)}}} ({region.ExceptionType?.ToTestDisplayString() ?? "null"})"); break; case ControlFlowRegionKind.Finally: Assert.Null(region.ExceptionType); enterRegion($".finally {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.Catch: switch (region.EnclosingRegion.Kind) { case ControlFlowRegionKind.FilterAndHandler: Assert.Same(region.ExceptionType, region.EnclosingRegion.ExceptionType); enterRegion($".handler {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.TryAndCatch: enterRegion($".catch {{{getRegionId(region)}}} ({region.ExceptionType?.ToTestDisplayString() ?? "null"})"); break; default: Assert.False(true, $"Unexpected region kind {region.EnclosingRegion.Kind}"); break; } break; case ControlFlowRegionKind.LocalLifetime: Assert.Null(region.ExceptionType); Assert.False(region.Locals.IsEmpty && region.LocalFunctions.IsEmpty && region.CaptureIds.IsEmpty); enterRegion($".locals {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.TryAndCatch: case ControlFlowRegionKind.TryAndFinally: Assert.Empty(region.Locals); Assert.Empty(region.LocalFunctions); Assert.Empty(region.CaptureIds); Assert.Null(region.ExceptionType); break; case ControlFlowRegionKind.StaticLocalInitializer: Assert.Null(region.ExceptionType); Assert.Empty(region.Locals); enterRegion($".static initializer {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.ErroneousBody: Assert.Null(region.ExceptionType); enterRegion($".erroneous body {{{getRegionId(region)}}}"); break; default: Assert.False(true, $"Unexpected region kind {region.Kind}"); break; } void enterRegion(string header) { appendLine(header); appendLine("{"); indent += 4; printLocals(region); } } void leaveRegions(ControlFlowRegion region, int lastBlockOrdinal) { if (region.LastBlockOrdinal != lastBlockOrdinal) { currentRegion = region; lastPrintedBlockIsInCurrentRegion = false; return; } string regionId = getRegionId(region); for (var i = 0; i < region.LocalFunctions.Length; i++) { var method = region.LocalFunctions[i]; appendLine(""); appendLine("{ " + method.ToTestDisplayString()); appendLine(""); var g = graph.GetLocalFunctionControlFlowGraph(method); localFunctionsMap.Add(method, g); Assert.Equal(OperationKind.LocalFunction, g.OriginalOperation.Kind); GetFlowGraph(stringBuilder, compilation, g, region, $"#{i}{regionId}", indent + 4, associatedSymbol); appendLine("}"); } switch (region.Kind) { case ControlFlowRegionKind.LocalLifetime: case ControlFlowRegionKind.Filter: case ControlFlowRegionKind.Try: case ControlFlowRegionKind.Finally: case ControlFlowRegionKind.FilterAndHandler: case ControlFlowRegionKind.StaticLocalInitializer: case ControlFlowRegionKind.ErroneousBody: indent -= 4; appendLine("}"); break; case ControlFlowRegionKind.Catch: switch (region.EnclosingRegion.Kind) { case ControlFlowRegionKind.FilterAndHandler: case ControlFlowRegionKind.TryAndCatch: goto endRegion; default: Assert.False(true, $"Unexpected region kind {region.EnclosingRegion.Kind}"); break; } break; endRegion: goto case ControlFlowRegionKind.Filter; case ControlFlowRegionKind.TryAndCatch: case ControlFlowRegionKind.TryAndFinally: break; default: Assert.False(true, $"Unexpected region kind {region.Kind}"); break; } leaveRegions(region.EnclosingRegion, lastBlockOrdinal); } void validateBranch(BasicBlock fromBlock, ControlFlowBranch branch) { if (branch.Destination == null) { Assert.Empty(branch.FinallyRegions); Assert.Empty(branch.LeavingRegions); Assert.Empty(branch.EnteringRegions); Assert.True(ControlFlowBranchSemantics.None == branch.Semantics || ControlFlowBranchSemantics.Throw == branch.Semantics || ControlFlowBranchSemantics.Rethrow == branch.Semantics || ControlFlowBranchSemantics.StructuredExceptionHandling == branch.Semantics || ControlFlowBranchSemantics.ProgramTermination == branch.Semantics || ControlFlowBranchSemantics.Error == branch.Semantics); return; } Assert.True(ControlFlowBranchSemantics.Regular == branch.Semantics || ControlFlowBranchSemantics.Return == branch.Semantics); Assert.True(branch.Destination.Predecessors.Contains(p => p.Source == fromBlock)); if (!branch.FinallyRegions.IsEmpty) { appendLine($" Finalizing:" + buildList(branch.FinallyRegions)); } ControlFlowRegion remainedIn1 = fromBlock.EnclosingRegion; if (!branch.LeavingRegions.IsEmpty) { appendLine($" Leaving:" + buildList(branch.LeavingRegions)); foreach (ControlFlowRegion r in branch.LeavingRegions) { Assert.Same(remainedIn1, r); remainedIn1 = r.EnclosingRegion; } } ControlFlowRegion remainedIn2 = branch.Destination.EnclosingRegion; if (!branch.EnteringRegions.IsEmpty) { appendLine($" Entering:" + buildList(branch.EnteringRegions)); for (int j = branch.EnteringRegions.Length - 1; j >= 0; j--) { ControlFlowRegion r = branch.EnteringRegions[j]; Assert.Same(remainedIn2, r); remainedIn2 = r.EnclosingRegion; } } Assert.Same(remainedIn1.EnclosingRegion, remainedIn2.EnclosingRegion); string buildList(ImmutableArray<ControlFlowRegion> list) { var builder = PooledObjects.PooledStringBuilder.GetInstance(); foreach (ControlFlowRegion r in list) { builder.Builder.Append($" {{{getRegionId(r)}}}"); } return builder.ToStringAndFree(); } } void validateRoot(IOperation root) { visitor.Visit(root); Assert.Null(root.Parent); Assert.Null(((Operation)root).OwningSemanticModel); Assert.Null(root.SemanticModel); Assert.True(CanBeInControlFlowGraph(root), $"Unexpected node kind OperationKind.{root.Kind}"); foreach (var operation in root.Descendants()) { visitor.Visit(operation); Assert.NotNull(operation.Parent); Assert.Null(((Operation)operation).OwningSemanticModel); Assert.Null(operation.SemanticModel); Assert.True(CanBeInControlFlowGraph(operation), $"Unexpected node kind OperationKind.{operation.Kind}"); } } void validateLifetimeOfReferences(BasicBlock block, Func<string> finalGraph) { referencedCaptureIds.Clear(); referencedLocalsAndMethods.Clear(); foreach (IOperation operation in block.Operations) { recordReferences(operation); } if (block.BranchValue != null) { recordReferences(block.BranchValue); } ControlFlowRegion region = block.EnclosingRegion; while ((referencedCaptureIds.Count != 0 || referencedLocalsAndMethods.Count != 0) && region != null) { foreach (ILocalSymbol l in region.Locals) { referencedLocalsAndMethods.Remove(l); } foreach (IMethodSymbol m in region.LocalFunctions) { referencedLocalsAndMethods.Remove(m); } foreach (CaptureId id in region.CaptureIds) { referencedCaptureIds.Remove(id); } region = region.EnclosingRegion; } if (referencedLocalsAndMethods.Count != 0) { ISymbol symbol = referencedLocalsAndMethods.First(); Assert.True(false, $"{(symbol.Kind == SymbolKind.Local ? "Local" : "Method")} without owning region {symbol.ToTestDisplayString()} in [{getBlockId(block)}]\n{finalGraph()}"); } if (referencedCaptureIds.Count != 0) { Assert.True(false, $"Capture [{referencedCaptureIds.First().Value}] without owning region in [{getBlockId(block)}]\n{finalGraph()}"); } } void recordReferences(IOperation operation) { foreach (IOperation node in operation.DescendantsAndSelf()) { IMethodSymbol method; switch (node) { case ILocalReferenceOperation localReference: if (localReference.Local.ContainingSymbol.IsTopLevelMainMethod() && !isInAssociatedSymbol(localReference.Local.ContainingSymbol, associatedSymbol)) { // Top-level locals can be referenced from locations in the same file that are not actually the top // level main. For these cases, we want to treat them like fields for the purposes of references, // as they are not declared in this method and have no owning region break; } referencedLocalsAndMethods.Add(localReference.Local); break; case IMethodReferenceOperation methodReference: method = methodReference.Method; if (method.MethodKind == MethodKind.LocalFunction) { if (method.ContainingSymbol.IsTopLevelMainMethod() && !isInAssociatedSymbol(method.ContainingSymbol, associatedSymbol)) { // Top-level local functions can be referenced from locations in the same file that are not actually the top // level main. For these cases, we want to treat them like class methods for the purposes of references, // as they are not declared in this method and have no owning region break; } referencedLocalsAndMethods.Add(method.OriginalDefinition); } break; case IInvocationOperation invocation: method = invocation.TargetMethod; if (method.MethodKind == MethodKind.LocalFunction) { if (method.ContainingSymbol.IsTopLevelMainMethod() && !associatedSymbol.IsTopLevelMainMethod()) { // Top-level local functions can be referenced from locations in the same file that are not actually the top // level main. For these cases, we want to treat them like class methods for the purposes of references, // as they are not declared in this method and have no owning region break; } referencedLocalsAndMethods.Add(method.OriginalDefinition); } break; case IFlowCaptureOperation flowCapture: referencedCaptureIds.Add(flowCapture.Id); break; case IFlowCaptureReferenceOperation flowCaptureReference: referencedCaptureIds.Add(flowCaptureReference.Id); break; } } static bool isInAssociatedSymbol(ISymbol symbol, ISymbol associatedSymbol) { while (symbol is IMethodSymbol m) { if ((object)m == associatedSymbol) { return true; } symbol = m.ContainingSymbol; } return false; } } string getBlockId(BasicBlock block) { return $"B{block.Ordinal}{idSuffix}"; } string getRegionId(ControlFlowRegion region) { return $"R{regionMap[region]}{idSuffix}"; } string getOperationTree(IOperation operation) { var walker = new OperationTreeSerializer(graph, currentRegion, idSuffix, anonymousFunctionsMap, compilation, operation, initialIndent: 8 + indent, associatedSymbol); walker.Visit(operation); return walker.Builder.ToString(); } } private static void AssertTrueWithGraph([DoesNotReturnIf(false)] bool value, string message, Func<string> finalGraph) { if (!value) { Assert.True(value, $"{message}\n{finalGraph()}"); } } private sealed class OperationTreeSerializer : OperationTreeVerifier { private readonly ControlFlowGraph _graph; private readonly ControlFlowRegion _region; private readonly string _idSuffix; private readonly Dictionary<IFlowAnonymousFunctionOperation, ControlFlowGraph> _anonymousFunctionsMap; private readonly ISymbol _associatedSymbol; public OperationTreeSerializer(ControlFlowGraph graph, ControlFlowRegion region, string idSuffix, Dictionary<IFlowAnonymousFunctionOperation, ControlFlowGraph> anonymousFunctionsMap, Compilation compilation, IOperation root, int initialIndent, ISymbol associatedSymbol) : base(compilation, root, initialIndent) { _graph = graph; _region = region; _idSuffix = idSuffix; _anonymousFunctionsMap = anonymousFunctionsMap; _associatedSymbol = associatedSymbol; } public System.Text.StringBuilder Builder => _builder; public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { base.VisitFlowAnonymousFunction(operation); LogString("{"); LogNewLine(); var g = _graph.GetAnonymousFunctionControlFlowGraph(operation); int id = _anonymousFunctionsMap.Count; _anonymousFunctionsMap.Add(operation, g); Assert.Equal(OperationKind.AnonymousFunction, g.OriginalOperation.Kind); GetFlowGraph(_builder, _compilation, g, _region, $"#A{id}{_idSuffix}", _currentIndent.Length + 4, _associatedSymbol); LogString("}"); LogNewLine(); } } private static bool CanBeInControlFlowGraph(IOperation n) { switch (n.Kind) { case OperationKind.Block: case OperationKind.Switch: case OperationKind.Loop: case OperationKind.Branch: case OperationKind.Lock: case OperationKind.Try: case OperationKind.Using: case OperationKind.Conditional: case OperationKind.Coalesce: case OperationKind.ConditionalAccess: case OperationKind.ConditionalAccessInstance: case OperationKind.MemberInitializer: case OperationKind.FieldInitializer: case OperationKind.PropertyInitializer: case OperationKind.ParameterInitializer: case OperationKind.CatchClause: case OperationKind.SwitchCase: case OperationKind.CaseClause: case OperationKind.VariableDeclarationGroup: case OperationKind.VariableDeclaration: case OperationKind.VariableDeclarator: case OperationKind.VariableInitializer: case OperationKind.Return: case OperationKind.YieldBreak: case OperationKind.Labeled: case OperationKind.Throw: case OperationKind.End: case OperationKind.Empty: case OperationKind.NameOf: case OperationKind.AnonymousFunction: case OperationKind.ObjectOrCollectionInitializer: case OperationKind.LocalFunction: case OperationKind.CoalesceAssignment: case OperationKind.SwitchExpression: case OperationKind.SwitchExpressionArm: return false; case OperationKind.Binary: var binary = (IBinaryOperation)n; return (binary.OperatorKind != Operations.BinaryOperatorKind.ConditionalAnd && binary.OperatorKind != Operations.BinaryOperatorKind.ConditionalOr) || (binary.OperatorMethod == null && !ITypeSymbolHelpers.IsBooleanType(binary.Type) && !ITypeSymbolHelpers.IsNullableOfBoolean(binary.Type) && !ITypeSymbolHelpers.IsObjectType(binary.Type) && !ITypeSymbolHelpers.IsDynamicType(binary.Type)); case OperationKind.InstanceReference: // Implicit instance receivers, except for anonymous type creations, are expected to have been removed when dealing with creations. var instanceReference = (IInstanceReferenceOperation)n; return instanceReference.ReferenceKind == InstanceReferenceKind.ContainingTypeInstance || instanceReference.ReferenceKind == InstanceReferenceKind.PatternInput || (instanceReference.ReferenceKind == InstanceReferenceKind.ImplicitReceiver && n.Type.IsAnonymousType && n.Parent is IPropertyReferenceOperation propertyReference && propertyReference.Instance == n && propertyReference.Parent is ISimpleAssignmentOperation simpleAssignment && simpleAssignment.Target == propertyReference && simpleAssignment.Parent.Kind == OperationKind.AnonymousObjectCreation); case OperationKind.None: return !(n is IPlaceholderOperation); case OperationKind.Invalid: case OperationKind.YieldReturn: case OperationKind.ExpressionStatement: case OperationKind.Stop: case OperationKind.RaiseEvent: case OperationKind.Literal: case OperationKind.Conversion: case OperationKind.Invocation: case OperationKind.ArrayElementReference: case OperationKind.LocalReference: case OperationKind.ParameterReference: case OperationKind.FieldReference: case OperationKind.MethodReference: case OperationKind.PropertyReference: case OperationKind.EventReference: case OperationKind.FlowAnonymousFunction: case OperationKind.ObjectCreation: case OperationKind.TypeParameterObjectCreation: case OperationKind.ArrayCreation: case OperationKind.ArrayInitializer: case OperationKind.IsType: case OperationKind.Await: case OperationKind.SimpleAssignment: case OperationKind.CompoundAssignment: case OperationKind.Parenthesized: case OperationKind.EventAssignment: case OperationKind.InterpolatedString: case OperationKind.AnonymousObjectCreation: case OperationKind.Tuple: case OperationKind.TupleBinary: case OperationKind.DynamicObjectCreation: case OperationKind.DynamicMemberReference: case OperationKind.DynamicInvocation: case OperationKind.DynamicIndexerAccess: case OperationKind.TranslatedQuery: case OperationKind.DelegateCreation: case OperationKind.DefaultValue: case OperationKind.TypeOf: case OperationKind.SizeOf: case OperationKind.AddressOf: case OperationKind.IsPattern: case OperationKind.Increment: case OperationKind.Decrement: case OperationKind.DeconstructionAssignment: case OperationKind.DeclarationExpression: case OperationKind.OmittedArgument: case OperationKind.Argument: case OperationKind.InterpolatedStringText: case OperationKind.Interpolation: case OperationKind.ConstantPattern: case OperationKind.DeclarationPattern: case OperationKind.Unary: case OperationKind.FlowCapture: case OperationKind.FlowCaptureReference: case OperationKind.IsNull: case OperationKind.CaughtException: case OperationKind.StaticLocalInitializationSemaphore: case OperationKind.Discard: case OperationKind.ReDim: case OperationKind.ReDimClause: case OperationKind.Range: case OperationKind.RecursivePattern: case OperationKind.DiscardPattern: case OperationKind.PropertySubpattern: case OperationKind.RelationalPattern: case OperationKind.NegatedPattern: case OperationKind.BinaryPattern: case OperationKind.TypePattern: return true; } Assert.True(false, $"Unhandled node kind OperationKind.{n.Kind}"); return false; } #nullable enable private static bool IsTopLevelMainMethod([NotNullWhen(true)] this ISymbol? symbol) { return symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType: INamedTypeSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, ContainingType: null, ContainingNamespace: { IsGlobalNamespace: true } } }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.VisualBasic.Syntax; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class ControlFlowGraphVerifier { public static (ControlFlowGraph graph, ISymbol associatedSymbol) GetControlFlowGraph(SyntaxNode syntaxNode, SemanticModel model) { IOperation operationRoot = model.GetOperation(syntaxNode); // Workaround for unit tests designed to work on IBlockOperation with ConstructorBodyOperation/MethodBodyOperation parent. operationRoot = operationRoot.Kind == OperationKind.Block && (operationRoot.Parent?.Kind == OperationKind.ConstructorBody || operationRoot.Parent?.Kind == OperationKind.MethodBody) ? operationRoot.Parent : operationRoot; TestOperationVisitor.VerifySubTree(operationRoot); ControlFlowGraph graph; switch (operationRoot) { case IBlockOperation blockOperation: graph = ControlFlowGraph.Create(blockOperation); break; case IMethodBodyOperation methodBodyOperation: graph = ControlFlowGraph.Create(methodBodyOperation); break; case IConstructorBodyOperation constructorBodyOperation: graph = ControlFlowGraph.Create(constructorBodyOperation); break; case IFieldInitializerOperation fieldInitializerOperation: graph = ControlFlowGraph.Create(fieldInitializerOperation); break; case IPropertyInitializerOperation propertyInitializerOperation: graph = ControlFlowGraph.Create(propertyInitializerOperation); break; case IParameterInitializerOperation parameterInitializerOperation: graph = ControlFlowGraph.Create(parameterInitializerOperation); break; default: return default; } Assert.NotNull(graph); Assert.Same(operationRoot, graph.OriginalOperation); var declaredSymbol = model.GetDeclaredSymbol(operationRoot.Syntax); return (graph, declaredSymbol); } public static void VerifyGraph(Compilation compilation, string expectedFlowGraph, ControlFlowGraph graph, ISymbol associatedSymbol) { var actualFlowGraph = GetFlowGraph(compilation, graph, associatedSymbol); OperationTreeVerifier.Verify(expectedFlowGraph, actualFlowGraph); // Basic block reachability analysis verification using a test-only dataflow analyzer // that uses the dataflow analysis engine linked from the Workspaces layer. // This provides test coverage for Workspace layer dataflow analysis engine // for all ControlFlowGraphs created in compiler layer's flow analysis unit tests. var reachabilityVector = BasicBlockReachabilityDataFlowAnalyzer.Run(graph); for (int i = 0; i < graph.Blocks.Length; i++) { Assert.Equal(graph.Blocks[i].IsReachable, reachabilityVector[i]); } } public static string GetFlowGraph(Compilation compilation, ControlFlowGraph graph, ISymbol associatedSymbol) { var pooledBuilder = PooledObjects.PooledStringBuilder.GetInstance(); var stringBuilder = pooledBuilder.Builder; GetFlowGraph(pooledBuilder.Builder, compilation, graph, enclosing: null, idSuffix: "", indent: 0, associatedSymbol); return pooledBuilder.ToStringAndFree(); } private static void GetFlowGraph(System.Text.StringBuilder stringBuilder, Compilation compilation, ControlFlowGraph graph, ControlFlowRegion enclosing, string idSuffix, int indent, ISymbol associatedSymbol) { ImmutableArray<BasicBlock> blocks = graph.Blocks; var visitor = TestOperationVisitor.Singleton; ControlFlowRegion currentRegion = graph.Root; bool lastPrintedBlockIsInCurrentRegion = true; PooledDictionary<ControlFlowRegion, int> regionMap = buildRegionMap(); var localFunctionsMap = PooledDictionary<IMethodSymbol, ControlFlowGraph>.GetInstance(); var anonymousFunctionsMap = PooledDictionary<IFlowAnonymousFunctionOperation, ControlFlowGraph>.GetInstance(); var referencedLocalsAndMethods = PooledHashSet<ISymbol>.GetInstance(); var referencedCaptureIds = PooledHashSet<CaptureId>.GetInstance(); for (int i = 0; i < blocks.Length; i++) { var block = blocks[i]; Assert.Equal(i, block.Ordinal); switch (block.Kind) { case BasicBlockKind.Block: Assert.NotEqual(0, i); Assert.NotEqual(blocks.Length - 1, i); break; case BasicBlockKind.Entry: Assert.Equal(0, i); Assert.Empty(block.Operations); Assert.Empty(block.Predecessors); Assert.Null(block.BranchValue); Assert.NotNull(block.FallThroughSuccessor); Assert.NotNull(block.FallThroughSuccessor.Destination); Assert.Null(block.ConditionalSuccessor); Assert.Same(graph.Root, currentRegion); Assert.Same(currentRegion, block.EnclosingRegion); Assert.Equal(0, currentRegion.FirstBlockOrdinal); Assert.Same(enclosing, currentRegion.EnclosingRegion); Assert.Null(currentRegion.ExceptionType); Assert.Empty(currentRegion.Locals); Assert.Empty(currentRegion.LocalFunctions); Assert.Empty(currentRegion.CaptureIds); Assert.Equal(ControlFlowRegionKind.Root, currentRegion.Kind); Assert.True(block.IsReachable); break; case BasicBlockKind.Exit: Assert.Equal(blocks.Length - 1, i); Assert.Empty(block.Operations); Assert.Null(block.FallThroughSuccessor); Assert.Null(block.ConditionalSuccessor); Assert.Null(block.BranchValue); Assert.Same(graph.Root, currentRegion); Assert.Same(currentRegion, block.EnclosingRegion); Assert.Equal(i, currentRegion.LastBlockOrdinal); break; default: Assert.False(true, $"Unexpected block kind {block.Kind}"); break; } if (block.EnclosingRegion != currentRegion) { enterRegions(block.EnclosingRegion, block.Ordinal); } if (!lastPrintedBlockIsInCurrentRegion) { stringBuilder.AppendLine(); } appendLine($"Block[{getBlockId(block)}] - {block.Kind}{(block.IsReachable ? "" : " [UnReachable]")}"); var predecessors = block.Predecessors; if (!predecessors.IsEmpty) { appendIndent(); stringBuilder.Append(" Predecessors:"); int previousPredecessorOrdinal = -1; for (var predecessorIndex = 0; predecessorIndex < predecessors.Length; predecessorIndex++) { var predecessorBranch = predecessors[predecessorIndex]; Assert.Same(block, predecessorBranch.Destination); var predecessor = predecessorBranch.Source; Assert.True(previousPredecessorOrdinal < predecessor.Ordinal); previousPredecessorOrdinal = predecessor.Ordinal; Assert.Same(blocks[predecessor.Ordinal], predecessor); if (predecessorBranch.IsConditionalSuccessor) { Assert.Same(predecessor.ConditionalSuccessor, predecessorBranch); Assert.NotEqual(ControlFlowConditionKind.None, predecessor.ConditionKind); } else { Assert.Same(predecessor.FallThroughSuccessor, predecessorBranch); } stringBuilder.Append($" [{getBlockId(predecessor)}"); if (predecessorIndex < predecessors.Length - 1 && predecessors[predecessorIndex + 1].Source == predecessor) { // Multiple branches from same predecessor - one must be conditional and other fall through. Assert.True(predecessorBranch.IsConditionalSuccessor); predecessorIndex++; predecessorBranch = predecessors[predecessorIndex]; Assert.Same(predecessor.FallThroughSuccessor, predecessorBranch); Assert.False(predecessorBranch.IsConditionalSuccessor); stringBuilder.Append("*2"); } stringBuilder.Append("]"); } stringBuilder.AppendLine(); } else if (block.Kind != BasicBlockKind.Entry) { appendLine(" Predecessors (0)"); } var statements = block.Operations; appendLine($" Statements ({statements.Length})"); foreach (var statement in statements) { validateRoot(statement); stringBuilder.AppendLine(getOperationTree(statement)); } ControlFlowBranch conditionalBranch = block.ConditionalSuccessor; if (block.ConditionKind != ControlFlowConditionKind.None) { Assert.NotNull(conditionalBranch); Assert.True(conditionalBranch.IsConditionalSuccessor); Assert.Same(block, conditionalBranch.Source); if (conditionalBranch.Destination != null) { Assert.Same(blocks[conditionalBranch.Destination.Ordinal], conditionalBranch.Destination); } Assert.NotEqual(ControlFlowBranchSemantics.Return, conditionalBranch.Semantics); Assert.NotEqual(ControlFlowBranchSemantics.Throw, conditionalBranch.Semantics); Assert.NotEqual(ControlFlowBranchSemantics.StructuredExceptionHandling, conditionalBranch.Semantics); Assert.True(block.ConditionKind == ControlFlowConditionKind.WhenTrue || block.ConditionKind == ControlFlowConditionKind.WhenFalse); string jumpIfTrue = block.ConditionKind == ControlFlowConditionKind.WhenTrue ? "True" : "False"; appendLine($" Jump if {jumpIfTrue} ({conditionalBranch.Semantics}) to Block[{getDestinationString(ref conditionalBranch)}]"); IOperation value = block.BranchValue; Assert.NotNull(value); validateRoot(value); stringBuilder.Append(getOperationTree(value)); validateBranch(block, conditionalBranch); stringBuilder.AppendLine(); } else { Assert.Null(conditionalBranch); Assert.Equal(ControlFlowConditionKind.None, block.ConditionKind); } ControlFlowBranch nextBranch = block.FallThroughSuccessor; if (block.Kind == BasicBlockKind.Exit) { Assert.Null(nextBranch); Assert.Null(block.BranchValue); } else { Assert.NotNull(nextBranch); Assert.False(nextBranch.IsConditionalSuccessor); Assert.Same(block, nextBranch.Source); if (nextBranch.Destination != null) { Assert.Same(blocks[nextBranch.Destination.Ordinal], nextBranch.Destination); } if (nextBranch.Semantics == ControlFlowBranchSemantics.StructuredExceptionHandling) { Assert.Null(nextBranch.Destination); Assert.Equal(block.EnclosingRegion.LastBlockOrdinal, block.Ordinal); Assert.True(block.EnclosingRegion.Kind == ControlFlowRegionKind.Filter || block.EnclosingRegion.Kind == ControlFlowRegionKind.Finally); } appendLine($" Next ({nextBranch.Semantics}) Block[{getDestinationString(ref nextBranch)}]"); IOperation value = block.ConditionKind == ControlFlowConditionKind.None ? block.BranchValue : null; if (value != null) { Assert.True(ControlFlowBranchSemantics.Return == nextBranch.Semantics || ControlFlowBranchSemantics.Throw == nextBranch.Semantics); validateRoot(value); stringBuilder.Append(getOperationTree(value)); } else { Assert.NotEqual(ControlFlowBranchSemantics.Return, nextBranch.Semantics); Assert.NotEqual(ControlFlowBranchSemantics.Throw, nextBranch.Semantics); } validateBranch(block, nextBranch); } if (currentRegion.LastBlockOrdinal == block.Ordinal && i != blocks.Length - 1) { leaveRegions(block.EnclosingRegion, block.Ordinal); } else { lastPrintedBlockIsInCurrentRegion = true; } } foreach (IMethodSymbol m in graph.LocalFunctions) { ControlFlowGraph g = localFunctionsMap[m]; Assert.Same(g, graph.GetLocalFunctionControlFlowGraph(m)); Assert.Same(g, graph.GetLocalFunctionControlFlowGraphInScope(m)); Assert.Same(graph, g.Parent); } Assert.Equal(graph.LocalFunctions.Length, localFunctionsMap.Count); foreach (KeyValuePair<IFlowAnonymousFunctionOperation, ControlFlowGraph> pair in anonymousFunctionsMap) { Assert.Same(pair.Value, graph.GetAnonymousFunctionControlFlowGraph(pair.Key)); Assert.Same(pair.Value, graph.GetAnonymousFunctionControlFlowGraphInScope(pair.Key)); Assert.Same(graph, pair.Value.Parent); } bool doCaptureVerification = true; if (graph.OriginalOperation.Language == LanguageNames.VisualBasic) { var model = compilation.GetSemanticModel(graph.OriginalOperation.Syntax.SyntaxTree); if (model.GetDiagnostics(graph.OriginalOperation.Syntax.Span). Any(d => d.Code == (int)VisualBasic.ERRID.ERR_GotoIntoWith || d.Code == (int)VisualBasic.ERRID.ERR_GotoIntoFor || d.Code == (int)VisualBasic.ERRID.ERR_GotoIntoSyncLock || d.Code == (int)VisualBasic.ERRID.ERR_GotoIntoUsing)) { // Invalid branches like that are often causing reports about // using captures before they are initialized. doCaptureVerification = false; } } Func<string> finalGraph = () => stringBuilder.ToString(); if (doCaptureVerification) { verifyCaptures(finalGraph); } foreach (var block in blocks) { validateLifetimeOfReferences(block, finalGraph); } regionMap.Free(); localFunctionsMap.Free(); anonymousFunctionsMap.Free(); referencedLocalsAndMethods.Free(); referencedCaptureIds.Free(); return; void verifyCaptures(Func<string> finalGraph) { var longLivedIds = PooledHashSet<CaptureId>.GetInstance(); var referencedIds = PooledHashSet<CaptureId>.GetInstance(); var entryStates = ArrayBuilder<PooledHashSet<CaptureId>>.GetInstance(blocks.Length, fillWithValue: null); var regions = ArrayBuilder<ControlFlowRegion>.GetInstance(); for (int i = 1; i < blocks.Length - 1; i++) { BasicBlock block = blocks[i]; PooledHashSet<CaptureId> currentState = entryStates[i] ?? PooledHashSet<CaptureId>.GetInstance(); entryStates[i] = null; foreach (ControlFlowBranch predecessor in block.Predecessors) { if (predecessor.Source.Ordinal >= i) { foreach (ControlFlowRegion region in predecessor.EnteringRegions) { if (region.FirstBlockOrdinal != block.Ordinal) { foreach (CaptureId id in region.CaptureIds) { AssertTrueWithGraph(currentState.Contains(id), $"Backward branch from [{getBlockId(predecessor.Source)}] to [{getBlockId(block)}] before capture [{id.Value}] is initialized.", finalGraph); } } } } } for (var j = 0; j < block.Operations.Length; j++) { var operation = block.Operations[j]; if (operation is IFlowCaptureOperation capture) { assertCaptureReferences(currentState, capture.Value, block, j, longLivedIds, referencedIds, finalGraph); AssertTrueWithGraph(currentState.Add(capture.Id), $"Operation [{j}] in [{getBlockId(block)}] re-initialized capture [{capture.Id.Value}]", finalGraph); } else { assertCaptureReferences(currentState, operation, block, j, longLivedIds, referencedIds, finalGraph); } } if (block.BranchValue != null) { assertCaptureReferences(currentState, block.BranchValue, block, block.Operations.Length, longLivedIds, referencedIds, finalGraph); if (block.ConditionalSuccessor != null) { adjustEntryStateForDestination(entryStates, block.ConditionalSuccessor, currentState); } } adjustEntryStateForDestination(entryStates, block.FallThroughSuccessor, currentState); if (blocks[i + 1].Predecessors.IsEmpty) { adjustAndGetEntryState(entryStates, blocks[i + 1], currentState); } verifyLeftRegions(block, longLivedIds, referencedIds, regions, finalGraph); currentState.Free(); } foreach (PooledHashSet<CaptureId> state in entryStates) { state?.Free(); } entryStates.Free(); longLivedIds.Free(); referencedIds.Free(); regions.Free(); } void verifyLeftRegions(BasicBlock block, PooledHashSet<CaptureId> longLivedIds, PooledHashSet<CaptureId> referencedIds, ArrayBuilder<ControlFlowRegion> regions, Func<string> finalGraph) { regions.Clear(); { ControlFlowRegion region = block.EnclosingRegion; while (region.LastBlockOrdinal == block.Ordinal) { regions.Add(region); region = region.EnclosingRegion; } } if (block.ConditionalSuccessor != null && block.ConditionalSuccessor.LeavingRegions.Length > regions.Count) { regions.Clear(); regions.AddRange(block.ConditionalSuccessor.LeavingRegions); } if (block.FallThroughSuccessor.LeavingRegions.Length > regions.Count) { regions.Clear(); regions.AddRange(block.FallThroughSuccessor.LeavingRegions); } if (regions.Count > 0) { IOperation lastOperation = null; for (int i = block.Ordinal; i > 0 && lastOperation == null; i--) { lastOperation = blocks[i].BranchValue ?? blocks[i].Operations.LastOrDefault(); } var referencedInLastOperation = PooledHashSet<CaptureId>.GetInstance(); if (lastOperation != null) { foreach (IFlowCaptureReferenceOperation reference in lastOperation.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { referencedInLastOperation.Add(reference.Id); } } foreach (ControlFlowRegion region in regions) { foreach (CaptureId id in region.CaptureIds) { if (referencedInLastOperation.Contains(id) || longLivedIds.Contains(id) || isCSharpEmptyObjectInitializerCapture(region, block, id) || isWithStatementTargetCapture(region, block, id) || isSwitchTargetCapture(region, block, id) || isForEachEnumeratorCapture(region, block, id) || isConditionalXMLAccessReceiverCapture(region, block, id) || isConditionalAccessCaptureUsedAfterNullCheck(lastOperation, region, block, id) || (referencedIds.Contains(id) && isAggregateGroupCapture(lastOperation, region, block, id))) { continue; } if (region.LastBlockOrdinal != block.Ordinal && referencedIds.Contains(id)) { continue; } IFlowCaptureReferenceOperation[] referencesAfter = getFlowCaptureReferenceOperationsInRegion(region, block.Ordinal + 1).Where(r => r.Id.Equals(id)).ToArray(); AssertTrueWithGraph(referencesAfter.Length > 0 && referencesAfter.All(r => isLongLivedCaptureReferenceSyntax(r.Syntax)), $"Capture [{id.Value}] is not used in region [{getRegionId(region)}] before leaving it after block [{getBlockId(block)}]", finalGraph); } } referencedInLastOperation.Free(); } } bool isCSharpEmptyObjectInitializerCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { if (graph.OriginalOperation.Language != LanguageNames.CSharp) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)candidate.Syntax); CSharpSyntaxNode parent = syntax; do { parent = parent.Parent; } while (parent != null && parent.Kind() != CSharp.SyntaxKind.SimpleAssignmentExpression); if (parent is AssignmentExpressionSyntax assignment && assignment.Parent?.Kind() == CSharp.SyntaxKind.ObjectInitializerExpression && assignment.Left.DescendantNodesAndSelf().Contains(syntax) && assignment.Right is InitializerExpressionSyntax initializer && initializer.Kind() == CSharp.SyntaxKind.ObjectInitializerExpression && !initializer.Expressions.Any()) { return true; } break; } } return false; } bool isWithStatementTargetCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { if (graph.OriginalOperation.Language != LanguageNames.VisualBasic) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); VisualBasicSyntaxNode parent = syntax.Parent; if (parent is WithStatementSyntax with && with.Expression == syntax) { return true; } break; } } return false; } bool isConditionalXMLAccessReceiverCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { if (graph.OriginalOperation.Language != LanguageNames.VisualBasic) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); VisualBasicSyntaxNode parent = syntax.Parent; if (parent is VisualBasic.Syntax.ConditionalAccessExpressionSyntax conditional && conditional.Expression == syntax && conditional.WhenNotNull.DescendantNodesAndSelf(). Any(n => n.IsKind(VisualBasic.SyntaxKind.XmlElementAccessExpression) || n.IsKind(VisualBasic.SyntaxKind.XmlDescendantAccessExpression) || n.IsKind(VisualBasic.SyntaxKind.XmlAttributeAccessExpression))) { // https://github.com/dotnet/roslyn/issues/27564: It looks like there is a bug in IOperation tree around XmlMemberAccessExpressionSyntax, // a None operation is created and all children are dropped. return true; } break; } } return false; } bool isEmptySwitchExpressionResult(IFlowCaptureReferenceOperation reference) { return reference.Syntax is CSharp.Syntax.SwitchExpressionSyntax switchExpr && switchExpr.Arms.Count == 0; } bool isSwitchTargetCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { switch (candidate.Language) { case LanguageNames.CSharp: { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)candidate.Syntax); if (syntax.Parent is CSharp.Syntax.SwitchStatementSyntax switchStmt && switchStmt.Expression == syntax) { return true; } if (syntax.Parent is CSharp.Syntax.SwitchExpressionSyntax switchExpr && switchExpr.GoverningExpression == syntax) { return true; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); if (syntax.Parent is VisualBasic.Syntax.SelectStatementSyntax switchStmt && switchStmt.Expression == syntax) { return true; } } break; } break; } } return false; } bool isForEachEnumeratorCapture(ControlFlowRegion region, BasicBlock block, CaptureId id) { foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { switch (candidate.Language) { case LanguageNames.CSharp: { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)candidate.Syntax); if (syntax.Parent is CSharp.Syntax.CommonForEachStatementSyntax forEach && forEach.Expression == syntax) { return true; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); if (syntax.Parent is VisualBasic.Syntax.ForEachStatementSyntax forEach && forEach.Expression == syntax) { return true; } } break; } break; } } return false; } bool isAggregateGroupCapture(IOperation operation, ControlFlowRegion region, BasicBlock block, CaptureId id) { if (graph.OriginalOperation.Language != LanguageNames.VisualBasic) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, block.Ordinal)) { if (candidate.Id.Equals(id)) { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)candidate.Syntax); foreach (ITranslatedQueryOperation query in operation.DescendantsAndSelf().OfType<ITranslatedQueryOperation>()) { if (query.Syntax is VisualBasic.Syntax.QueryExpressionSyntax querySyntax && querySyntax.Clauses.AsSingleton() is VisualBasic.Syntax.AggregateClauseSyntax aggregate && aggregate.AggregateKeyword.SpanStart < candidate.Syntax.SpanStart && aggregate.IntoKeyword.SpanStart > candidate.Syntax.SpanStart && query.Operation.Kind == OperationKind.AnonymousObjectCreation) { return true; } } break; } } return false; } void adjustEntryStateForDestination(ArrayBuilder<PooledHashSet<CaptureId>> entryStates, ControlFlowBranch branch, PooledHashSet<CaptureId> state) { if (branch.Destination != null) { if (branch.Destination.Ordinal > branch.Source.Ordinal) { PooledHashSet<CaptureId> entryState = adjustAndGetEntryState(entryStates, branch.Destination, state); foreach (ControlFlowRegion region in branch.LeavingRegions) { entryState.RemoveAll(region.CaptureIds); } } } else if (branch.Semantics == ControlFlowBranchSemantics.Throw || branch.Semantics == ControlFlowBranchSemantics.Rethrow || branch.Semantics == ControlFlowBranchSemantics.Error || branch.Semantics == ControlFlowBranchSemantics.StructuredExceptionHandling) { ControlFlowRegion region = branch.Source.EnclosingRegion; while (region.Kind != ControlFlowRegionKind.Root) { if (region.Kind == ControlFlowRegionKind.Try && region.EnclosingRegion.Kind == ControlFlowRegionKind.TryAndFinally) { Debug.Assert(region.EnclosingRegion.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); adjustAndGetEntryState(entryStates, blocks[region.EnclosingRegion.NestedRegions[1].FirstBlockOrdinal], state); } region = region.EnclosingRegion; } } foreach (ControlFlowRegion @finally in branch.FinallyRegions) { adjustAndGetEntryState(entryStates, blocks[@finally.FirstBlockOrdinal], state); } } PooledHashSet<CaptureId> adjustAndGetEntryState(ArrayBuilder<PooledHashSet<CaptureId>> entryStates, BasicBlock block, PooledHashSet<CaptureId> state) { PooledHashSet<CaptureId> entryState = entryStates[block.Ordinal]; if (entryState == null) { entryState = PooledHashSet<CaptureId>.GetInstance(); entryState.AddAll(state); entryStates[block.Ordinal] = entryState; } else { entryState.RemoveWhere(id => !state.Contains(id)); } return entryState; } void assertCaptureReferences( PooledHashSet<CaptureId> state, IOperation operation, BasicBlock block, int operationIndex, PooledHashSet<CaptureId> longLivedIds, PooledHashSet<CaptureId> referencedIds, Func<string> finalGraph) { foreach (IFlowCaptureReferenceOperation reference in operation.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { CaptureId id = reference.Id; referencedIds.Add(id); if (isLongLivedCaptureReference(reference, block.EnclosingRegion)) { longLivedIds.Add(id); } AssertTrueWithGraph(state.Contains(id) || isCaptureFromEnclosingGraph(id) || isEmptySwitchExpressionResult(reference), $"Operation [{operationIndex}] in [{getBlockId(block)}] uses not initialized capture [{id.Value}].", finalGraph); // Except for a few specific scenarios, any references to captures should either be long-lived capture references, // or they should come from the enclosing region. AssertTrueWithGraph(block.EnclosingRegion.CaptureIds.Contains(id) || longLivedIds.Contains(id) || ((isFirstOperandOfDynamicOrUserDefinedLogicalOperator(reference) || isIncrementedNullableForToLoopControlVariable(reference) || isConditionalAccessReceiver(reference) || isCoalesceAssignmentTarget(reference) || isObjectInitializerInitializedObjectTarget(reference)) && block.EnclosingRegion.EnclosingRegion.CaptureIds.Contains(id)), $"Operation [{operationIndex}] in [{getBlockId(block)}] uses capture [{id.Value}] from another region. Should the regions be merged?", finalGraph); } } bool isConditionalAccessReceiver(IFlowCaptureReferenceOperation reference) { SyntaxNode captureReferenceSyntax = reference.Syntax; switch (captureReferenceSyntax.Language) { case LanguageNames.CSharp: { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)captureReferenceSyntax); if (syntax.Parent is CSharp.Syntax.ConditionalAccessExpressionSyntax access && access.Expression == syntax) { return true; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)captureReferenceSyntax); if (syntax.Parent is VisualBasic.Syntax.ConditionalAccessExpressionSyntax access && access.Expression == syntax) { return true; } } break; } return false; } bool isCoalesceAssignmentTarget(IFlowCaptureReferenceOperation reference) { if (reference.Language != LanguageNames.CSharp) { return false; } CSharpSyntaxNode referenceSyntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)reference.Syntax); return referenceSyntax.Parent is AssignmentExpressionSyntax conditionalAccess && conditionalAccess.IsKind(CSharp.SyntaxKind.CoalesceAssignmentExpression) && conditionalAccess.Left == referenceSyntax; } bool isObjectInitializerInitializedObjectTarget(IFlowCaptureReferenceOperation reference) { if (reference.Language != LanguageNames.CSharp) { return false; } CSharpSyntaxNode referenceSyntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)reference.Syntax); return referenceSyntax.Parent is CSharp.Syntax.AssignmentExpressionSyntax { RawKind: (int)CSharp.SyntaxKind.SimpleAssignmentExpression, Parent: InitializerExpressionSyntax { Parent: CSharp.Syntax.ObjectCreationExpressionSyntax }, Left: var left } && left == referenceSyntax; } bool isFirstOperandOfDynamicOrUserDefinedLogicalOperator(IFlowCaptureReferenceOperation reference) { if (reference.Parent is IBinaryOperation binOp) { if (binOp.LeftOperand == reference && (binOp.OperatorKind == Operations.BinaryOperatorKind.And || binOp.OperatorKind == Operations.BinaryOperatorKind.Or) && (binOp.OperatorMethod != null || (ITypeSymbolHelpers.IsDynamicType(binOp.Type) && (ITypeSymbolHelpers.IsDynamicType(binOp.LeftOperand.Type) || ITypeSymbolHelpers.IsDynamicType(binOp.RightOperand.Type))))) { if (reference.Language == LanguageNames.CSharp) { if (binOp.Syntax is CSharp.Syntax.BinaryExpressionSyntax binOpSyntax && (binOpSyntax.Kind() == CSharp.SyntaxKind.LogicalAndExpression || binOpSyntax.Kind() == CSharp.SyntaxKind.LogicalOrExpression) && binOpSyntax.Left == applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)reference.Syntax) && binOpSyntax.Right == applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)binOp.RightOperand.Syntax)) { return true; } } else if (reference.Language == LanguageNames.VisualBasic) { var referenceSyntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)reference.Syntax); if (binOp.Syntax is VisualBasic.Syntax.BinaryExpressionSyntax binOpSyntax && (binOpSyntax.Kind() == VisualBasic.SyntaxKind.AndAlsoExpression || binOpSyntax.Kind() == VisualBasic.SyntaxKind.OrElseExpression) && binOpSyntax.Left == referenceSyntax && binOpSyntax.Right == applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)binOp.RightOperand.Syntax)) { return true; } else if (binOp.Syntax is VisualBasic.Syntax.RangeCaseClauseSyntax range && binOp.OperatorKind == Operations.BinaryOperatorKind.And && range.LowerBound == referenceSyntax && range.UpperBound == applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)binOp.RightOperand.Syntax)) { return true; } else if (binOp.Syntax is VisualBasic.Syntax.CaseStatementSyntax caseStmt && binOp.OperatorKind == Operations.BinaryOperatorKind.Or && caseStmt.Cases.Count > 1 && (caseStmt == referenceSyntax || caseStmt.Cases.Contains(referenceSyntax as CaseClauseSyntax)) && caseStmt.Cases.Contains(applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)binOp.RightOperand.Syntax) as CaseClauseSyntax)) { return true; } } } } return false; } bool isIncrementedNullableForToLoopControlVariable(IFlowCaptureReferenceOperation reference) { if (reference.Parent is ISimpleAssignmentOperation assignment && assignment.IsImplicit && assignment.Target == reference && ITypeSymbolHelpers.IsNullableType(reference.Type) && assignment.Syntax.Parent is VisualBasic.Syntax.ForStatementSyntax forStmt && assignment.Syntax == forStmt.ControlVariable && reference.Syntax == assignment.Syntax && assignment.Value.Syntax == forStmt.StepClause.StepValue) { return true; } return false; } bool isLongLivedCaptureReference(IFlowCaptureReferenceOperation reference, ControlFlowRegion region) { if (isLongLivedCaptureReferenceSyntax(reference.Syntax)) { return true; } return isCaptureFromEnclosingGraph(reference.Id); } bool isCaptureFromEnclosingGraph(CaptureId id) { ControlFlowRegion region = graph.Root.EnclosingRegion; while (region != null) { if (region.CaptureIds.Contains(id)) { return true; } region = region.EnclosingRegion; } return false; } bool isConditionalAccessCaptureUsedAfterNullCheck(IOperation operation, ControlFlowRegion region, BasicBlock block, CaptureId id) { SyntaxNode whenNotNull = null; if (operation.Parent == null && operation is IsNullOperation isNull && isNull.Operand.Kind == OperationKind.FlowCaptureReference) { switch (isNull.Operand.Language) { case LanguageNames.CSharp: { CSharpSyntaxNode syntax = applyParenthesizedOrNullSuppressionIfAnyCS((CSharpSyntaxNode)isNull.Operand.Syntax); if (syntax.Parent is CSharp.Syntax.ConditionalAccessExpressionSyntax access && access.Expression == syntax) { whenNotNull = access.WhenNotNull; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)isNull.Operand.Syntax); if (syntax.Parent is VisualBasic.Syntax.ConditionalAccessExpressionSyntax access && access.Expression == syntax) { whenNotNull = access.WhenNotNull; } } break; } } if (whenNotNull == null) { return false; } foreach (IFlowCaptureOperation candidate in getFlowCaptureOperationsFromBlocksInRegion(region, region.LastBlockOrdinal)) { if (candidate.Id.Equals(id)) { if (whenNotNull.Contains(candidate.Syntax)) { return true; } break; } } return false; } bool isLongLivedCaptureReferenceSyntax(SyntaxNode captureReferenceSyntax) { switch (captureReferenceSyntax.Language) { case LanguageNames.CSharp: { var syntax = (CSharpSyntaxNode)captureReferenceSyntax; switch (syntax.Kind()) { case CSharp.SyntaxKind.ObjectCreationExpression: case CSharp.SyntaxKind.ImplicitObjectCreationExpression: if (((CSharp.Syntax.BaseObjectCreationExpressionSyntax)syntax).Initializer?.Expressions.Any() == true) { return true; } break; } if (syntax.Parent is CSharp.Syntax.WithExpressionSyntax withExpr && withExpr.Initializer.Expressions.Any() && withExpr.Expression == (object)syntax) { return true; } syntax = applyParenthesizedOrNullSuppressionIfAnyCS(syntax); if (syntax.Parent?.Parent is CSharp.Syntax.UsingStatementSyntax usingStmt && usingStmt.Declaration == syntax.Parent) { return true; } CSharpSyntaxNode parent = syntax.Parent; switch (parent?.Kind()) { case CSharp.SyntaxKind.ForEachStatement: case CSharp.SyntaxKind.ForEachVariableStatement: if (((CommonForEachStatementSyntax)parent).Expression == syntax) { return true; } break; case CSharp.SyntaxKind.Argument: if ((parent = parent.Parent)?.Kind() == CSharp.SyntaxKind.BracketedArgumentList && (parent = parent.Parent)?.Kind() == CSharp.SyntaxKind.ImplicitElementAccess && parent.Parent is AssignmentExpressionSyntax assignment && assignment.Kind() == CSharp.SyntaxKind.SimpleAssignmentExpression && assignment.Left == parent && assignment.Parent?.Kind() == CSharp.SyntaxKind.ObjectInitializerExpression && (assignment.Right.Kind() == CSharp.SyntaxKind.CollectionInitializerExpression || assignment.Right.Kind() == CSharp.SyntaxKind.ObjectInitializerExpression)) { return true; } break; case CSharp.SyntaxKind.LockStatement: if (((LockStatementSyntax)syntax.Parent).Expression == syntax) { return true; } break; case CSharp.SyntaxKind.UsingStatement: if (((CSharp.Syntax.UsingStatementSyntax)syntax.Parent).Expression == syntax) { return true; } break; case CSharp.SyntaxKind.SwitchStatement: if (((CSharp.Syntax.SwitchStatementSyntax)syntax.Parent).Expression == syntax) { return true; } break; case CSharp.SyntaxKind.SwitchExpression: if (((CSharp.Syntax.SwitchExpressionSyntax)syntax.Parent).GoverningExpression == syntax) { return true; } break; case CSharp.SyntaxKind.CoalesceAssignmentExpression: if (((AssignmentExpressionSyntax)syntax.Parent).Left == syntax) { return true; } break; } } break; case LanguageNames.VisualBasic: { VisualBasicSyntaxNode syntax = applyParenthesizedIfAnyVB((VisualBasicSyntaxNode)captureReferenceSyntax); switch (syntax.Kind()) { case VisualBasic.SyntaxKind.ForStatement: case VisualBasic.SyntaxKind.ForBlock: return true; case VisualBasic.SyntaxKind.ObjectCreationExpression: var objCreation = (VisualBasic.Syntax.ObjectCreationExpressionSyntax)syntax; if ((objCreation.Initializer is VisualBasic.Syntax.ObjectMemberInitializerSyntax memberInit && memberInit.Initializers.Any()) || (objCreation.Initializer is VisualBasic.Syntax.ObjectCollectionInitializerSyntax collectionInit && collectionInit.Initializer.Initializers.Any())) { return true; } break; } VisualBasicSyntaxNode parent = syntax.Parent; switch (parent?.Kind()) { case VisualBasic.SyntaxKind.ForEachStatement: if (((VisualBasic.Syntax.ForEachStatementSyntax)parent).Expression == syntax) { return true; } break; case VisualBasic.SyntaxKind.ForStatement: if (((VisualBasic.Syntax.ForStatementSyntax)parent).ToValue == syntax) { return true; } break; case VisualBasic.SyntaxKind.ForStepClause: if (((ForStepClauseSyntax)parent).StepValue == syntax) { return true; } break; case VisualBasic.SyntaxKind.SyncLockStatement: if (((VisualBasic.Syntax.SyncLockStatementSyntax)parent).Expression == syntax) { return true; } break; case VisualBasic.SyntaxKind.UsingStatement: if (((VisualBasic.Syntax.UsingStatementSyntax)parent).Expression == syntax) { return true; } break; case VisualBasic.SyntaxKind.WithStatement: if (((VisualBasic.Syntax.WithStatementSyntax)parent).Expression == syntax) { return true; } break; case VisualBasic.SyntaxKind.SelectStatement: if (((VisualBasic.Syntax.SelectStatementSyntax)parent).Expression == syntax) { return true; } break; } } break; } return false; } CSharpSyntaxNode applyParenthesizedOrNullSuppressionIfAnyCS(CSharpSyntaxNode syntax) { while (syntax.Parent is CSharp.Syntax.ParenthesizedExpressionSyntax or PostfixUnaryExpressionSyntax { OperatorToken: { RawKind: (int)CSharp.SyntaxKind.ExclamationToken } }) { syntax = syntax.Parent; } return syntax; } VisualBasicSyntaxNode applyParenthesizedIfAnyVB(VisualBasicSyntaxNode syntax) { while (syntax.Parent?.Kind() == VisualBasic.SyntaxKind.ParenthesizedExpression) { syntax = syntax.Parent; } return syntax; } IEnumerable<IFlowCaptureOperation> getFlowCaptureOperationsFromBlocksInRegion(ControlFlowRegion region, int lastBlockOrdinal) { Debug.Assert(lastBlockOrdinal <= region.LastBlockOrdinal); for (int i = lastBlockOrdinal; i >= region.FirstBlockOrdinal; i--) { for (var j = blocks[i].Operations.Length - 1; j >= 0; j--) { if (blocks[i].Operations[j] is IFlowCaptureOperation capture) { yield return capture; } } } } IEnumerable<IFlowCaptureReferenceOperation> getFlowCaptureReferenceOperationsInRegion(ControlFlowRegion region, int firstBlockOrdinal) { Debug.Assert(firstBlockOrdinal >= region.FirstBlockOrdinal); for (int i = firstBlockOrdinal; i <= region.LastBlockOrdinal; i++) { BasicBlock block = blocks[i]; foreach (IOperation operation in block.Operations) { foreach (IFlowCaptureReferenceOperation reference in operation.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { yield return reference; } } if (block.BranchValue != null) { foreach (IFlowCaptureReferenceOperation reference in block.BranchValue.DescendantsAndSelf().OfType<IFlowCaptureReferenceOperation>()) { yield return reference; } } } } string getDestinationString(ref ControlFlowBranch branch) { return branch.Destination != null ? getBlockId(branch.Destination) : "null"; } PooledObjects.PooledDictionary<ControlFlowRegion, int> buildRegionMap() { var result = PooledObjects.PooledDictionary<ControlFlowRegion, int>.GetInstance(); int ordinal = 0; visit(graph.Root); void visit(ControlFlowRegion region) { result.Add(region, ordinal++); foreach (ControlFlowRegion r in region.NestedRegions) { visit(r); } } return result; } void appendLine(string line) { appendIndent(); stringBuilder.AppendLine(line); } void appendIndent() { stringBuilder.Append(' ', indent); } void printLocals(ControlFlowRegion region) { if (!region.Locals.IsEmpty) { appendIndent(); stringBuilder.Append("Locals:"); foreach (ILocalSymbol local in region.Locals) { stringBuilder.Append($" [{local.ToTestDisplayString()}]"); } stringBuilder.AppendLine(); } if (!region.LocalFunctions.IsEmpty) { appendIndent(); stringBuilder.Append("Methods:"); foreach (IMethodSymbol method in region.LocalFunctions) { stringBuilder.Append($" [{method.ToTestDisplayString()}]"); } stringBuilder.AppendLine(); } if (!region.CaptureIds.IsEmpty) { appendIndent(); stringBuilder.Append("CaptureIds:"); foreach (CaptureId id in region.CaptureIds) { stringBuilder.Append($" [{id.Value}]"); } stringBuilder.AppendLine(); } } void enterRegions(ControlFlowRegion region, int firstBlockOrdinal) { if (region.FirstBlockOrdinal != firstBlockOrdinal) { Assert.Same(currentRegion, region); if (lastPrintedBlockIsInCurrentRegion) { stringBuilder.AppendLine(); } return; } enterRegions(region.EnclosingRegion, firstBlockOrdinal); currentRegion = region; lastPrintedBlockIsInCurrentRegion = true; switch (region.Kind) { case ControlFlowRegionKind.Filter: Assert.Empty(region.Locals); Assert.Empty(region.LocalFunctions); Assert.Equal(firstBlockOrdinal, region.EnclosingRegion.FirstBlockOrdinal); Assert.Same(region.ExceptionType, region.EnclosingRegion.ExceptionType); enterRegion($".filter {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.Try: Assert.Null(region.ExceptionType); Assert.Equal(firstBlockOrdinal, region.EnclosingRegion.FirstBlockOrdinal); enterRegion($".try {{{getRegionId(region.EnclosingRegion)}, {getRegionId(region)}}}"); break; case ControlFlowRegionKind.FilterAndHandler: enterRegion($".catch {{{getRegionId(region)}}} ({region.ExceptionType?.ToTestDisplayString() ?? "null"})"); break; case ControlFlowRegionKind.Finally: Assert.Null(region.ExceptionType); enterRegion($".finally {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.Catch: switch (region.EnclosingRegion.Kind) { case ControlFlowRegionKind.FilterAndHandler: Assert.Same(region.ExceptionType, region.EnclosingRegion.ExceptionType); enterRegion($".handler {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.TryAndCatch: enterRegion($".catch {{{getRegionId(region)}}} ({region.ExceptionType?.ToTestDisplayString() ?? "null"})"); break; default: Assert.False(true, $"Unexpected region kind {region.EnclosingRegion.Kind}"); break; } break; case ControlFlowRegionKind.LocalLifetime: Assert.Null(region.ExceptionType); Assert.False(region.Locals.IsEmpty && region.LocalFunctions.IsEmpty && region.CaptureIds.IsEmpty); enterRegion($".locals {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.TryAndCatch: case ControlFlowRegionKind.TryAndFinally: Assert.Empty(region.Locals); Assert.Empty(region.LocalFunctions); Assert.Empty(region.CaptureIds); Assert.Null(region.ExceptionType); break; case ControlFlowRegionKind.StaticLocalInitializer: Assert.Null(region.ExceptionType); Assert.Empty(region.Locals); enterRegion($".static initializer {{{getRegionId(region)}}}"); break; case ControlFlowRegionKind.ErroneousBody: Assert.Null(region.ExceptionType); enterRegion($".erroneous body {{{getRegionId(region)}}}"); break; default: Assert.False(true, $"Unexpected region kind {region.Kind}"); break; } void enterRegion(string header) { appendLine(header); appendLine("{"); indent += 4; printLocals(region); } } void leaveRegions(ControlFlowRegion region, int lastBlockOrdinal) { if (region.LastBlockOrdinal != lastBlockOrdinal) { currentRegion = region; lastPrintedBlockIsInCurrentRegion = false; return; } string regionId = getRegionId(region); for (var i = 0; i < region.LocalFunctions.Length; i++) { var method = region.LocalFunctions[i]; appendLine(""); appendLine("{ " + method.ToTestDisplayString()); appendLine(""); var g = graph.GetLocalFunctionControlFlowGraph(method); localFunctionsMap.Add(method, g); Assert.Equal(OperationKind.LocalFunction, g.OriginalOperation.Kind); GetFlowGraph(stringBuilder, compilation, g, region, $"#{i}{regionId}", indent + 4, associatedSymbol); appendLine("}"); } switch (region.Kind) { case ControlFlowRegionKind.LocalLifetime: case ControlFlowRegionKind.Filter: case ControlFlowRegionKind.Try: case ControlFlowRegionKind.Finally: case ControlFlowRegionKind.FilterAndHandler: case ControlFlowRegionKind.StaticLocalInitializer: case ControlFlowRegionKind.ErroneousBody: indent -= 4; appendLine("}"); break; case ControlFlowRegionKind.Catch: switch (region.EnclosingRegion.Kind) { case ControlFlowRegionKind.FilterAndHandler: case ControlFlowRegionKind.TryAndCatch: goto endRegion; default: Assert.False(true, $"Unexpected region kind {region.EnclosingRegion.Kind}"); break; } break; endRegion: goto case ControlFlowRegionKind.Filter; case ControlFlowRegionKind.TryAndCatch: case ControlFlowRegionKind.TryAndFinally: break; default: Assert.False(true, $"Unexpected region kind {region.Kind}"); break; } leaveRegions(region.EnclosingRegion, lastBlockOrdinal); } void validateBranch(BasicBlock fromBlock, ControlFlowBranch branch) { if (branch.Destination == null) { Assert.Empty(branch.FinallyRegions); Assert.Empty(branch.LeavingRegions); Assert.Empty(branch.EnteringRegions); Assert.True(ControlFlowBranchSemantics.None == branch.Semantics || ControlFlowBranchSemantics.Throw == branch.Semantics || ControlFlowBranchSemantics.Rethrow == branch.Semantics || ControlFlowBranchSemantics.StructuredExceptionHandling == branch.Semantics || ControlFlowBranchSemantics.ProgramTermination == branch.Semantics || ControlFlowBranchSemantics.Error == branch.Semantics); return; } Assert.True(ControlFlowBranchSemantics.Regular == branch.Semantics || ControlFlowBranchSemantics.Return == branch.Semantics); Assert.True(branch.Destination.Predecessors.Contains(p => p.Source == fromBlock)); if (!branch.FinallyRegions.IsEmpty) { appendLine($" Finalizing:" + buildList(branch.FinallyRegions)); } ControlFlowRegion remainedIn1 = fromBlock.EnclosingRegion; if (!branch.LeavingRegions.IsEmpty) { appendLine($" Leaving:" + buildList(branch.LeavingRegions)); foreach (ControlFlowRegion r in branch.LeavingRegions) { Assert.Same(remainedIn1, r); remainedIn1 = r.EnclosingRegion; } } ControlFlowRegion remainedIn2 = branch.Destination.EnclosingRegion; if (!branch.EnteringRegions.IsEmpty) { appendLine($" Entering:" + buildList(branch.EnteringRegions)); for (int j = branch.EnteringRegions.Length - 1; j >= 0; j--) { ControlFlowRegion r = branch.EnteringRegions[j]; Assert.Same(remainedIn2, r); remainedIn2 = r.EnclosingRegion; } } Assert.Same(remainedIn1.EnclosingRegion, remainedIn2.EnclosingRegion); string buildList(ImmutableArray<ControlFlowRegion> list) { var builder = PooledObjects.PooledStringBuilder.GetInstance(); foreach (ControlFlowRegion r in list) { builder.Builder.Append($" {{{getRegionId(r)}}}"); } return builder.ToStringAndFree(); } } void validateRoot(IOperation root) { visitor.Visit(root); Assert.Null(root.Parent); Assert.Null(((Operation)root).OwningSemanticModel); Assert.Null(root.SemanticModel); Assert.True(CanBeInControlFlowGraph(root), $"Unexpected node kind OperationKind.{root.Kind}"); foreach (var operation in root.Descendants()) { visitor.Visit(operation); Assert.NotNull(operation.Parent); Assert.Null(((Operation)operation).OwningSemanticModel); Assert.Null(operation.SemanticModel); Assert.True(CanBeInControlFlowGraph(operation), $"Unexpected node kind OperationKind.{operation.Kind}"); } } void validateLifetimeOfReferences(BasicBlock block, Func<string> finalGraph) { referencedCaptureIds.Clear(); referencedLocalsAndMethods.Clear(); foreach (IOperation operation in block.Operations) { recordReferences(operation); } if (block.BranchValue != null) { recordReferences(block.BranchValue); } ControlFlowRegion region = block.EnclosingRegion; while ((referencedCaptureIds.Count != 0 || referencedLocalsAndMethods.Count != 0) && region != null) { foreach (ILocalSymbol l in region.Locals) { referencedLocalsAndMethods.Remove(l); } foreach (IMethodSymbol m in region.LocalFunctions) { referencedLocalsAndMethods.Remove(m); } foreach (CaptureId id in region.CaptureIds) { referencedCaptureIds.Remove(id); } region = region.EnclosingRegion; } if (referencedLocalsAndMethods.Count != 0) { ISymbol symbol = referencedLocalsAndMethods.First(); Assert.True(false, $"{(symbol.Kind == SymbolKind.Local ? "Local" : "Method")} without owning region {symbol.ToTestDisplayString()} in [{getBlockId(block)}]\n{finalGraph()}"); } if (referencedCaptureIds.Count != 0) { Assert.True(false, $"Capture [{referencedCaptureIds.First().Value}] without owning region in [{getBlockId(block)}]\n{finalGraph()}"); } } void recordReferences(IOperation operation) { foreach (IOperation node in operation.DescendantsAndSelf()) { IMethodSymbol method; switch (node) { case ILocalReferenceOperation localReference: if (localReference.Local.ContainingSymbol.IsTopLevelMainMethod() && !isInAssociatedSymbol(localReference.Local.ContainingSymbol, associatedSymbol)) { // Top-level locals can be referenced from locations in the same file that are not actually the top // level main. For these cases, we want to treat them like fields for the purposes of references, // as they are not declared in this method and have no owning region break; } referencedLocalsAndMethods.Add(localReference.Local); break; case IMethodReferenceOperation methodReference: method = methodReference.Method; if (method.MethodKind == MethodKind.LocalFunction) { if (method.ContainingSymbol.IsTopLevelMainMethod() && !isInAssociatedSymbol(method.ContainingSymbol, associatedSymbol)) { // Top-level local functions can be referenced from locations in the same file that are not actually the top // level main. For these cases, we want to treat them like class methods for the purposes of references, // as they are not declared in this method and have no owning region break; } referencedLocalsAndMethods.Add(method.OriginalDefinition); } break; case IInvocationOperation invocation: method = invocation.TargetMethod; if (method.MethodKind == MethodKind.LocalFunction) { if (method.ContainingSymbol.IsTopLevelMainMethod() && !associatedSymbol.IsTopLevelMainMethod()) { // Top-level local functions can be referenced from locations in the same file that are not actually the top // level main. For these cases, we want to treat them like class methods for the purposes of references, // as they are not declared in this method and have no owning region break; } referencedLocalsAndMethods.Add(method.OriginalDefinition); } break; case IFlowCaptureOperation flowCapture: referencedCaptureIds.Add(flowCapture.Id); break; case IFlowCaptureReferenceOperation flowCaptureReference: referencedCaptureIds.Add(flowCaptureReference.Id); break; } } static bool isInAssociatedSymbol(ISymbol symbol, ISymbol associatedSymbol) { while (symbol is IMethodSymbol m) { if ((object)m == associatedSymbol) { return true; } symbol = m.ContainingSymbol; } return false; } } string getBlockId(BasicBlock block) { return $"B{block.Ordinal}{idSuffix}"; } string getRegionId(ControlFlowRegion region) { return $"R{regionMap[region]}{idSuffix}"; } string getOperationTree(IOperation operation) { var walker = new OperationTreeSerializer(graph, currentRegion, idSuffix, anonymousFunctionsMap, compilation, operation, initialIndent: 8 + indent, associatedSymbol); walker.Visit(operation); return walker.Builder.ToString(); } } private static void AssertTrueWithGraph([DoesNotReturnIf(false)] bool value, string message, Func<string> finalGraph) { if (!value) { Assert.True(value, $"{message}\n{finalGraph()}"); } } private sealed class OperationTreeSerializer : OperationTreeVerifier { private readonly ControlFlowGraph _graph; private readonly ControlFlowRegion _region; private readonly string _idSuffix; private readonly Dictionary<IFlowAnonymousFunctionOperation, ControlFlowGraph> _anonymousFunctionsMap; private readonly ISymbol _associatedSymbol; public OperationTreeSerializer(ControlFlowGraph graph, ControlFlowRegion region, string idSuffix, Dictionary<IFlowAnonymousFunctionOperation, ControlFlowGraph> anonymousFunctionsMap, Compilation compilation, IOperation root, int initialIndent, ISymbol associatedSymbol) : base(compilation, root, initialIndent) { _graph = graph; _region = region; _idSuffix = idSuffix; _anonymousFunctionsMap = anonymousFunctionsMap; _associatedSymbol = associatedSymbol; } public System.Text.StringBuilder Builder => _builder; public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { base.VisitFlowAnonymousFunction(operation); LogString("{"); LogNewLine(); var g = _graph.GetAnonymousFunctionControlFlowGraph(operation); int id = _anonymousFunctionsMap.Count; _anonymousFunctionsMap.Add(operation, g); Assert.Equal(OperationKind.AnonymousFunction, g.OriginalOperation.Kind); GetFlowGraph(_builder, _compilation, g, _region, $"#A{id}{_idSuffix}", _currentIndent.Length + 4, _associatedSymbol); LogString("}"); LogNewLine(); } } private static bool CanBeInControlFlowGraph(IOperation n) { switch (n.Kind) { case OperationKind.Block: case OperationKind.Switch: case OperationKind.Loop: case OperationKind.Branch: case OperationKind.Lock: case OperationKind.Try: case OperationKind.Using: case OperationKind.Conditional: case OperationKind.Coalesce: case OperationKind.ConditionalAccess: case OperationKind.ConditionalAccessInstance: case OperationKind.MemberInitializer: case OperationKind.FieldInitializer: case OperationKind.PropertyInitializer: case OperationKind.ParameterInitializer: case OperationKind.CatchClause: case OperationKind.SwitchCase: case OperationKind.CaseClause: case OperationKind.VariableDeclarationGroup: case OperationKind.VariableDeclaration: case OperationKind.VariableDeclarator: case OperationKind.VariableInitializer: case OperationKind.Return: case OperationKind.YieldBreak: case OperationKind.Labeled: case OperationKind.Throw: case OperationKind.End: case OperationKind.Empty: case OperationKind.NameOf: case OperationKind.AnonymousFunction: case OperationKind.ObjectOrCollectionInitializer: case OperationKind.LocalFunction: case OperationKind.CoalesceAssignment: case OperationKind.SwitchExpression: case OperationKind.SwitchExpressionArm: return false; case OperationKind.Binary: var binary = (IBinaryOperation)n; return (binary.OperatorKind != Operations.BinaryOperatorKind.ConditionalAnd && binary.OperatorKind != Operations.BinaryOperatorKind.ConditionalOr) || (binary.OperatorMethod == null && !ITypeSymbolHelpers.IsBooleanType(binary.Type) && !ITypeSymbolHelpers.IsNullableOfBoolean(binary.Type) && !ITypeSymbolHelpers.IsObjectType(binary.Type) && !ITypeSymbolHelpers.IsDynamicType(binary.Type)); case OperationKind.InstanceReference: // Implicit instance receivers, except for anonymous type creations, are expected to have been removed when dealing with creations. var instanceReference = (IInstanceReferenceOperation)n; return instanceReference.ReferenceKind == InstanceReferenceKind.ContainingTypeInstance || instanceReference.ReferenceKind == InstanceReferenceKind.PatternInput || // Will be removed when CFG support for interpolated string handlers is implemented, tracked by // https://github.com/dotnet/roslyn/issues/54718 instanceReference.ReferenceKind == InstanceReferenceKind.InterpolatedStringHandler || (instanceReference.ReferenceKind == InstanceReferenceKind.ImplicitReceiver && n.Type.IsAnonymousType && n.Parent is IPropertyReferenceOperation propertyReference && propertyReference.Instance == n && propertyReference.Parent is ISimpleAssignmentOperation simpleAssignment && simpleAssignment.Target == propertyReference && simpleAssignment.Parent.Kind == OperationKind.AnonymousObjectCreation); case OperationKind.None: return !(n is IPlaceholderOperation); case OperationKind.Invalid: case OperationKind.YieldReturn: case OperationKind.ExpressionStatement: case OperationKind.Stop: case OperationKind.RaiseEvent: case OperationKind.Literal: case OperationKind.Conversion: case OperationKind.Invocation: case OperationKind.ArrayElementReference: case OperationKind.LocalReference: case OperationKind.ParameterReference: case OperationKind.FieldReference: case OperationKind.MethodReference: case OperationKind.PropertyReference: case OperationKind.EventReference: case OperationKind.FlowAnonymousFunction: case OperationKind.ObjectCreation: case OperationKind.TypeParameterObjectCreation: case OperationKind.ArrayCreation: case OperationKind.ArrayInitializer: case OperationKind.IsType: case OperationKind.Await: case OperationKind.SimpleAssignment: case OperationKind.CompoundAssignment: case OperationKind.Parenthesized: case OperationKind.EventAssignment: case OperationKind.InterpolatedString: case OperationKind.AnonymousObjectCreation: case OperationKind.Tuple: case OperationKind.TupleBinary: case OperationKind.DynamicObjectCreation: case OperationKind.DynamicMemberReference: case OperationKind.DynamicInvocation: case OperationKind.DynamicIndexerAccess: case OperationKind.TranslatedQuery: case OperationKind.DelegateCreation: case OperationKind.DefaultValue: case OperationKind.TypeOf: case OperationKind.SizeOf: case OperationKind.AddressOf: case OperationKind.IsPattern: case OperationKind.Increment: case OperationKind.Decrement: case OperationKind.DeconstructionAssignment: case OperationKind.DeclarationExpression: case OperationKind.OmittedArgument: case OperationKind.Argument: case OperationKind.InterpolatedStringText: case OperationKind.Interpolation: case OperationKind.ConstantPattern: case OperationKind.DeclarationPattern: case OperationKind.Unary: case OperationKind.FlowCapture: case OperationKind.FlowCaptureReference: case OperationKind.IsNull: case OperationKind.CaughtException: case OperationKind.StaticLocalInitializationSemaphore: case OperationKind.Discard: case OperationKind.ReDim: case OperationKind.ReDimClause: case OperationKind.Range: case OperationKind.RecursivePattern: case OperationKind.DiscardPattern: case OperationKind.PropertySubpattern: case OperationKind.RelationalPattern: case OperationKind.NegatedPattern: case OperationKind.BinaryPattern: case OperationKind.TypePattern: case OperationKind.InterpolatedStringAppendFormatted: case OperationKind.InterpolatedStringAppendLiteral: case OperationKind.InterpolatedStringAppendInvalid: return true; } Assert.True(false, $"Unhandled node kind OperationKind.{n.Kind}"); return false; } #nullable enable private static bool IsTopLevelMainMethod([NotNullWhen(true)] this ISymbol? symbol) { return symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType: INamedTypeSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, ContainingType: null, ContainingNamespace: { IsGlobalNamespace: true } } }; } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Test/Core/Compilation/OperationTreeVerifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public class OperationTreeVerifier : OperationWalker { protected readonly Compilation _compilation; protected readonly IOperation _root; protected readonly StringBuilder _builder; private readonly Dictionary<SyntaxNode, IOperation> _explicitNodeMap; private readonly Dictionary<ILabelSymbol, uint> _labelIdMap; private const string indent = " "; protected string _currentIndent; private bool _pendingIndent; private uint _currentLabelId = 0; public OperationTreeVerifier(Compilation compilation, IOperation root, int initialIndent) { _compilation = compilation; _root = root; _builder = new StringBuilder(); _currentIndent = new string(' ', initialIndent); _pendingIndent = true; _explicitNodeMap = new Dictionary<SyntaxNode, IOperation>(); _labelIdMap = new Dictionary<ILabelSymbol, uint>(); } public static string GetOperationTree(Compilation compilation, IOperation operation, int initialIndent = 0) { var walker = new OperationTreeVerifier(compilation, operation, initialIndent); walker.Visit(operation); return walker._builder.ToString(); } public static void Verify(string expectedOperationTree, string actualOperationTree) { char[] newLineChars = Environment.NewLine.ToCharArray(); string actual = actualOperationTree.Trim(newLineChars); actual = actual.Replace(" \n", "\n").Replace(" \r", "\r"); expectedOperationTree = expectedOperationTree.Trim(newLineChars); expectedOperationTree = expectedOperationTree.Replace("\r\n", "\n").Replace(" \n", "\n").Replace("\n", Environment.NewLine); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedOperationTree, actual); } #region Logging helpers private void LogPatternPropertiesAndNewLine(IPatternOperation operation) { LogPatternProperties(operation); LogString(")"); LogNewLine(); } private void LogPatternProperties(IPatternOperation operation) { LogCommonProperties(operation); LogString(" ("); LogType(operation.InputType, $"{nameof(operation.InputType)}"); LogString(", "); LogType(operation.NarrowedType, $"{nameof(operation.NarrowedType)}"); } private void LogCommonPropertiesAndNewLine(IOperation operation) { LogCommonProperties(operation); LogNewLine(); } private void LogCommonProperties(IOperation operation) { LogString(" ("); // Kind LogString($"{nameof(OperationKind)}.{GetKindText(operation.Kind)}"); // Type LogString(", "); LogType(operation.Type); // ConstantValue if (operation.ConstantValue.HasValue) { LogString(", "); LogConstant(operation.ConstantValue); } // IsInvalid if (operation.HasErrors(_compilation)) { LogString(", IsInvalid"); } // IsImplicit if (operation.IsImplicit) { LogString(", IsImplicit"); } LogString(")"); // Syntax Assert.NotNull(operation.Syntax); LogString($" (Syntax: {GetSnippetFromSyntax(operation.Syntax)})"); // Some of these kinds were inconsistent in the first release, and in standardizing them the // string output isn't guaranteed to be one or the other. So standardize manually. string GetKindText(OperationKind kind) { switch (kind) { case OperationKind.Unary: return "Unary"; case OperationKind.Binary: return "Binary"; case OperationKind.TupleBinary: return "TupleBinary"; case OperationKind.MethodBody: return "MethodBody"; case OperationKind.ConstructorBody: return "ConstructorBody"; default: return kind.ToString(); } } } private static string GetSnippetFromSyntax(SyntaxNode syntax) { if (syntax == null) { return "null"; } var text = syntax.ToString().Trim(Environment.NewLine.ToCharArray()); var lines = text.Split(new[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).ToArray(); if (lines.Length <= 1 && text.Length < 25) { return $"'{text}'"; } const int maxTokenLength = 11; var firstLine = lines[0]; var lastLine = lines[lines.Length - 1]; var prefix = firstLine.Length <= maxTokenLength ? firstLine : firstLine.Substring(0, maxTokenLength); var suffix = lastLine.Length <= maxTokenLength ? lastLine : lastLine.Substring(lastLine.Length - maxTokenLength, maxTokenLength); return $"'{prefix} ... {suffix}'"; } private static bool ShouldLogType(IOperation operation) { var operationKind = (int)operation.Kind; // Expressions if (operationKind >= 0x100 && operationKind < 0x400) { return true; } return false; } protected void LogString(string str) { if (_pendingIndent) { str = _currentIndent + str; _pendingIndent = false; } _builder.Append(str); } protected void LogNewLine() { LogString(Environment.NewLine); _pendingIndent = true; } private void Indent() { _currentIndent += indent; } private void Unindent() { _currentIndent = _currentIndent.Substring(indent.Length); } private void LogConstant(Optional<object> constant, string header = "Constant") { if (constant.HasValue) { LogConstant(constant.Value, header); } } private static string ConstantToString(object constant) { switch (constant) { case null: return "null"; case string s: s = s.Replace("\"", "\"\""); return @"""" + s + @""""; case IFormattable formattable: return formattable.ToString(null, CultureInfo.InvariantCulture).Replace("\"", "\"\""); default: return constant.ToString().Replace("\"", "\"\""); } } private void LogConstant(object constant, string header = "Constant") { string valueStr = ConstantToString(constant); LogString($"{header}: {valueStr}"); } private void LogConversion(CommonConversion conversion, string header = "Conversion") { var exists = FormatBoolProperty(nameof(conversion.Exists), conversion.Exists); var isIdentity = FormatBoolProperty(nameof(conversion.IsIdentity), conversion.IsIdentity); var isNumeric = FormatBoolProperty(nameof(conversion.IsNumeric), conversion.IsNumeric); var isReference = FormatBoolProperty(nameof(conversion.IsReference), conversion.IsReference); var isUserDefined = FormatBoolProperty(nameof(conversion.IsUserDefined), conversion.IsUserDefined); LogString($"{header}: {nameof(CommonConversion)} ({exists}, {isIdentity}, {isNumeric}, {isReference}, {isUserDefined}) ("); LogSymbol(conversion.MethodSymbol, nameof(conversion.MethodSymbol)); LogString(")"); } private void LogSymbol(ISymbol symbol, string header, bool logDisplayString = true) { if (!string.IsNullOrEmpty(header)) { LogString($"{header}: "); } var symbolStr = symbol != null ? (logDisplayString ? symbol.ToTestDisplayString() : symbol.Name) : "null"; LogString($"{symbolStr}"); } private void LogType(ITypeSymbol type, string header = "Type") { var typeStr = type != null ? type.ToTestDisplayString() : "null"; LogString($"{header}: {typeStr}"); } private uint GetLabelId(ILabelSymbol symbol) { if (_labelIdMap.ContainsKey(symbol)) { return _labelIdMap[symbol]; } var id = _currentLabelId++; _labelIdMap[symbol] = id; return id; } private static string FormatBoolProperty(string propertyName, bool value) => $"{propertyName}: {(value ? "True" : "False")}"; #endregion #region Visit methods public override void Visit(IOperation operation) { if (operation == null) { Indent(); LogString("null"); LogNewLine(); Unindent(); return; } if (!operation.IsImplicit) { try { _explicitNodeMap.Add(operation.Syntax, operation); } catch (ArgumentException) { Assert.False(true, $"Duplicate explicit node for syntax ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}"); } } Assert.True(operation.Type == null || !operation.MustHaveNullType(), $"Unexpected non-null type: {operation.Type}"); if (operation != _root) { Indent(); } base.Visit(operation); if (operation != _root) { Unindent(); } Assert.True(operation.Syntax.Language == operation.Language); } private void Visit(IOperation operation, string header) { Debug.Assert(!string.IsNullOrEmpty(header)); Indent(); LogString($"{header}: "); LogNewLine(); Visit(operation); Unindent(); } private void VisitArrayCommon<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault, Action<T> arrayElementVisitor) { Debug.Assert(!string.IsNullOrEmpty(header)); Indent(); if (!list.IsDefaultOrEmpty) { var elementCount = logElementCount ? $"({list.Count()})" : string.Empty; LogString($"{header}{elementCount}:"); LogNewLine(); Indent(); foreach (var element in list) { arrayElementVisitor(element); } Unindent(); } else { var suffix = logNullForDefault && list.IsDefault ? ": null" : "(0)"; LogString($"{header}{suffix}"); LogNewLine(); } Unindent(); } internal void VisitSymbolArrayElement(ISymbol element) { LogSymbol(element, header: "Symbol"); LogNewLine(); } internal void VisitStringArrayElement(string element) { var valueStr = element != null ? element.ToString() : "null"; valueStr = @"""" + valueStr + @""""; LogString(valueStr); LogNewLine(); } internal void VisitRefKindArrayElement(RefKind element) { LogString(element.ToString()); LogNewLine(); } private void VisitChildren(IOperation operation) { Debug.Assert(operation.Children.All(o => o != null)); var children = operation.Children.ToImmutableArray(); if (!children.IsEmpty || operation.Kind != OperationKind.None) { VisitArray(children, "Children", logElementCount: true); } } private void VisitArray<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault = false) where T : IOperation { VisitArrayCommon(list, header, logElementCount, logNullForDefault, o => Visit(o)); } private void VisitArray(ImmutableArray<ISymbol> list, string header, bool logElementCount, bool logNullForDefault = false) { VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitSymbolArrayElement); } private void VisitArray(ImmutableArray<string> list, string header, bool logElementCount, bool logNullForDefault = false) { VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitStringArrayElement); } private void VisitArray(ImmutableArray<RefKind> list, string header, bool logElementCount, bool logNullForDefault = false) { VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitRefKindArrayElement); } private void VisitInstance(IOperation instance) { Visit(instance, header: "Instance Receiver"); } internal override void VisitNoneOperation(IOperation operation) { LogString("IOperation: "); LogCommonPropertiesAndNewLine(operation); VisitChildren(operation); } public override void VisitBlock(IBlockOperation operation) { LogString(nameof(IBlockOperation)); var statementsStr = $"{operation.Operations.Length} statements"; var localStr = !operation.Locals.IsEmpty ? $", {operation.Locals.Length} locals" : string.Empty; LogString($" ({statementsStr}{localStr})"); LogCommonPropertiesAndNewLine(operation); if (operation.Operations.IsEmpty) { return; } LogLocals(operation.Locals); base.VisitBlock(operation); } public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) { var variablesCountStr = $"{operation.Declarations.Length} declarations"; LogString($"{nameof(IVariableDeclarationGroupOperation)} ({variablesCountStr})"); LogCommonPropertiesAndNewLine(operation); base.VisitVariableDeclarationGroup(operation); } public override void VisitUsingDeclaration(IUsingDeclarationOperation operation) { LogString($"{nameof(IUsingDeclarationOperation)}"); LogString($"(IsAsynchronous: {operation.IsAsynchronous}"); var disposeMethod = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod; if (disposeMethod is object) { LogSymbol(disposeMethod, ", DisposeMethod"); } LogString(")"); LogCommonPropertiesAndNewLine(operation); Visit(operation.DeclarationGroup, "DeclarationGroup"); var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { VisitArray(disposeArgs, "DisposeArguments", logElementCount: true); } } public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { LogString($"{nameof(IVariableDeclaratorOperation)} ("); LogSymbol(operation.Symbol, "Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Initializer, "Initializer"); if (!operation.IgnoredArguments.IsEmpty) { VisitArray(operation.IgnoredArguments, "IgnoredArguments", logElementCount: true); } } public override void VisitVariableDeclaration(IVariableDeclarationOperation operation) { var variableCount = operation.Declarators.Length; LogString($"{nameof(IVariableDeclarationOperation)} ({variableCount} declarators)"); LogCommonPropertiesAndNewLine(operation); if (!operation.IgnoredDimensions.IsEmpty) { VisitArray(operation.IgnoredDimensions, "Ignored Dimensions", true); } VisitArray(operation.Declarators, "Declarators", false); Visit(operation.Initializer, "Initializer"); } public override void VisitSwitch(ISwitchOperation operation) { var caseCountStr = $"{operation.Cases.Length} cases"; var exitLabelStr = $", Exit Label Id: {GetLabelId(operation.ExitLabel)}"; LogString($"{nameof(ISwitchOperation)} ({caseCountStr}{exitLabelStr})"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, header: "Switch expression"); LogLocals(operation.Locals); foreach (ISwitchCaseOperation section in operation.Cases) { foreach (ICaseClauseOperation c in section.Clauses) { if (c.Label != null) { GetLabelId(c.Label); } } } VisitArray(operation.Cases, "Sections", logElementCount: false); } public override void VisitSwitchCase(ISwitchCaseOperation operation) { var caseClauseCountStr = $"{operation.Clauses.Length} case clauses"; var statementCountStr = $"{operation.Body.Length} statements"; LogString($"{nameof(ISwitchCaseOperation)} ({caseClauseCountStr}, {statementCountStr})"); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Indent(); VisitArray(operation.Clauses, "Clauses", logElementCount: false); VisitArray(operation.Body, "Body", logElementCount: false); Unindent(); _ = ((SwitchCaseOperation)operation).Condition; } public override void VisitWhileLoop(IWhileLoopOperation operation) { LogString(nameof(IWhileLoopOperation)); LogString($" (ConditionIsTop: {operation.ConditionIsTop}, ConditionIsUntil: {operation.ConditionIsUntil})"); LogLoopStatementHeader(operation); Visit(operation.Condition, "Condition"); Visit(operation.Body, "Body"); Visit(operation.IgnoredCondition, "IgnoredCondition"); } public override void VisitForLoop(IForLoopOperation operation) { LogString(nameof(IForLoopOperation)); LogLoopStatementHeader(operation); LogLocals(operation.ConditionLocals, header: nameof(operation.ConditionLocals)); Visit(operation.Condition, "Condition"); VisitArray(operation.Before, "Before", logElementCount: false); VisitArray(operation.AtLoopBottom, "AtLoopBottom", logElementCount: false); Visit(operation.Body, "Body"); } public override void VisitForToLoop(IForToLoopOperation operation) { LogString(nameof(IForToLoopOperation)); LogLoopStatementHeader(operation, operation.IsChecked); Visit(operation.LoopControlVariable, "LoopControlVariable"); Visit(operation.InitialValue, "InitialValue"); Visit(operation.LimitValue, "LimitValue"); Visit(operation.StepValue, "StepValue"); Visit(operation.Body, "Body"); VisitArray(operation.NextVariables, "NextVariables", logElementCount: true); (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; if (userDefinedInfo != null) { _ = userDefinedInfo.Addition; _ = userDefinedInfo.Subtraction; _ = userDefinedInfo.LessThanOrEqual; _ = userDefinedInfo.GreaterThanOrEqual; } } private void LogLocals(IEnumerable<ILocalSymbol> locals, string header = "Locals") { if (!locals.Any()) { return; } Indent(); LogString($"{header}: "); Indent(); int localIndex = 1; foreach (var local in locals) { LogSymbol(local, header: $"Local_{localIndex++}"); LogNewLine(); } Unindent(); Unindent(); } private void LogLoopStatementHeader(ILoopOperation operation, bool? isChecked = null) { Assert.Equal(OperationKind.Loop, operation.Kind); var propertyStringBuilder = new StringBuilder(); propertyStringBuilder.Append(" ("); propertyStringBuilder.Append($"{nameof(LoopKind)}.{operation.LoopKind}"); if (operation is IForEachLoopOperation { IsAsynchronous: true }) { propertyStringBuilder.Append($", IsAsynchronous"); } propertyStringBuilder.Append($", Continue Label Id: {GetLabelId(operation.ContinueLabel)}"); propertyStringBuilder.Append($", Exit Label Id: {GetLabelId(operation.ExitLabel)}"); if (isChecked.GetValueOrDefault()) { propertyStringBuilder.Append($", Checked"); } propertyStringBuilder.Append(")"); LogString(propertyStringBuilder.ToString()); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); } public override void VisitForEachLoop(IForEachLoopOperation operation) { LogString(nameof(IForEachLoopOperation)); LogLoopStatementHeader(operation); Assert.NotNull(operation.LoopControlVariable); Visit(operation.LoopControlVariable, "LoopControlVariable"); Visit(operation.Collection, "Collection"); Visit(operation.Body, "Body"); VisitArray(operation.NextVariables, "NextVariables", logElementCount: true); ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; } public override void VisitLabeled(ILabeledOperation operation) { LogString(nameof(ILabeledOperation)); if (!operation.Label.IsImplicitlyDeclared) { LogString($" (Label: {operation.Label.Name})"); } else { LogString($" (Label Id: {GetLabelId(operation.Label)})"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Statement"); } public override void VisitBranch(IBranchOperation operation) { LogString(nameof(IBranchOperation)); var kindStr = $"{nameof(BranchKind)}.{operation.BranchKind}"; // If the label is implicit, or if it has been assigned an id (such as VB Exit Do/While/Switch labels) then print the id, instead of the name. var labelStr = !(operation.Target.IsImplicitlyDeclared || _labelIdMap.ContainsKey(operation.Target)) ? $", Label: {operation.Target.Name}" : $", Label Id: {GetLabelId(operation.Target)}"; LogString($" ({kindStr}{labelStr})"); LogCommonPropertiesAndNewLine(operation); base.VisitBranch(operation); } public override void VisitEmpty(IEmptyOperation operation) { LogString(nameof(IEmptyOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitReturn(IReturnOperation operation) { LogString(nameof(IReturnOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.ReturnedValue, "ReturnedValue"); } public override void VisitLock(ILockOperation operation) { LogString(nameof(ILockOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.LockedValue, "Expression"); Visit(operation.Body, "Body"); } public override void VisitTry(ITryOperation operation) { LogString(nameof(ITryOperation)); if (operation.ExitLabel != null) { LogString($" (Exit Label Id: {GetLabelId(operation.ExitLabel)})"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.Body, "Body"); VisitArray(operation.Catches, "Catch clauses", logElementCount: true); Visit(operation.Finally, "Finally"); } public override void VisitCatchClause(ICatchClauseOperation operation) { LogString(nameof(ICatchClauseOperation)); var exceptionTypeStr = operation.ExceptionType != null ? operation.ExceptionType.ToTestDisplayString() : "null"; LogString($" (Exception type: {exceptionTypeStr})"); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Visit(operation.ExceptionDeclarationOrExpression, "ExceptionDeclarationOrExpression"); Visit(operation.Filter, "Filter"); Visit(operation.Handler, "Handler"); } public override void VisitUsing(IUsingOperation operation) { LogString(nameof(IUsingOperation)); if (operation.IsAsynchronous) { LogString($" (IsAsynchronous)"); } var disposeMethod = ((UsingOperation)operation).DisposeInfo.DisposeMethod; if (disposeMethod is object) { LogSymbol(disposeMethod, " (DisposeMethod"); LogString(")"); } LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Visit(operation.Resources, "Resources"); Visit(operation.Body, "Body"); Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind); Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind); var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { VisitArray(disposeArgs, "DisposeArguments", logElementCount: true); } } // https://github.com/dotnet/roslyn/issues/21281 internal override void VisitFixed(IFixedOperation operation) { LogString(nameof(IFixedOperation)); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Visit(operation.Variables, "Declaration"); Visit(operation.Body, "Body"); } internal override void VisitAggregateQuery(IAggregateQueryOperation operation) { LogString(nameof(IAggregateQueryOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Group, "Group"); Visit(operation.Aggregation, "Aggregation"); } public override void VisitExpressionStatement(IExpressionStatementOperation operation) { LogString(nameof(IExpressionStatementOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); } internal override void VisitWithStatement(IWithStatementOperation operation) { LogString(nameof(IWithStatementOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, "Value"); Visit(operation.Body, "Body"); } public override void VisitStop(IStopOperation operation) { LogString(nameof(IStopOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitEnd(IEndOperation operation) { LogString(nameof(IEndOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitInvocation(IInvocationOperation operation) { LogString(nameof(IInvocationOperation)); var isVirtualStr = operation.IsVirtual ? "virtual " : string.Empty; var spacing = !operation.IsVirtual && operation.Instance != null ? " " : string.Empty; LogString($" ({isVirtualStr}{spacing}"); LogSymbol(operation.TargetMethod, header: string.Empty); LogString(")"); LogCommonPropertiesAndNewLine(operation); VisitInstance(operation.Instance); VisitArguments(operation.Arguments); } private void VisitArguments(ImmutableArray<IArgumentOperation> arguments) { VisitArray(arguments, "Arguments", logElementCount: true); } private void VisitDynamicArguments(HasDynamicArgumentsExpression operation) { VisitArray(operation.Arguments, "Arguments", logElementCount: true); VisitArray(operation.ArgumentNames, "ArgumentNames", logElementCount: true); VisitArray(operation.ArgumentRefKinds, "ArgumentRefKinds", logElementCount: true, logNullForDefault: true); VerifyGetArgumentNamePublicApi(operation, operation.ArgumentNames); VerifyGetArgumentRefKindPublicApi(operation, operation.ArgumentRefKinds); } private static void VerifyGetArgumentNamePublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<string> argumentNames) { var length = operation.Arguments.Length; if (argumentNames.IsDefaultOrEmpty) { for (int i = 0; i < length; i++) { Assert.Null(operation.GetArgumentName(i)); } } else { Assert.Equal(length, argumentNames.Length); for (var i = 0; i < length; i++) { Assert.Equal(argumentNames[i], operation.GetArgumentName(i)); } } } private static void VerifyGetArgumentRefKindPublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<RefKind> argumentRefKinds) { var length = operation.Arguments.Length; if (argumentRefKinds.IsDefault) { for (int i = 0; i < length; i++) { Assert.Null(operation.GetArgumentRefKind(i)); } } else if (argumentRefKinds.IsEmpty) { for (int i = 0; i < length; i++) { Assert.Equal(RefKind.None, operation.GetArgumentRefKind(i)); } } else { Assert.Equal(length, argumentRefKinds.Length); for (var i = 0; i < length; i++) { Assert.Equal(argumentRefKinds[i], operation.GetArgumentRefKind(i)); } } } public override void VisitArgument(IArgumentOperation operation) { LogString($"{nameof(IArgumentOperation)} ("); LogString($"{nameof(ArgumentKind)}.{operation.ArgumentKind}, "); LogSymbol(operation.Parameter, header: "Matching Parameter", logDisplayString: false); LogString(")"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value); Indent(); LogConversion(operation.InConversion, "InConversion"); LogNewLine(); LogConversion(operation.OutConversion, "OutConversion"); LogNewLine(); Unindent(); } public override void VisitOmittedArgument(IOmittedArgumentOperation operation) { LogString(nameof(IOmittedArgumentOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitArrayElementReference(IArrayElementReferenceOperation operation) { LogString(nameof(IArrayElementReferenceOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.ArrayReference, "Array reference"); VisitArray(operation.Indices, "Indices", logElementCount: true); } internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) { LogString(nameof(IPointerIndirectionReferenceOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Pointer, "Pointer"); } public override void VisitLocalReference(ILocalReferenceOperation operation) { LogString(nameof(ILocalReferenceOperation)); LogString($": {operation.Local.Name}"); if (operation.IsDeclaration) { LogString($" (IsDeclaration: {operation.IsDeclaration})"); } LogCommonPropertiesAndNewLine(operation); } public override void VisitFlowCapture(IFlowCaptureOperation operation) { LogString(nameof(IFlowCaptureOperation)); LogString($": {operation.Id.Value}"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, "Value"); TestOperationVisitor.Singleton.VisitFlowCapture(operation); } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { LogString(nameof(IFlowCaptureReferenceOperation)); LogString($": {operation.Id.Value}"); LogCommonPropertiesAndNewLine(operation); } public override void VisitIsNull(IIsNullOperation operation) { LogString(nameof(IIsNullOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); } public override void VisitCaughtException(ICaughtExceptionOperation operation) { LogString(nameof(ICaughtExceptionOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitParameterReference(IParameterReferenceOperation operation) { LogString(nameof(IParameterReferenceOperation)); LogString($": {operation.Parameter.Name}"); LogCommonPropertiesAndNewLine(operation); } public override void VisitInstanceReference(IInstanceReferenceOperation operation) { LogString(nameof(IInstanceReferenceOperation)); LogString($" (ReferenceKind: {operation.ReferenceKind})"); LogCommonPropertiesAndNewLine(operation); if (operation.IsImplicit) { if (operation.Parent is IMemberReferenceOperation memberReference && memberReference.Instance == operation) { Assert.False(memberReference.Member.IsStatic && !operation.HasErrors(this._compilation)); } else if (operation.Parent is IInvocationOperation invocation && invocation.Instance == operation) { Assert.False(invocation.TargetMethod.IsStatic); } } } private void VisitMemberReferenceExpressionCommon(IMemberReferenceOperation operation) { if (operation.Member.IsStatic) { LogString(" (Static)"); } LogCommonPropertiesAndNewLine(operation); VisitInstance(operation.Instance); } public override void VisitFieldReference(IFieldReferenceOperation operation) { LogString(nameof(IFieldReferenceOperation)); LogString($": {operation.Field.ToTestDisplayString()}"); if (operation.IsDeclaration) { LogString($" (IsDeclaration: {operation.IsDeclaration})"); } VisitMemberReferenceExpressionCommon(operation); } public override void VisitMethodReference(IMethodReferenceOperation operation) { LogString(nameof(IMethodReferenceOperation)); LogString($": {operation.Method.ToTestDisplayString()}"); if (operation.IsVirtual) { LogString(" (IsVirtual)"); } Assert.Null(operation.Type); VisitMemberReferenceExpressionCommon(operation); } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { LogString(nameof(IPropertyReferenceOperation)); LogString($": {operation.Property.ToTestDisplayString()}"); VisitMemberReferenceExpressionCommon(operation); if (operation.Arguments.Length > 0) { VisitArguments(operation.Arguments); } } public override void VisitEventReference(IEventReferenceOperation operation) { LogString(nameof(IEventReferenceOperation)); LogString($": {operation.Event.ToTestDisplayString()}"); VisitMemberReferenceExpressionCommon(operation); } public override void VisitEventAssignment(IEventAssignmentOperation operation) { var kindStr = operation.Adds ? "EventAdd" : "EventRemove"; LogString($"{nameof(IEventAssignmentOperation)} ({kindStr})"); LogCommonPropertiesAndNewLine(operation); Assert.NotNull(operation.EventReference); Visit(operation.EventReference, header: "Event Reference"); Visit(operation.HandlerValue, header: "Handler"); } public override void VisitConditionalAccess(IConditionalAccessOperation operation) { LogString(nameof(IConditionalAccessOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, header: nameof(operation.Operation)); Visit(operation.WhenNotNull, header: nameof(operation.WhenNotNull)); Assert.NotNull(operation.Type); } public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) { LogString(nameof(IConditionalAccessInstanceOperation)); LogCommonPropertiesAndNewLine(operation); } internal override void VisitPlaceholder(IPlaceholderOperation operation) { LogString(nameof(IPlaceholderOperation)); LogCommonPropertiesAndNewLine(operation); Assert.Equal(PlaceholderKind.AggregationGroup, operation.PlaceholderKind); } public override void VisitUnaryOperator(IUnaryOperation operation) { LogString(nameof(IUnaryOperation)); var kindStr = $"{nameof(UnaryOperatorKind)}.{operation.OperatorKind}"; if (operation.IsLifted) { kindStr += ", IsLifted"; } if (operation.IsChecked) { kindStr += ", Checked"; } LogString($" ({kindStr})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); } public override void VisitBinaryOperator(IBinaryOperation operation) { LogString(nameof(IBinaryOperation)); var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}"; if (operation.IsLifted) { kindStr += ", IsLifted"; } if (operation.IsChecked) { kindStr += ", Checked"; } if (operation.IsCompareText) { kindStr += ", CompareText"; } LogString($" ({kindStr})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod; LogCommonPropertiesAndNewLine(operation); Visit(operation.LeftOperand, "Left"); Visit(operation.RightOperand, "Right"); } public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation) { LogString(nameof(ITupleBinaryOperation)); var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}"; LogString($" ({kindStr})"); LogCommonPropertiesAndNewLine(operation); Visit(operation.LeftOperand, "Left"); Visit(operation.RightOperand, "Right"); } private void LogHasOperatorMethodExpressionCommon(IMethodSymbol operatorMethodOpt) { if (operatorMethodOpt != null) { LogSymbol(operatorMethodOpt, header: " (OperatorMethod"); LogString(")"); } } public override void VisitConversion(IConversionOperation operation) { LogString(nameof(IConversionOperation)); var isTryCast = $"TryCast: {(operation.IsTryCast ? "True" : "False")}"; var isChecked = operation.IsChecked ? "Checked" : "Unchecked"; LogString($" ({isTryCast}, {isChecked})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); LogCommonPropertiesAndNewLine(operation); Indent(); LogConversion(operation.Conversion); if (((Operation)operation).OwningSemanticModel == null) { LogNewLine(); Indent(); LogString($"({((ConversionOperation)operation).ConversionConvertible})"); Unindent(); } Unindent(); LogNewLine(); Visit(operation.Operand, "Operand"); } public override void VisitConditional(IConditionalOperation operation) { LogString(nameof(IConditionalOperation)); if (operation.IsRef) { LogString(" (IsRef)"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.Condition, "Condition"); Visit(operation.WhenTrue, "WhenTrue"); Visit(operation.WhenFalse, "WhenFalse"); } public override void VisitCoalesce(ICoalesceOperation operation) { LogString(nameof(ICoalesceOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, "Expression"); Indent(); LogConversion(operation.ValueConversion, "ValueConversion"); LogNewLine(); Indent(); LogString($"({((CoalesceOperation)operation).ValueConversionConvertible})"); Unindent(); LogNewLine(); Unindent(); Visit(operation.WhenNull, "WhenNull"); } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { LogString(nameof(ICoalesceAssignmentOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, nameof(operation.Target)); Visit(operation.Value, nameof(operation.Value)); } public override void VisitIsType(IIsTypeOperation operation) { LogString(nameof(IIsTypeOperation)); if (operation.IsNegated) { LogString(" (IsNotExpression)"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.ValueOperand, "Operand"); Indent(); LogType(operation.TypeOperand, "IsType"); LogNewLine(); Unindent(); } public override void VisitSizeOf(ISizeOfOperation operation) { LogString(nameof(ISizeOfOperation)); LogCommonPropertiesAndNewLine(operation); Indent(); LogType(operation.TypeOperand, "TypeOperand"); LogNewLine(); Unindent(); } public override void VisitTypeOf(ITypeOfOperation operation) { LogString(nameof(ITypeOfOperation)); LogCommonPropertiesAndNewLine(operation); Indent(); LogType(operation.TypeOperand, "TypeOperand"); LogNewLine(); Unindent(); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { LogString(nameof(IAnonymousFunctionOperation)); // For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart. // That is how symbol display is implemented for C#. // https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output. LogSymbol(operation.Symbol, header: " (Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); base.VisitAnonymousFunction(operation); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { LogString(nameof(IFlowAnonymousFunctionOperation)); // For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart. // That is how symbol display is implemented for C#. // https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output. LogSymbol(operation.Symbol, header: " (Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); base.VisitFlowAnonymousFunction(operation); } public override void VisitDelegateCreation(IDelegateCreationOperation operation) { LogString(nameof(IDelegateCreationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, nameof(operation.Target)); } public override void VisitLiteral(ILiteralOperation operation) { LogString(nameof(ILiteralOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitAwait(IAwaitOperation operation) { LogString(nameof(IAwaitOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); } public override void VisitNameOf(INameOfOperation operation) { LogString(nameof(INameOfOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Argument); } public override void VisitThrow(IThrowOperation operation) { LogString(nameof(IThrowOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Exception); } public override void VisitAddressOf(IAddressOfOperation operation) { LogString(nameof(IAddressOfOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Reference, "Reference"); } public override void VisitObjectCreation(IObjectCreationOperation operation) { LogString(nameof(IObjectCreationOperation)); LogString($" (Constructor: {operation.Constructor?.ToTestDisplayString() ?? "<null>"})"); LogCommonPropertiesAndNewLine(operation); VisitArguments(operation.Arguments); Visit(operation.Initializer, "Initializer"); } public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) { LogString(nameof(IAnonymousObjectCreationOperation)); LogCommonPropertiesAndNewLine(operation); foreach (var initializer in operation.Initializers) { var simpleAssignment = (ISimpleAssignmentOperation)initializer; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Assert.Empty(propertyReference.Arguments); Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind); Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind); } VisitArray(operation.Initializers, "Initializers", logElementCount: true); } public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) { LogString(nameof(IDynamicObjectCreationOperation)); LogCommonPropertiesAndNewLine(operation); VisitDynamicArguments((HasDynamicArgumentsExpression)operation); Visit(operation.Initializer, "Initializer"); } public override void VisitDynamicInvocation(IDynamicInvocationOperation operation) { LogString(nameof(IDynamicInvocationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); VisitDynamicArguments((HasDynamicArgumentsExpression)operation); } public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) { LogString(nameof(IDynamicIndexerAccessOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); VisitDynamicArguments((HasDynamicArgumentsExpression)operation); } public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) { LogString(nameof(IObjectOrCollectionInitializerOperation)); LogCommonPropertiesAndNewLine(operation); VisitArray(operation.Initializers, "Initializers", logElementCount: true); } public override void VisitMemberInitializer(IMemberInitializerOperation operation) { LogString(nameof(IMemberInitializerOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.InitializedMember, "InitializedMember"); Visit(operation.Initializer, "Initializer"); } [Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", error: true)] public override void VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation) { // Kept to ensure that it's never called, as we can't override DefaultVisit in this visitor throw ExceptionUtilities.Unreachable; } public override void VisitFieldInitializer(IFieldInitializerOperation operation) { LogString(nameof(IFieldInitializerOperation)); if (operation.InitializedFields.Length <= 1) { if (operation.InitializedFields.Length == 1) { LogSymbol(operation.InitializedFields[0], header: " (Field"); LogString(")"); } LogCommonPropertiesAndNewLine(operation); } else { LogString($" ({operation.InitializedFields.Length} initialized fields)"); LogCommonPropertiesAndNewLine(operation); Indent(); int index = 1; foreach (var local in operation.InitializedFields) { LogSymbol(local, header: $"Field_{index++}"); LogNewLine(); } Unindent(); } LogLocals(operation.Locals); base.VisitFieldInitializer(operation); } public override void VisitVariableInitializer(IVariableInitializerOperation operation) { LogString(nameof(IVariableInitializerOperation)); LogCommonPropertiesAndNewLine(operation); Assert.Empty(operation.Locals); base.VisitVariableInitializer(operation); } public override void VisitPropertyInitializer(IPropertyInitializerOperation operation) { LogString(nameof(IPropertyInitializerOperation)); if (operation.InitializedProperties.Length <= 1) { if (operation.InitializedProperties.Length == 1) { LogSymbol(operation.InitializedProperties[0], header: " (Property"); LogString(")"); } LogCommonPropertiesAndNewLine(operation); } else { LogString($" ({operation.InitializedProperties.Length} initialized properties)"); LogCommonPropertiesAndNewLine(operation); Indent(); int index = 1; foreach (var property in operation.InitializedProperties) { LogSymbol(property, header: $"Property_{index++}"); LogNewLine(); } Unindent(); } LogLocals(operation.Locals); base.VisitPropertyInitializer(operation); } public override void VisitParameterInitializer(IParameterInitializerOperation operation) { LogString(nameof(IParameterInitializerOperation)); LogSymbol(operation.Parameter, header: " (Parameter"); LogString(")"); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); base.VisitParameterInitializer(operation); } public override void VisitArrayCreation(IArrayCreationOperation operation) { LogString(nameof(IArrayCreationOperation)); LogCommonPropertiesAndNewLine(operation); VisitArray(operation.DimensionSizes, "Dimension Sizes", logElementCount: true); Visit(operation.Initializer, "Initializer"); } public override void VisitArrayInitializer(IArrayInitializerOperation operation) { LogString(nameof(IArrayInitializerOperation)); LogString($" ({operation.ElementValues.Length} elements)"); LogCommonPropertiesAndNewLine(operation); Assert.Null(operation.Type); VisitArray(operation.ElementValues, "Element Values", logElementCount: true); } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { LogString(nameof(ISimpleAssignmentOperation)); if (operation.IsRef) { LogString(" (IsRef)"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, "Left"); Visit(operation.Value, "Right"); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { LogString(nameof(IDeconstructionAssignmentOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, "Left"); Visit(operation.Value, "Right"); } public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation) { LogString(nameof(IDeclarationExpressionOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Expression); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { LogString(nameof(ICompoundAssignmentOperation)); var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}"; if (operation.IsLifted) { kindStr += ", IsLifted"; } if (operation.IsChecked) { kindStr += ", Checked"; } LogString($" ({kindStr})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); LogCommonPropertiesAndNewLine(operation); Indent(); LogConversion(operation.InConversion, "InConversion"); LogNewLine(); LogConversion(operation.OutConversion, "OutConversion"); LogNewLine(); Unindent(); Visit(operation.Target, "Left"); Visit(operation.Value, "Right"); } public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) { LogString(nameof(IIncrementOrDecrementOperation)); var kindStr = operation.IsPostfix ? "Postfix" : "Prefix"; if (operation.IsLifted) { kindStr += ", IsLifted"; } if (operation.IsChecked) { kindStr += ", Checked"; } LogString($" ({kindStr})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, "Target"); } public override void VisitParenthesized(IParenthesizedOperation operation) { LogString(nameof(IParenthesizedOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); } public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) { LogString(nameof(IDynamicMemberReferenceOperation)); // (Member Name: "quoted name", Containing Type: type) LogString(" ("); LogConstant((object)operation.MemberName, "Member Name"); LogString(", "); LogType(operation.ContainingType, "Containing Type"); LogString(")"); LogCommonPropertiesAndNewLine(operation); VisitArrayCommon(operation.TypeArguments, "Type Arguments", logElementCount: true, logNullForDefault: false, arrayElementVisitor: VisitSymbolArrayElement); VisitInstance(operation.Instance); } public override void VisitDefaultValue(IDefaultValueOperation operation) { LogString(nameof(IDefaultValueOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) { LogString(nameof(ITypeParameterObjectCreationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Initializer, "Initializer"); } internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) { LogString(nameof(INoPiaObjectCreationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Initializer, "Initializer"); } public override void VisitInvalid(IInvalidOperation operation) { LogString(nameof(IInvalidOperation)); LogCommonPropertiesAndNewLine(operation); VisitChildren(operation); } public override void VisitLocalFunction(ILocalFunctionOperation operation) { LogString(nameof(ILocalFunctionOperation)); LogSymbol(operation.Symbol, header: " (Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); if (operation.Body != null) { if (operation.IgnoredBody != null) { Visit(operation.Body, "Body"); Visit(operation.IgnoredBody, "IgnoredBody"); } else { Visit(operation.Body); } } else { Assert.Null(operation.IgnoredBody); } } private void LogCaseClauseCommon(ICaseClauseOperation operation) { Assert.Equal(OperationKind.CaseClause, operation.Kind); if (operation.Label != null) { LogString($" (Label Id: {GetLabelId(operation.Label)})"); } var kindStr = $"{nameof(CaseKind)}.{operation.CaseKind}"; LogString($" ({kindStr})"); LogCommonPropertiesAndNewLine(operation); } public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) { LogString(nameof(ISingleValueCaseClauseOperation)); LogCaseClauseCommon(operation); Visit(operation.Value, "Value"); } public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) { LogString(nameof(IRelationalCaseClauseOperation)); var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.Relation}"; LogString($" (Relational operator kind: {kindStr})"); LogCaseClauseCommon(operation); Visit(operation.Value, "Value"); } public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation) { LogString(nameof(IRangeCaseClauseOperation)); LogCaseClauseCommon(operation); Visit(operation.MinimumValue, "Min"); Visit(operation.MaximumValue, "Max"); } public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) { LogString(nameof(IDefaultCaseClauseOperation)); LogCaseClauseCommon(operation); } public override void VisitTuple(ITupleOperation operation) { LogString(nameof(ITupleOperation)); LogCommonPropertiesAndNewLine(operation); Indent(); LogType(operation.NaturalType, nameof(operation.NaturalType)); LogNewLine(); Unindent(); VisitArray(operation.Elements, "Elements", logElementCount: true); } public override void VisitInterpolatedString(IInterpolatedStringOperation operation) { LogString(nameof(IInterpolatedStringOperation)); LogCommonPropertiesAndNewLine(operation); VisitArray(operation.Parts, "Parts", logElementCount: true); } public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) { LogString(nameof(IInterpolatedStringTextOperation)); LogCommonPropertiesAndNewLine(operation); if (operation.Text.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind); } Visit(operation.Text, "Text"); } public override void VisitInterpolation(IInterpolationOperation operation) { LogString(nameof(IInterpolationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Expression, "Expression"); Visit(operation.Alignment, "Alignment"); Visit(operation.FormatString, "FormatString"); if (operation.FormatString != null && operation.FormatString.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind); } } public override void VisitConstantPattern(IConstantPatternOperation operation) { LogString(nameof(IConstantPatternOperation)); LogPatternPropertiesAndNewLine(operation); Visit(operation.Value, "Value"); } public override void VisitRelationalPattern(IRelationalPatternOperation operation) { LogString(nameof(IRelationalPatternOperation)); LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})"); LogPatternPropertiesAndNewLine(operation); Visit(operation.Value, "Value"); } public override void VisitNegatedPattern(INegatedPatternOperation operation) { LogString(nameof(INegatedPatternOperation)); LogPatternPropertiesAndNewLine(operation); Visit(operation.Pattern, "Pattern"); } public override void VisitBinaryPattern(IBinaryPatternOperation operation) { LogString(nameof(IBinaryPatternOperation)); LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})"); LogPatternPropertiesAndNewLine(operation); Visit(operation.LeftPattern, "LeftPattern"); Visit(operation.RightPattern, "RightPattern"); } public override void VisitTypePattern(ITypePatternOperation operation) { LogString(nameof(ITypePatternOperation)); LogPatternProperties(operation); LogSymbol(operation.MatchedType, $", {nameof(operation.MatchedType)}"); LogString(")"); LogNewLine(); } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { LogString(nameof(IDeclarationPatternOperation)); LogPatternProperties(operation); LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}"); LogConstant((object)operation.MatchesNull, $", {nameof(operation.MatchesNull)}"); LogString(")"); LogNewLine(); } public override void VisitRecursivePattern(IRecursivePatternOperation operation) { LogString(nameof(IRecursivePatternOperation)); LogPatternProperties(operation); LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}"); LogType(operation.MatchedType, $", {nameof(operation.MatchedType)}"); LogSymbol(operation.DeconstructSymbol, $", {nameof(operation.DeconstructSymbol)}"); LogString(")"); LogNewLine(); VisitArray(operation.DeconstructionSubpatterns, $"{nameof(operation.DeconstructionSubpatterns)} ", true, true); VisitArray(operation.PropertySubpatterns, $"{nameof(operation.PropertySubpatterns)} ", true, true); } public override void VisitPropertySubpattern(IPropertySubpatternOperation operation) { LogString(nameof(IPropertySubpatternOperation)); LogCommonProperties(operation); LogNewLine(); Visit(operation.Member, $"{nameof(operation.Member)}"); Visit(operation.Pattern, $"{nameof(operation.Pattern)}"); } public override void VisitIsPattern(IIsPatternOperation operation) { LogString(nameof(IIsPatternOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, $"{nameof(operation.Value)}"); Visit(operation.Pattern, "Pattern"); } public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation) { LogString(nameof(IPatternCaseClauseOperation)); LogCaseClauseCommon(operation); Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label); Visit(operation.Pattern, "Pattern"); if (operation.Guard != null) Visit(operation.Guard, nameof(operation.Guard)); } public override void VisitTranslatedQuery(ITranslatedQueryOperation operation) { LogString(nameof(ITranslatedQueryOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); } public override void VisitRaiseEvent(IRaiseEventOperation operation) { LogString(nameof(IRaiseEventOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.EventReference, header: "Event Reference"); VisitArguments(operation.Arguments); } public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation) { LogString(nameof(IConstructorBodyOperation)); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Visit(operation.Initializer, "Initializer"); Visit(operation.BlockBody, "BlockBody"); Visit(operation.ExpressionBody, "ExpressionBody"); } public override void VisitMethodBodyOperation(IMethodBodyOperation operation) { LogString(nameof(IMethodBodyOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.BlockBody, "BlockBody"); Visit(operation.ExpressionBody, "ExpressionBody"); } public override void VisitDiscardOperation(IDiscardOperation operation) { LogString(nameof(IDiscardOperation)); LogString(" ("); LogSymbol(operation.DiscardSymbol, "Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); } public override void VisitDiscardPattern(IDiscardPatternOperation operation) { LogString(nameof(IDiscardPatternOperation)); LogPatternPropertiesAndNewLine(operation); } public override void VisitSwitchExpression(ISwitchExpressionOperation operation) { LogString($"{nameof(ISwitchExpressionOperation)} ({operation.Arms.Length} arms, IsExhaustive: {operation.IsExhaustive})"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, nameof(operation.Value)); VisitArray(operation.Arms, nameof(operation.Arms), logElementCount: true); } public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) { LogString($"{nameof(ISwitchExpressionArmOperation)} ({operation.Locals.Length} locals)"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Pattern, nameof(operation.Pattern)); if (operation.Guard != null) Visit(operation.Guard, nameof(operation.Guard)); Visit(operation.Value, nameof(operation.Value)); LogLocals(operation.Locals); } public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) { LogString(nameof(IStaticLocalInitializationSemaphoreOperation)); LogSymbol(operation.Local, " (Local Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); } public override void VisitRangeOperation(IRangeOperation operation) { LogString(nameof(IRangeOperation)); if (operation.IsLifted) { LogString(" (IsLifted)"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.LeftOperand, nameof(operation.LeftOperand)); Visit(operation.RightOperand, nameof(operation.RightOperand)); } public override void VisitReDim(IReDimOperation operation) { LogString(nameof(IReDimOperation)); if (operation.Preserve) { LogString(" (Preserve)"); } LogCommonPropertiesAndNewLine(operation); VisitArray(operation.Clauses, "Clauses", logElementCount: true); } public override void VisitReDimClause(IReDimClauseOperation operation) { LogString(nameof(IReDimClauseOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); VisitArray(operation.DimensionSizes, "DimensionSizes", logElementCount: true); } public override void VisitWith(IWithOperation operation) { LogString(nameof(IWithOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); Indent(); LogSymbol(operation.CloneMethod, nameof(operation.CloneMethod)); LogNewLine(); Unindent(); Visit(operation.Initializer, "Initializer"); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public class OperationTreeVerifier : OperationWalker { protected readonly Compilation _compilation; protected readonly IOperation _root; protected readonly StringBuilder _builder; private readonly Dictionary<SyntaxNode, IOperation> _explicitNodeMap; private readonly Dictionary<ILabelSymbol, uint> _labelIdMap; private const string indent = " "; protected string _currentIndent; private bool _pendingIndent; private uint _currentLabelId = 0; public OperationTreeVerifier(Compilation compilation, IOperation root, int initialIndent) { _compilation = compilation; _root = root; _builder = new StringBuilder(); _currentIndent = new string(' ', initialIndent); _pendingIndent = true; _explicitNodeMap = new Dictionary<SyntaxNode, IOperation>(); _labelIdMap = new Dictionary<ILabelSymbol, uint>(); } public static string GetOperationTree(Compilation compilation, IOperation operation, int initialIndent = 0) { var walker = new OperationTreeVerifier(compilation, operation, initialIndent); walker.Visit(operation); return walker._builder.ToString(); } public static void Verify(string expectedOperationTree, string actualOperationTree) { char[] newLineChars = Environment.NewLine.ToCharArray(); string actual = actualOperationTree.Trim(newLineChars); actual = actual.Replace(" \n", "\n").Replace(" \r", "\r"); expectedOperationTree = expectedOperationTree.Trim(newLineChars); expectedOperationTree = expectedOperationTree.Replace("\r\n", "\n").Replace(" \n", "\n").Replace("\n", Environment.NewLine); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedOperationTree, actual); } #region Logging helpers private void LogPatternPropertiesAndNewLine(IPatternOperation operation) { LogPatternProperties(operation); LogString(")"); LogNewLine(); } private void LogPatternProperties(IPatternOperation operation) { LogCommonProperties(operation); LogString(" ("); LogType(operation.InputType, $"{nameof(operation.InputType)}"); LogString(", "); LogType(operation.NarrowedType, $"{nameof(operation.NarrowedType)}"); } private void LogCommonPropertiesAndNewLine(IOperation operation) { LogCommonProperties(operation); LogNewLine(); } private void LogCommonProperties(IOperation operation) { LogString(" ("); // Kind LogString($"{nameof(OperationKind)}.{GetKindText(operation.Kind)}"); // Type LogString(", "); LogType(operation.Type); // ConstantValue if (operation.ConstantValue.HasValue) { LogString(", "); LogConstant(operation.ConstantValue); } // IsInvalid if (operation.HasErrors(_compilation)) { LogString(", IsInvalid"); } // IsImplicit if (operation.IsImplicit) { LogString(", IsImplicit"); } LogString(")"); // Syntax Assert.NotNull(operation.Syntax); LogString($" (Syntax: {GetSnippetFromSyntax(operation.Syntax)})"); // Some of these kinds were inconsistent in the first release, and in standardizing them the // string output isn't guaranteed to be one or the other. So standardize manually. string GetKindText(OperationKind kind) { switch (kind) { case OperationKind.Unary: return "Unary"; case OperationKind.Binary: return "Binary"; case OperationKind.TupleBinary: return "TupleBinary"; case OperationKind.MethodBody: return "MethodBody"; case OperationKind.ConstructorBody: return "ConstructorBody"; default: return kind.ToString(); } } } private static string GetSnippetFromSyntax(SyntaxNode syntax) { if (syntax == null) { return "null"; } var text = syntax.ToString().Trim(Environment.NewLine.ToCharArray()); var lines = text.Split(new[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).ToArray(); if (lines.Length <= 1 && text.Length < 25) { return $"'{text}'"; } const int maxTokenLength = 11; var firstLine = lines[0]; var lastLine = lines[lines.Length - 1]; var prefix = firstLine.Length <= maxTokenLength ? firstLine : firstLine.Substring(0, maxTokenLength); var suffix = lastLine.Length <= maxTokenLength ? lastLine : lastLine.Substring(lastLine.Length - maxTokenLength, maxTokenLength); return $"'{prefix} ... {suffix}'"; } private static bool ShouldLogType(IOperation operation) { var operationKind = (int)operation.Kind; // Expressions if (operationKind >= 0x100 && operationKind < 0x400) { return true; } return false; } protected void LogString(string str) { if (_pendingIndent) { str = _currentIndent + str; _pendingIndent = false; } _builder.Append(str); } protected void LogNewLine() { LogString(Environment.NewLine); _pendingIndent = true; } private void Indent() { _currentIndent += indent; } private void Unindent() { _currentIndent = _currentIndent.Substring(indent.Length); } private void LogConstant(Optional<object> constant, string header = "Constant") { if (constant.HasValue) { LogConstant(constant.Value, header); } } private static string ConstantToString(object constant) { switch (constant) { case null: return "null"; case string s: s = s.Replace("\"", "\"\""); return @"""" + s + @""""; case IFormattable formattable: return formattable.ToString(null, CultureInfo.InvariantCulture).Replace("\"", "\"\""); default: return constant.ToString().Replace("\"", "\"\""); } } private void LogConstant(object constant, string header = "Constant") { string valueStr = ConstantToString(constant); LogString($"{header}: {valueStr}"); } private void LogConversion(CommonConversion conversion, string header = "Conversion") { var exists = FormatBoolProperty(nameof(conversion.Exists), conversion.Exists); var isIdentity = FormatBoolProperty(nameof(conversion.IsIdentity), conversion.IsIdentity); var isNumeric = FormatBoolProperty(nameof(conversion.IsNumeric), conversion.IsNumeric); var isReference = FormatBoolProperty(nameof(conversion.IsReference), conversion.IsReference); var isUserDefined = FormatBoolProperty(nameof(conversion.IsUserDefined), conversion.IsUserDefined); LogString($"{header}: {nameof(CommonConversion)} ({exists}, {isIdentity}, {isNumeric}, {isReference}, {isUserDefined}) ("); LogSymbol(conversion.MethodSymbol, nameof(conversion.MethodSymbol)); LogString(")"); } private void LogSymbol(ISymbol symbol, string header, bool logDisplayString = true) { if (!string.IsNullOrEmpty(header)) { LogString($"{header}: "); } var symbolStr = symbol != null ? (logDisplayString ? symbol.ToTestDisplayString() : symbol.Name) : "null"; LogString($"{symbolStr}"); } private void LogType(ITypeSymbol type, string header = "Type") { var typeStr = type != null ? type.ToTestDisplayString() : "null"; LogString($"{header}: {typeStr}"); } private uint GetLabelId(ILabelSymbol symbol) { if (_labelIdMap.ContainsKey(symbol)) { return _labelIdMap[symbol]; } var id = _currentLabelId++; _labelIdMap[symbol] = id; return id; } private static string FormatBoolProperty(string propertyName, bool value) => $"{propertyName}: {(value ? "True" : "False")}"; #endregion #region Visit methods public override void Visit(IOperation operation) { if (operation == null) { Indent(); LogString("null"); LogNewLine(); Unindent(); return; } if (!operation.IsImplicit) { try { _explicitNodeMap.Add(operation.Syntax, operation); } catch (ArgumentException) { Assert.False(true, $"Duplicate explicit node for syntax ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}"); } } Assert.True(operation.Type == null || !operation.MustHaveNullType(), $"Unexpected non-null type: {operation.Type}"); if (operation != _root) { Indent(); } base.Visit(operation); if (operation != _root) { Unindent(); } Assert.True(operation.Syntax.Language == operation.Language); } private void Visit(IOperation operation, string header) { Debug.Assert(!string.IsNullOrEmpty(header)); Indent(); LogString($"{header}: "); LogNewLine(); Visit(operation); Unindent(); } private void VisitArrayCommon<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault, Action<T> arrayElementVisitor) { Debug.Assert(!string.IsNullOrEmpty(header)); Indent(); if (!list.IsDefaultOrEmpty) { var elementCount = logElementCount ? $"({list.Count()})" : string.Empty; LogString($"{header}{elementCount}:"); LogNewLine(); Indent(); foreach (var element in list) { arrayElementVisitor(element); } Unindent(); } else { var suffix = logNullForDefault && list.IsDefault ? ": null" : "(0)"; LogString($"{header}{suffix}"); LogNewLine(); } Unindent(); } internal void VisitSymbolArrayElement(ISymbol element) { LogSymbol(element, header: "Symbol"); LogNewLine(); } internal void VisitStringArrayElement(string element) { var valueStr = element != null ? element.ToString() : "null"; valueStr = @"""" + valueStr + @""""; LogString(valueStr); LogNewLine(); } internal void VisitRefKindArrayElement(RefKind element) { LogString(element.ToString()); LogNewLine(); } private void VisitChildren(IOperation operation) { Debug.Assert(operation.Children.All(o => o != null)); var children = operation.Children.ToImmutableArray(); if (!children.IsEmpty || operation.Kind != OperationKind.None) { VisitArray(children, "Children", logElementCount: true); } } private void VisitArray<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault = false) where T : IOperation { VisitArrayCommon(list, header, logElementCount, logNullForDefault, o => Visit(o)); } private void VisitArray(ImmutableArray<ISymbol> list, string header, bool logElementCount, bool logNullForDefault = false) { VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitSymbolArrayElement); } private void VisitArray(ImmutableArray<string> list, string header, bool logElementCount, bool logNullForDefault = false) { VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitStringArrayElement); } private void VisitArray(ImmutableArray<RefKind> list, string header, bool logElementCount, bool logNullForDefault = false) { VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitRefKindArrayElement); } private void VisitInstance(IOperation instance) { Visit(instance, header: "Instance Receiver"); } internal override void VisitNoneOperation(IOperation operation) { LogString("IOperation: "); LogCommonPropertiesAndNewLine(operation); VisitChildren(operation); } public override void VisitBlock(IBlockOperation operation) { LogString(nameof(IBlockOperation)); var statementsStr = $"{operation.Operations.Length} statements"; var localStr = !operation.Locals.IsEmpty ? $", {operation.Locals.Length} locals" : string.Empty; LogString($" ({statementsStr}{localStr})"); LogCommonPropertiesAndNewLine(operation); if (operation.Operations.IsEmpty) { return; } LogLocals(operation.Locals); base.VisitBlock(operation); } public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) { var variablesCountStr = $"{operation.Declarations.Length} declarations"; LogString($"{nameof(IVariableDeclarationGroupOperation)} ({variablesCountStr})"); LogCommonPropertiesAndNewLine(operation); base.VisitVariableDeclarationGroup(operation); } public override void VisitUsingDeclaration(IUsingDeclarationOperation operation) { LogString($"{nameof(IUsingDeclarationOperation)}"); LogString($"(IsAsynchronous: {operation.IsAsynchronous}"); var disposeMethod = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod; if (disposeMethod is object) { LogSymbol(disposeMethod, ", DisposeMethod"); } LogString(")"); LogCommonPropertiesAndNewLine(operation); Visit(operation.DeclarationGroup, "DeclarationGroup"); var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { VisitArray(disposeArgs, "DisposeArguments", logElementCount: true); } } public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { LogString($"{nameof(IVariableDeclaratorOperation)} ("); LogSymbol(operation.Symbol, "Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Initializer, "Initializer"); if (!operation.IgnoredArguments.IsEmpty) { VisitArray(operation.IgnoredArguments, "IgnoredArguments", logElementCount: true); } } public override void VisitVariableDeclaration(IVariableDeclarationOperation operation) { var variableCount = operation.Declarators.Length; LogString($"{nameof(IVariableDeclarationOperation)} ({variableCount} declarators)"); LogCommonPropertiesAndNewLine(operation); if (!operation.IgnoredDimensions.IsEmpty) { VisitArray(operation.IgnoredDimensions, "Ignored Dimensions", true); } VisitArray(operation.Declarators, "Declarators", false); Visit(operation.Initializer, "Initializer"); } public override void VisitSwitch(ISwitchOperation operation) { var caseCountStr = $"{operation.Cases.Length} cases"; var exitLabelStr = $", Exit Label Id: {GetLabelId(operation.ExitLabel)}"; LogString($"{nameof(ISwitchOperation)} ({caseCountStr}{exitLabelStr})"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, header: "Switch expression"); LogLocals(operation.Locals); foreach (ISwitchCaseOperation section in operation.Cases) { foreach (ICaseClauseOperation c in section.Clauses) { if (c.Label != null) { GetLabelId(c.Label); } } } VisitArray(operation.Cases, "Sections", logElementCount: false); } public override void VisitSwitchCase(ISwitchCaseOperation operation) { var caseClauseCountStr = $"{operation.Clauses.Length} case clauses"; var statementCountStr = $"{operation.Body.Length} statements"; LogString($"{nameof(ISwitchCaseOperation)} ({caseClauseCountStr}, {statementCountStr})"); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Indent(); VisitArray(operation.Clauses, "Clauses", logElementCount: false); VisitArray(operation.Body, "Body", logElementCount: false); Unindent(); _ = ((SwitchCaseOperation)operation).Condition; } public override void VisitWhileLoop(IWhileLoopOperation operation) { LogString(nameof(IWhileLoopOperation)); LogString($" (ConditionIsTop: {operation.ConditionIsTop}, ConditionIsUntil: {operation.ConditionIsUntil})"); LogLoopStatementHeader(operation); Visit(operation.Condition, "Condition"); Visit(operation.Body, "Body"); Visit(operation.IgnoredCondition, "IgnoredCondition"); } public override void VisitForLoop(IForLoopOperation operation) { LogString(nameof(IForLoopOperation)); LogLoopStatementHeader(operation); LogLocals(operation.ConditionLocals, header: nameof(operation.ConditionLocals)); Visit(operation.Condition, "Condition"); VisitArray(operation.Before, "Before", logElementCount: false); VisitArray(operation.AtLoopBottom, "AtLoopBottom", logElementCount: false); Visit(operation.Body, "Body"); } public override void VisitForToLoop(IForToLoopOperation operation) { LogString(nameof(IForToLoopOperation)); LogLoopStatementHeader(operation, operation.IsChecked); Visit(operation.LoopControlVariable, "LoopControlVariable"); Visit(operation.InitialValue, "InitialValue"); Visit(operation.LimitValue, "LimitValue"); Visit(operation.StepValue, "StepValue"); Visit(operation.Body, "Body"); VisitArray(operation.NextVariables, "NextVariables", logElementCount: true); (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; if (userDefinedInfo != null) { _ = userDefinedInfo.Addition; _ = userDefinedInfo.Subtraction; _ = userDefinedInfo.LessThanOrEqual; _ = userDefinedInfo.GreaterThanOrEqual; } } private void LogLocals(IEnumerable<ILocalSymbol> locals, string header = "Locals") { if (!locals.Any()) { return; } Indent(); LogString($"{header}: "); Indent(); int localIndex = 1; foreach (var local in locals) { LogSymbol(local, header: $"Local_{localIndex++}"); LogNewLine(); } Unindent(); Unindent(); } private void LogLoopStatementHeader(ILoopOperation operation, bool? isChecked = null) { Assert.Equal(OperationKind.Loop, operation.Kind); var propertyStringBuilder = new StringBuilder(); propertyStringBuilder.Append(" ("); propertyStringBuilder.Append($"{nameof(LoopKind)}.{operation.LoopKind}"); if (operation is IForEachLoopOperation { IsAsynchronous: true }) { propertyStringBuilder.Append($", IsAsynchronous"); } propertyStringBuilder.Append($", Continue Label Id: {GetLabelId(operation.ContinueLabel)}"); propertyStringBuilder.Append($", Exit Label Id: {GetLabelId(operation.ExitLabel)}"); if (isChecked.GetValueOrDefault()) { propertyStringBuilder.Append($", Checked"); } propertyStringBuilder.Append(")"); LogString(propertyStringBuilder.ToString()); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); } public override void VisitForEachLoop(IForEachLoopOperation operation) { LogString(nameof(IForEachLoopOperation)); LogLoopStatementHeader(operation); Assert.NotNull(operation.LoopControlVariable); Visit(operation.LoopControlVariable, "LoopControlVariable"); Visit(operation.Collection, "Collection"); Visit(operation.Body, "Body"); VisitArray(operation.NextVariables, "NextVariables", logElementCount: true); ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; } public override void VisitLabeled(ILabeledOperation operation) { LogString(nameof(ILabeledOperation)); if (!operation.Label.IsImplicitlyDeclared) { LogString($" (Label: {operation.Label.Name})"); } else { LogString($" (Label Id: {GetLabelId(operation.Label)})"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Statement"); } public override void VisitBranch(IBranchOperation operation) { LogString(nameof(IBranchOperation)); var kindStr = $"{nameof(BranchKind)}.{operation.BranchKind}"; // If the label is implicit, or if it has been assigned an id (such as VB Exit Do/While/Switch labels) then print the id, instead of the name. var labelStr = !(operation.Target.IsImplicitlyDeclared || _labelIdMap.ContainsKey(operation.Target)) ? $", Label: {operation.Target.Name}" : $", Label Id: {GetLabelId(operation.Target)}"; LogString($" ({kindStr}{labelStr})"); LogCommonPropertiesAndNewLine(operation); base.VisitBranch(operation); } public override void VisitEmpty(IEmptyOperation operation) { LogString(nameof(IEmptyOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitReturn(IReturnOperation operation) { LogString(nameof(IReturnOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.ReturnedValue, "ReturnedValue"); } public override void VisitLock(ILockOperation operation) { LogString(nameof(ILockOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.LockedValue, "Expression"); Visit(operation.Body, "Body"); } public override void VisitTry(ITryOperation operation) { LogString(nameof(ITryOperation)); if (operation.ExitLabel != null) { LogString($" (Exit Label Id: {GetLabelId(operation.ExitLabel)})"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.Body, "Body"); VisitArray(operation.Catches, "Catch clauses", logElementCount: true); Visit(operation.Finally, "Finally"); } public override void VisitCatchClause(ICatchClauseOperation operation) { LogString(nameof(ICatchClauseOperation)); var exceptionTypeStr = operation.ExceptionType != null ? operation.ExceptionType.ToTestDisplayString() : "null"; LogString($" (Exception type: {exceptionTypeStr})"); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Visit(operation.ExceptionDeclarationOrExpression, "ExceptionDeclarationOrExpression"); Visit(operation.Filter, "Filter"); Visit(operation.Handler, "Handler"); } public override void VisitUsing(IUsingOperation operation) { LogString(nameof(IUsingOperation)); if (operation.IsAsynchronous) { LogString($" (IsAsynchronous)"); } var disposeMethod = ((UsingOperation)operation).DisposeInfo.DisposeMethod; if (disposeMethod is object) { LogSymbol(disposeMethod, " (DisposeMethod"); LogString(")"); } LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Visit(operation.Resources, "Resources"); Visit(operation.Body, "Body"); Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind); Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind); var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { VisitArray(disposeArgs, "DisposeArguments", logElementCount: true); } } // https://github.com/dotnet/roslyn/issues/21281 internal override void VisitFixed(IFixedOperation operation) { LogString(nameof(IFixedOperation)); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Visit(operation.Variables, "Declaration"); Visit(operation.Body, "Body"); } internal override void VisitAggregateQuery(IAggregateQueryOperation operation) { LogString(nameof(IAggregateQueryOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Group, "Group"); Visit(operation.Aggregation, "Aggregation"); } public override void VisitExpressionStatement(IExpressionStatementOperation operation) { LogString(nameof(IExpressionStatementOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); } internal override void VisitWithStatement(IWithStatementOperation operation) { LogString(nameof(IWithStatementOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, "Value"); Visit(operation.Body, "Body"); } public override void VisitStop(IStopOperation operation) { LogString(nameof(IStopOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitEnd(IEndOperation operation) { LogString(nameof(IEndOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitInvocation(IInvocationOperation operation) { LogString(nameof(IInvocationOperation)); var isVirtualStr = operation.IsVirtual ? "virtual " : string.Empty; var spacing = !operation.IsVirtual && operation.Instance != null ? " " : string.Empty; LogString($" ({isVirtualStr}{spacing}"); LogSymbol(operation.TargetMethod, header: string.Empty); LogString(")"); LogCommonPropertiesAndNewLine(operation); VisitInstance(operation.Instance); VisitArguments(operation.Arguments); } private void VisitArguments(ImmutableArray<IArgumentOperation> arguments) { VisitArray(arguments, "Arguments", logElementCount: true); } private void VisitDynamicArguments(HasDynamicArgumentsExpression operation) { VisitArray(operation.Arguments, "Arguments", logElementCount: true); VisitArray(operation.ArgumentNames, "ArgumentNames", logElementCount: true); VisitArray(operation.ArgumentRefKinds, "ArgumentRefKinds", logElementCount: true, logNullForDefault: true); VerifyGetArgumentNamePublicApi(operation, operation.ArgumentNames); VerifyGetArgumentRefKindPublicApi(operation, operation.ArgumentRefKinds); } private static void VerifyGetArgumentNamePublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<string> argumentNames) { var length = operation.Arguments.Length; if (argumentNames.IsDefaultOrEmpty) { for (int i = 0; i < length; i++) { Assert.Null(operation.GetArgumentName(i)); } } else { Assert.Equal(length, argumentNames.Length); for (var i = 0; i < length; i++) { Assert.Equal(argumentNames[i], operation.GetArgumentName(i)); } } } private static void VerifyGetArgumentRefKindPublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<RefKind> argumentRefKinds) { var length = operation.Arguments.Length; if (argumentRefKinds.IsDefault) { for (int i = 0; i < length; i++) { Assert.Null(operation.GetArgumentRefKind(i)); } } else if (argumentRefKinds.IsEmpty) { for (int i = 0; i < length; i++) { Assert.Equal(RefKind.None, operation.GetArgumentRefKind(i)); } } else { Assert.Equal(length, argumentRefKinds.Length); for (var i = 0; i < length; i++) { Assert.Equal(argumentRefKinds[i], operation.GetArgumentRefKind(i)); } } } public override void VisitArgument(IArgumentOperation operation) { LogString($"{nameof(IArgumentOperation)} ("); LogString($"{nameof(ArgumentKind)}.{operation.ArgumentKind}, "); LogSymbol(operation.Parameter, header: "Matching Parameter", logDisplayString: false); LogString(")"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value); Indent(); LogConversion(operation.InConversion, "InConversion"); LogNewLine(); LogConversion(operation.OutConversion, "OutConversion"); LogNewLine(); Unindent(); } public override void VisitOmittedArgument(IOmittedArgumentOperation operation) { LogString(nameof(IOmittedArgumentOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitArrayElementReference(IArrayElementReferenceOperation operation) { LogString(nameof(IArrayElementReferenceOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.ArrayReference, "Array reference"); VisitArray(operation.Indices, "Indices", logElementCount: true); } internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) { LogString(nameof(IPointerIndirectionReferenceOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Pointer, "Pointer"); } public override void VisitLocalReference(ILocalReferenceOperation operation) { LogString(nameof(ILocalReferenceOperation)); LogString($": {operation.Local.Name}"); if (operation.IsDeclaration) { LogString($" (IsDeclaration: {operation.IsDeclaration})"); } LogCommonPropertiesAndNewLine(operation); } public override void VisitFlowCapture(IFlowCaptureOperation operation) { LogString(nameof(IFlowCaptureOperation)); LogString($": {operation.Id.Value}"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, "Value"); TestOperationVisitor.Singleton.VisitFlowCapture(operation); } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { LogString(nameof(IFlowCaptureReferenceOperation)); LogString($": {operation.Id.Value}"); LogCommonPropertiesAndNewLine(operation); } public override void VisitIsNull(IIsNullOperation operation) { LogString(nameof(IIsNullOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); } public override void VisitCaughtException(ICaughtExceptionOperation operation) { LogString(nameof(ICaughtExceptionOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitParameterReference(IParameterReferenceOperation operation) { LogString(nameof(IParameterReferenceOperation)); LogString($": {operation.Parameter.Name}"); LogCommonPropertiesAndNewLine(operation); } public override void VisitInstanceReference(IInstanceReferenceOperation operation) { LogString(nameof(IInstanceReferenceOperation)); LogString($" (ReferenceKind: {operation.ReferenceKind})"); LogCommonPropertiesAndNewLine(operation); if (operation.IsImplicit) { if (operation.Parent is IMemberReferenceOperation memberReference && memberReference.Instance == operation) { Assert.False(memberReference.Member.IsStatic && !operation.HasErrors(this._compilation)); } else if (operation.Parent is IInvocationOperation invocation && invocation.Instance == operation) { Assert.False(invocation.TargetMethod.IsStatic); } } } private void VisitMemberReferenceExpressionCommon(IMemberReferenceOperation operation) { if (operation.Member.IsStatic) { LogString(" (Static)"); } LogCommonPropertiesAndNewLine(operation); VisitInstance(operation.Instance); } public override void VisitFieldReference(IFieldReferenceOperation operation) { LogString(nameof(IFieldReferenceOperation)); LogString($": {operation.Field.ToTestDisplayString()}"); if (operation.IsDeclaration) { LogString($" (IsDeclaration: {operation.IsDeclaration})"); } VisitMemberReferenceExpressionCommon(operation); } public override void VisitMethodReference(IMethodReferenceOperation operation) { LogString(nameof(IMethodReferenceOperation)); LogString($": {operation.Method.ToTestDisplayString()}"); if (operation.IsVirtual) { LogString(" (IsVirtual)"); } Assert.Null(operation.Type); VisitMemberReferenceExpressionCommon(operation); } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { LogString(nameof(IPropertyReferenceOperation)); LogString($": {operation.Property.ToTestDisplayString()}"); VisitMemberReferenceExpressionCommon(operation); if (operation.Arguments.Length > 0) { VisitArguments(operation.Arguments); } } public override void VisitEventReference(IEventReferenceOperation operation) { LogString(nameof(IEventReferenceOperation)); LogString($": {operation.Event.ToTestDisplayString()}"); VisitMemberReferenceExpressionCommon(operation); } public override void VisitEventAssignment(IEventAssignmentOperation operation) { var kindStr = operation.Adds ? "EventAdd" : "EventRemove"; LogString($"{nameof(IEventAssignmentOperation)} ({kindStr})"); LogCommonPropertiesAndNewLine(operation); Assert.NotNull(operation.EventReference); Visit(operation.EventReference, header: "Event Reference"); Visit(operation.HandlerValue, header: "Handler"); } public override void VisitConditionalAccess(IConditionalAccessOperation operation) { LogString(nameof(IConditionalAccessOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, header: nameof(operation.Operation)); Visit(operation.WhenNotNull, header: nameof(operation.WhenNotNull)); Assert.NotNull(operation.Type); } public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) { LogString(nameof(IConditionalAccessInstanceOperation)); LogCommonPropertiesAndNewLine(operation); } internal override void VisitPlaceholder(IPlaceholderOperation operation) { LogString(nameof(IPlaceholderOperation)); LogCommonPropertiesAndNewLine(operation); Assert.Equal(PlaceholderKind.AggregationGroup, operation.PlaceholderKind); } public override void VisitUnaryOperator(IUnaryOperation operation) { LogString(nameof(IUnaryOperation)); var kindStr = $"{nameof(UnaryOperatorKind)}.{operation.OperatorKind}"; if (operation.IsLifted) { kindStr += ", IsLifted"; } if (operation.IsChecked) { kindStr += ", Checked"; } LogString($" ({kindStr})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); } public override void VisitBinaryOperator(IBinaryOperation operation) { LogString(nameof(IBinaryOperation)); var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}"; if (operation.IsLifted) { kindStr += ", IsLifted"; } if (operation.IsChecked) { kindStr += ", Checked"; } if (operation.IsCompareText) { kindStr += ", CompareText"; } LogString($" ({kindStr})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod; LogCommonPropertiesAndNewLine(operation); Visit(operation.LeftOperand, "Left"); Visit(operation.RightOperand, "Right"); } public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation) { LogString(nameof(ITupleBinaryOperation)); var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}"; LogString($" ({kindStr})"); LogCommonPropertiesAndNewLine(operation); Visit(operation.LeftOperand, "Left"); Visit(operation.RightOperand, "Right"); } private void LogHasOperatorMethodExpressionCommon(IMethodSymbol operatorMethodOpt) { if (operatorMethodOpt != null) { LogSymbol(operatorMethodOpt, header: " (OperatorMethod"); LogString(")"); } } public override void VisitConversion(IConversionOperation operation) { LogString(nameof(IConversionOperation)); var isTryCast = $"TryCast: {(operation.IsTryCast ? "True" : "False")}"; var isChecked = operation.IsChecked ? "Checked" : "Unchecked"; LogString($" ({isTryCast}, {isChecked})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); LogCommonPropertiesAndNewLine(operation); Indent(); LogConversion(operation.Conversion); if (((Operation)operation).OwningSemanticModel == null) { LogNewLine(); Indent(); LogString($"({((ConversionOperation)operation).ConversionConvertible})"); Unindent(); } Unindent(); LogNewLine(); Visit(operation.Operand, "Operand"); } public override void VisitConditional(IConditionalOperation operation) { LogString(nameof(IConditionalOperation)); if (operation.IsRef) { LogString(" (IsRef)"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.Condition, "Condition"); Visit(operation.WhenTrue, "WhenTrue"); Visit(operation.WhenFalse, "WhenFalse"); } public override void VisitCoalesce(ICoalesceOperation operation) { LogString(nameof(ICoalesceOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, "Expression"); Indent(); LogConversion(operation.ValueConversion, "ValueConversion"); LogNewLine(); Indent(); LogString($"({((CoalesceOperation)operation).ValueConversionConvertible})"); Unindent(); LogNewLine(); Unindent(); Visit(operation.WhenNull, "WhenNull"); } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { LogString(nameof(ICoalesceAssignmentOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, nameof(operation.Target)); Visit(operation.Value, nameof(operation.Value)); } public override void VisitIsType(IIsTypeOperation operation) { LogString(nameof(IIsTypeOperation)); if (operation.IsNegated) { LogString(" (IsNotExpression)"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.ValueOperand, "Operand"); Indent(); LogType(operation.TypeOperand, "IsType"); LogNewLine(); Unindent(); } public override void VisitSizeOf(ISizeOfOperation operation) { LogString(nameof(ISizeOfOperation)); LogCommonPropertiesAndNewLine(operation); Indent(); LogType(operation.TypeOperand, "TypeOperand"); LogNewLine(); Unindent(); } public override void VisitTypeOf(ITypeOfOperation operation) { LogString(nameof(ITypeOfOperation)); LogCommonPropertiesAndNewLine(operation); Indent(); LogType(operation.TypeOperand, "TypeOperand"); LogNewLine(); Unindent(); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { LogString(nameof(IAnonymousFunctionOperation)); // For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart. // That is how symbol display is implemented for C#. // https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output. LogSymbol(operation.Symbol, header: " (Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); base.VisitAnonymousFunction(operation); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { LogString(nameof(IFlowAnonymousFunctionOperation)); // For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart. // That is how symbol display is implemented for C#. // https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output. LogSymbol(operation.Symbol, header: " (Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); base.VisitFlowAnonymousFunction(operation); } public override void VisitDelegateCreation(IDelegateCreationOperation operation) { LogString(nameof(IDelegateCreationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, nameof(operation.Target)); } public override void VisitLiteral(ILiteralOperation operation) { LogString(nameof(ILiteralOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitAwait(IAwaitOperation operation) { LogString(nameof(IAwaitOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); } public override void VisitNameOf(INameOfOperation operation) { LogString(nameof(INameOfOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Argument); } public override void VisitThrow(IThrowOperation operation) { LogString(nameof(IThrowOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Exception); } public override void VisitAddressOf(IAddressOfOperation operation) { LogString(nameof(IAddressOfOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Reference, "Reference"); } public override void VisitObjectCreation(IObjectCreationOperation operation) { LogString(nameof(IObjectCreationOperation)); LogString($" (Constructor: {operation.Constructor?.ToTestDisplayString() ?? "<null>"})"); LogCommonPropertiesAndNewLine(operation); VisitArguments(operation.Arguments); Visit(operation.Initializer, "Initializer"); } public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) { LogString(nameof(IAnonymousObjectCreationOperation)); LogCommonPropertiesAndNewLine(operation); foreach (var initializer in operation.Initializers) { var simpleAssignment = (ISimpleAssignmentOperation)initializer; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Assert.Empty(propertyReference.Arguments); Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind); Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind); } VisitArray(operation.Initializers, "Initializers", logElementCount: true); } public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) { LogString(nameof(IDynamicObjectCreationOperation)); LogCommonPropertiesAndNewLine(operation); VisitDynamicArguments((HasDynamicArgumentsExpression)operation); Visit(operation.Initializer, "Initializer"); } public override void VisitDynamicInvocation(IDynamicInvocationOperation operation) { LogString(nameof(IDynamicInvocationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); VisitDynamicArguments((HasDynamicArgumentsExpression)operation); } public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) { LogString(nameof(IDynamicIndexerAccessOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); VisitDynamicArguments((HasDynamicArgumentsExpression)operation); } public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) { LogString(nameof(IObjectOrCollectionInitializerOperation)); LogCommonPropertiesAndNewLine(operation); VisitArray(operation.Initializers, "Initializers", logElementCount: true); } public override void VisitMemberInitializer(IMemberInitializerOperation operation) { LogString(nameof(IMemberInitializerOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.InitializedMember, "InitializedMember"); Visit(operation.Initializer, "Initializer"); } [Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", error: true)] public override void VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation) { // Kept to ensure that it's never called, as we can't override DefaultVisit in this visitor throw ExceptionUtilities.Unreachable; } public override void VisitFieldInitializer(IFieldInitializerOperation operation) { LogString(nameof(IFieldInitializerOperation)); if (operation.InitializedFields.Length <= 1) { if (operation.InitializedFields.Length == 1) { LogSymbol(operation.InitializedFields[0], header: " (Field"); LogString(")"); } LogCommonPropertiesAndNewLine(operation); } else { LogString($" ({operation.InitializedFields.Length} initialized fields)"); LogCommonPropertiesAndNewLine(operation); Indent(); int index = 1; foreach (var local in operation.InitializedFields) { LogSymbol(local, header: $"Field_{index++}"); LogNewLine(); } Unindent(); } LogLocals(operation.Locals); base.VisitFieldInitializer(operation); } public override void VisitVariableInitializer(IVariableInitializerOperation operation) { LogString(nameof(IVariableInitializerOperation)); LogCommonPropertiesAndNewLine(operation); Assert.Empty(operation.Locals); base.VisitVariableInitializer(operation); } public override void VisitPropertyInitializer(IPropertyInitializerOperation operation) { LogString(nameof(IPropertyInitializerOperation)); if (operation.InitializedProperties.Length <= 1) { if (operation.InitializedProperties.Length == 1) { LogSymbol(operation.InitializedProperties[0], header: " (Property"); LogString(")"); } LogCommonPropertiesAndNewLine(operation); } else { LogString($" ({operation.InitializedProperties.Length} initialized properties)"); LogCommonPropertiesAndNewLine(operation); Indent(); int index = 1; foreach (var property in operation.InitializedProperties) { LogSymbol(property, header: $"Property_{index++}"); LogNewLine(); } Unindent(); } LogLocals(operation.Locals); base.VisitPropertyInitializer(operation); } public override void VisitParameterInitializer(IParameterInitializerOperation operation) { LogString(nameof(IParameterInitializerOperation)); LogSymbol(operation.Parameter, header: " (Parameter"); LogString(")"); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); base.VisitParameterInitializer(operation); } public override void VisitArrayCreation(IArrayCreationOperation operation) { LogString(nameof(IArrayCreationOperation)); LogCommonPropertiesAndNewLine(operation); VisitArray(operation.DimensionSizes, "Dimension Sizes", logElementCount: true); Visit(operation.Initializer, "Initializer"); } public override void VisitArrayInitializer(IArrayInitializerOperation operation) { LogString(nameof(IArrayInitializerOperation)); LogString($" ({operation.ElementValues.Length} elements)"); LogCommonPropertiesAndNewLine(operation); Assert.Null(operation.Type); VisitArray(operation.ElementValues, "Element Values", logElementCount: true); } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { LogString(nameof(ISimpleAssignmentOperation)); if (operation.IsRef) { LogString(" (IsRef)"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, "Left"); Visit(operation.Value, "Right"); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { LogString(nameof(IDeconstructionAssignmentOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, "Left"); Visit(operation.Value, "Right"); } public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation) { LogString(nameof(IDeclarationExpressionOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Expression); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { LogString(nameof(ICompoundAssignmentOperation)); var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}"; if (operation.IsLifted) { kindStr += ", IsLifted"; } if (operation.IsChecked) { kindStr += ", Checked"; } LogString($" ({kindStr})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); LogCommonPropertiesAndNewLine(operation); Indent(); LogConversion(operation.InConversion, "InConversion"); LogNewLine(); LogConversion(operation.OutConversion, "OutConversion"); LogNewLine(); Unindent(); Visit(operation.Target, "Left"); Visit(operation.Value, "Right"); } public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) { LogString(nameof(IIncrementOrDecrementOperation)); var kindStr = operation.IsPostfix ? "Postfix" : "Prefix"; if (operation.IsLifted) { kindStr += ", IsLifted"; } if (operation.IsChecked) { kindStr += ", Checked"; } LogString($" ({kindStr})"); LogHasOperatorMethodExpressionCommon(operation.OperatorMethod); LogCommonPropertiesAndNewLine(operation); Visit(operation.Target, "Target"); } public override void VisitParenthesized(IParenthesizedOperation operation) { LogString(nameof(IParenthesizedOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); } public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) { LogString(nameof(IDynamicMemberReferenceOperation)); // (Member Name: "quoted name", Containing Type: type) LogString(" ("); LogConstant((object)operation.MemberName, "Member Name"); LogString(", "); LogType(operation.ContainingType, "Containing Type"); LogString(")"); LogCommonPropertiesAndNewLine(operation); VisitArrayCommon(operation.TypeArguments, "Type Arguments", logElementCount: true, logNullForDefault: false, arrayElementVisitor: VisitSymbolArrayElement); VisitInstance(operation.Instance); } public override void VisitDefaultValue(IDefaultValueOperation operation) { LogString(nameof(IDefaultValueOperation)); LogCommonPropertiesAndNewLine(operation); } public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) { LogString(nameof(ITypeParameterObjectCreationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Initializer, "Initializer"); } internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) { LogString(nameof(INoPiaObjectCreationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Initializer, "Initializer"); } public override void VisitInvalid(IInvalidOperation operation) { LogString(nameof(IInvalidOperation)); LogCommonPropertiesAndNewLine(operation); VisitChildren(operation); } public override void VisitLocalFunction(ILocalFunctionOperation operation) { LogString(nameof(ILocalFunctionOperation)); LogSymbol(operation.Symbol, header: " (Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); if (operation.Body != null) { if (operation.IgnoredBody != null) { Visit(operation.Body, "Body"); Visit(operation.IgnoredBody, "IgnoredBody"); } else { Visit(operation.Body); } } else { Assert.Null(operation.IgnoredBody); } } private void LogCaseClauseCommon(ICaseClauseOperation operation) { Assert.Equal(OperationKind.CaseClause, operation.Kind); if (operation.Label != null) { LogString($" (Label Id: {GetLabelId(operation.Label)})"); } var kindStr = $"{nameof(CaseKind)}.{operation.CaseKind}"; LogString($" ({kindStr})"); LogCommonPropertiesAndNewLine(operation); } public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) { LogString(nameof(ISingleValueCaseClauseOperation)); LogCaseClauseCommon(operation); Visit(operation.Value, "Value"); } public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) { LogString(nameof(IRelationalCaseClauseOperation)); var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.Relation}"; LogString($" (Relational operator kind: {kindStr})"); LogCaseClauseCommon(operation); Visit(operation.Value, "Value"); } public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation) { LogString(nameof(IRangeCaseClauseOperation)); LogCaseClauseCommon(operation); Visit(operation.MinimumValue, "Min"); Visit(operation.MaximumValue, "Max"); } public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) { LogString(nameof(IDefaultCaseClauseOperation)); LogCaseClauseCommon(operation); } public override void VisitTuple(ITupleOperation operation) { LogString(nameof(ITupleOperation)); LogCommonPropertiesAndNewLine(operation); Indent(); LogType(operation.NaturalType, nameof(operation.NaturalType)); LogNewLine(); Unindent(); VisitArray(operation.Elements, "Elements", logElementCount: true); } public override void VisitInterpolatedString(IInterpolatedStringOperation operation) { LogString(nameof(IInterpolatedStringOperation)); LogCommonPropertiesAndNewLine(operation); VisitArray(operation.Parts, "Parts", logElementCount: true); } public override void VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation) { LogString(nameof(IInterpolatedStringHandlerCreationOperation)); LogString($" (HandlerAppendCallsReturnBool: {operation.HandlerAppendCallsReturnBool}, HandlerCreationHasSuccessParameter: {operation.HandlerCreationHasSuccessParameter})"); LogCommonPropertiesAndNewLine(operation); Visit(operation.HandlerCreation, "Creation"); Visit(operation.Content, "Content"); } public override void VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation) { LogString(nameof(IInterpolatedStringAdditionOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Left, "Left"); Visit(operation.Right, "Right"); } public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) { LogString(nameof(IInterpolatedStringTextOperation)); LogCommonPropertiesAndNewLine(operation); if (operation.Text.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind); } Visit(operation.Text, "Text"); } public override void VisitInterpolation(IInterpolationOperation operation) { LogString(nameof(IInterpolationOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Expression, "Expression"); Visit(operation.Alignment, "Alignment"); Visit(operation.FormatString, "FormatString"); if (operation.FormatString != null && operation.FormatString.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind); } } public override void VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation) { LogString(nameof(IInterpolatedStringAppendOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.AppendCall, "AppendCall"); } public override void VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation) { LogString(nameof(IInterpolatedStringHandlerArgumentPlaceholderOperation)); if (operation.PlaceholderKind is InterpolatedStringArgumentPlaceholderKind.CallsiteArgument) { LogString($" (ArgumentIndex: {operation.ArgumentIndex})"); } else { LogString($" ({operation.PlaceholderKind})"); } LogCommonPropertiesAndNewLine(operation); } public override void VisitConstantPattern(IConstantPatternOperation operation) { LogString(nameof(IConstantPatternOperation)); LogPatternPropertiesAndNewLine(operation); Visit(operation.Value, "Value"); } public override void VisitRelationalPattern(IRelationalPatternOperation operation) { LogString(nameof(IRelationalPatternOperation)); LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})"); LogPatternPropertiesAndNewLine(operation); Visit(operation.Value, "Value"); } public override void VisitNegatedPattern(INegatedPatternOperation operation) { LogString(nameof(INegatedPatternOperation)); LogPatternPropertiesAndNewLine(operation); Visit(operation.Pattern, "Pattern"); } public override void VisitBinaryPattern(IBinaryPatternOperation operation) { LogString(nameof(IBinaryPatternOperation)); LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})"); LogPatternPropertiesAndNewLine(operation); Visit(operation.LeftPattern, "LeftPattern"); Visit(operation.RightPattern, "RightPattern"); } public override void VisitTypePattern(ITypePatternOperation operation) { LogString(nameof(ITypePatternOperation)); LogPatternProperties(operation); LogSymbol(operation.MatchedType, $", {nameof(operation.MatchedType)}"); LogString(")"); LogNewLine(); } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { LogString(nameof(IDeclarationPatternOperation)); LogPatternProperties(operation); LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}"); LogConstant((object)operation.MatchesNull, $", {nameof(operation.MatchesNull)}"); LogString(")"); LogNewLine(); } public override void VisitRecursivePattern(IRecursivePatternOperation operation) { LogString(nameof(IRecursivePatternOperation)); LogPatternProperties(operation); LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}"); LogType(operation.MatchedType, $", {nameof(operation.MatchedType)}"); LogSymbol(operation.DeconstructSymbol, $", {nameof(operation.DeconstructSymbol)}"); LogString(")"); LogNewLine(); VisitArray(operation.DeconstructionSubpatterns, $"{nameof(operation.DeconstructionSubpatterns)} ", true, true); VisitArray(operation.PropertySubpatterns, $"{nameof(operation.PropertySubpatterns)} ", true, true); } public override void VisitPropertySubpattern(IPropertySubpatternOperation operation) { LogString(nameof(IPropertySubpatternOperation)); LogCommonProperties(operation); LogNewLine(); Visit(operation.Member, $"{nameof(operation.Member)}"); Visit(operation.Pattern, $"{nameof(operation.Pattern)}"); } public override void VisitIsPattern(IIsPatternOperation operation) { LogString(nameof(IIsPatternOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, $"{nameof(operation.Value)}"); Visit(operation.Pattern, "Pattern"); } public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation) { LogString(nameof(IPatternCaseClauseOperation)); LogCaseClauseCommon(operation); Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label); Visit(operation.Pattern, "Pattern"); if (operation.Guard != null) Visit(operation.Guard, nameof(operation.Guard)); } public override void VisitTranslatedQuery(ITranslatedQueryOperation operation) { LogString(nameof(ITranslatedQueryOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operation, "Expression"); } public override void VisitRaiseEvent(IRaiseEventOperation operation) { LogString(nameof(IRaiseEventOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.EventReference, header: "Event Reference"); VisitArguments(operation.Arguments); } public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation) { LogString(nameof(IConstructorBodyOperation)); LogCommonPropertiesAndNewLine(operation); LogLocals(operation.Locals); Visit(operation.Initializer, "Initializer"); Visit(operation.BlockBody, "BlockBody"); Visit(operation.ExpressionBody, "ExpressionBody"); } public override void VisitMethodBodyOperation(IMethodBodyOperation operation) { LogString(nameof(IMethodBodyOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.BlockBody, "BlockBody"); Visit(operation.ExpressionBody, "ExpressionBody"); } public override void VisitDiscardOperation(IDiscardOperation operation) { LogString(nameof(IDiscardOperation)); LogString(" ("); LogSymbol(operation.DiscardSymbol, "Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); } public override void VisitDiscardPattern(IDiscardPatternOperation operation) { LogString(nameof(IDiscardPatternOperation)); LogPatternPropertiesAndNewLine(operation); } public override void VisitSwitchExpression(ISwitchExpressionOperation operation) { LogString($"{nameof(ISwitchExpressionOperation)} ({operation.Arms.Length} arms, IsExhaustive: {operation.IsExhaustive})"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Value, nameof(operation.Value)); VisitArray(operation.Arms, nameof(operation.Arms), logElementCount: true); } public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) { LogString($"{nameof(ISwitchExpressionArmOperation)} ({operation.Locals.Length} locals)"); LogCommonPropertiesAndNewLine(operation); Visit(operation.Pattern, nameof(operation.Pattern)); if (operation.Guard != null) Visit(operation.Guard, nameof(operation.Guard)); Visit(operation.Value, nameof(operation.Value)); LogLocals(operation.Locals); } public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) { LogString(nameof(IStaticLocalInitializationSemaphoreOperation)); LogSymbol(operation.Local, " (Local Symbol"); LogString(")"); LogCommonPropertiesAndNewLine(operation); } public override void VisitRangeOperation(IRangeOperation operation) { LogString(nameof(IRangeOperation)); if (operation.IsLifted) { LogString(" (IsLifted)"); } LogCommonPropertiesAndNewLine(operation); Visit(operation.LeftOperand, nameof(operation.LeftOperand)); Visit(operation.RightOperand, nameof(operation.RightOperand)); } public override void VisitReDim(IReDimOperation operation) { LogString(nameof(IReDimOperation)); if (operation.Preserve) { LogString(" (Preserve)"); } LogCommonPropertiesAndNewLine(operation); VisitArray(operation.Clauses, "Clauses", logElementCount: true); } public override void VisitReDimClause(IReDimClauseOperation operation) { LogString(nameof(IReDimClauseOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); VisitArray(operation.DimensionSizes, "DimensionSizes", logElementCount: true); } public override void VisitWith(IWithOperation operation) { LogString(nameof(IWithOperation)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Operand, "Operand"); Indent(); LogSymbol(operation.CloneMethod, nameof(operation.CloneMethod)); LogNewLine(); Unindent(); Visit(operation.Initializer, "Initializer"); } #endregion } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Test/Core/Compilation/TestOperationVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class TestOperationVisitor : OperationVisitor { public static readonly TestOperationVisitor Singleton = new TestOperationVisitor(); private TestOperationVisitor() : base() { } public override void DefaultVisit(IOperation operation) { throw new NotImplementedException(operation.GetType().ToString()); } internal override void VisitNoneOperation(IOperation operation) { #if Test_IOperation_None_Kind Assert.True(false, "Encountered an IOperation with `Kind == OperationKind.None` while walking the operation tree."); #endif Assert.Equal(OperationKind.None, operation.Kind); } public override void Visit(IOperation operation) { if (operation != null) { var syntax = operation.Syntax; var type = operation.Type; var constantValue = operation.ConstantValue; Assert.NotNull(syntax); // operation.Language can throw due to https://github.com/dotnet/roslyn/issues/23821 // Conditional logic below should be removed once the issue is fixed if (syntax is Microsoft.CodeAnalysis.Syntax.SyntaxList) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Equal(LanguageNames.CSharp, operation.Parent.Language); } else { var language = operation.Language; } var isImplicit = operation.IsImplicit; foreach (IOperation child in operation.Children) { Assert.NotNull(child); } if (operation.SemanticModel != null) { Assert.Same(operation.SemanticModel, operation.SemanticModel.ContainingModelOrSelf); } } base.Visit(operation); } public override void VisitBlock(IBlockOperation operation) { Assert.Equal(OperationKind.Block, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Operations, operation.Children); } public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) { Assert.Equal(OperationKind.VariableDeclarationGroup, operation.Kind); AssertEx.Equal(operation.Declarations, operation.Children); } public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { Assert.Equal(OperationKind.VariableDeclarator, operation.Kind); Assert.NotNull(operation.Symbol); IEnumerable<IOperation> children = operation.IgnoredArguments; var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitVariableDeclaration(IVariableDeclarationOperation operation) { Assert.Equal(OperationKind.VariableDeclaration, operation.Kind); IEnumerable<IOperation> children = operation.IgnoredDimensions.Concat(operation.Declarators); var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitSwitch(ISwitchOperation operation) { Assert.Equal(OperationKind.Switch, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ExitLabel); AssertEx.Equal(new[] { operation.Value }.Concat(operation.Cases), operation.Children); } public override void VisitSwitchCase(ISwitchCaseOperation operation) { Assert.Equal(OperationKind.SwitchCase, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Clauses.Concat(operation.Body), operation.Children); VerifySubTree(((SwitchCaseOperation)operation).Condition, hasNonNullParent: true); } internal static void VerifySubTree(IOperation root, bool hasNonNullParent = false) { if (root != null) { if (hasNonNullParent) { // This is only ever true for ISwitchCaseOperation.Condition. Assert.NotNull(root.Parent); Assert.Same(root, ((SwitchCaseOperation)root.Parent).Condition); } else { Assert.Null(root.Parent); } var explicitNodeMap = new Dictionary<SyntaxNode, IOperation>(); foreach (IOperation descendant in root.DescendantsAndSelf()) { if (!descendant.IsImplicit) { try { explicitNodeMap.Add(descendant.Syntax, descendant); } catch (ArgumentException) { Assert.False(true, $"Duplicate explicit node for syntax ({descendant.Syntax.RawKind}): {descendant.Syntax.ToString()}"); } } Singleton.Visit(descendant); } } } public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.SingleValue, operation.CaseKind); AssertEx.Equal(new[] { operation.Value }, operation.Children); } private static void VisitCaseClauseOperation(ICaseClauseOperation operation) { Assert.Equal(OperationKind.CaseClause, operation.Kind); _ = operation.Label; } public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Relational, operation.CaseKind); var relation = operation.Relation; AssertEx.Equal(new[] { operation.Value }, operation.Children); } public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Default, operation.CaseKind); Assert.Empty(operation.Children); } private static void VisitLocals(ImmutableArray<ILocalSymbol> locals) { foreach (var local in locals) { Assert.NotNull(local); } } public override void VisitWhileLoop(IWhileLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.While, operation.LoopKind); var conditionIsTop = operation.ConditionIsTop; var conditionIsUntil = operation.ConditionIsUntil; IEnumerable<IOperation> children; if (conditionIsTop) { if (operation.IgnoredCondition != null) { children = new[] { operation.Condition, operation.Body, operation.IgnoredCondition }; } else { children = new[] { operation.Condition, operation.Body }; } } else { Assert.Null(operation.IgnoredCondition); if (operation.Condition != null) { children = new[] { operation.Body, operation.Condition }; } else { children = new[] { operation.Body }; } } AssertEx.Equal(children, operation.Children); } public override void VisitForLoop(IForLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.For, operation.LoopKind); VisitLocals(operation.Locals); VisitLocals(operation.ConditionLocals); IEnumerable<IOperation> children = operation.Before; if (operation.Condition != null) { children = children.Concat(new[] { operation.Condition }); } children = children.Concat(new[] { operation.Body }); children = children.Concat(operation.AtLoopBottom); AssertEx.Equal(children, operation.Children); } public override void VisitForToLoop(IForToLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForTo, operation.LoopKind); _ = operation.IsChecked; (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; if (userDefinedInfo != null) { VerifySubTree(userDefinedInfo.Addition); VerifySubTree(userDefinedInfo.Subtraction); VerifySubTree(userDefinedInfo.LessThanOrEqual); VerifySubTree(userDefinedInfo.GreaterThanOrEqual); } IEnumerable<IOperation> children; children = new[] { operation.LoopControlVariable, operation.InitialValue, operation.LimitValue, operation.StepValue, operation.Body }; children = children.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); } public override void VisitForEachLoop(IForEachLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForEach, operation.LoopKind); IEnumerable<IOperation> children = new[] { operation.Collection, operation.LoopControlVariable, operation.Body }.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; if (info != null) { visitArguments(info.GetEnumeratorArguments); visitArguments(info.MoveNextArguments); visitArguments(info.CurrentArguments); visitArguments(info.DisposeArguments); } void visitArguments(ImmutableArray<IArgumentOperation> arguments) { if (arguments != null) { foreach (IArgumentOperation arg in arguments) { VerifySubTree(arg); } } } } private static void VisitLoop(ILoopOperation operation) { Assert.Equal(OperationKind.Loop, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ContinueLabel); Assert.NotNull(operation.ExitLabel); } public override void VisitLabeled(ILabeledOperation operation) { Assert.Equal(OperationKind.Labeled, operation.Kind); Assert.NotNull(operation.Label); if (operation.Operation == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Operation, operation.Children.Single()); } } public override void VisitBranch(IBranchOperation operation) { Assert.Equal(OperationKind.Branch, operation.Kind); Assert.NotNull(operation.Target); switch (operation.BranchKind) { case BranchKind.Break: case BranchKind.Continue: case BranchKind.GoTo: break; default: Assert.False(true); break; } Assert.Empty(operation.Children); } public override void VisitEmpty(IEmptyOperation operation) { Assert.Equal(OperationKind.Empty, operation.Kind); Assert.Empty(operation.Children); } public override void VisitReturn(IReturnOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Return, OperationKind.YieldReturn, OperationKind.YieldBreak }); if (operation.ReturnedValue == null) { Assert.NotEqual(OperationKind.YieldReturn, operation.Kind); Assert.Empty(operation.Children); } else { Assert.Same(operation.ReturnedValue, operation.Children.Single()); } } public override void VisitLock(ILockOperation operation) { Assert.Equal(OperationKind.Lock, operation.Kind); AssertEx.Equal(new[] { operation.LockedValue, operation.Body }, operation.Children); } public override void VisitTry(ITryOperation operation) { Assert.Equal(OperationKind.Try, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Body }; _ = operation.ExitLabel; children = children.Concat(operation.Catches); if (operation.Finally != null) { children = children.Concat(new[] { operation.Finally }); } AssertEx.Equal(children, operation.Children); } public override void VisitCatchClause(ICatchClauseOperation operation) { Assert.Equal(OperationKind.CatchClause, operation.Kind); var exceptionType = operation.ExceptionType; VisitLocals(operation.Locals); IEnumerable<IOperation> children = Array.Empty<IOperation>(); if (operation.ExceptionDeclarationOrExpression != null) { children = children.Concat(new[] { operation.ExceptionDeclarationOrExpression }); } if (operation.Filter != null) { children = children.Concat(new[] { operation.Filter }); } children = children.Concat(new[] { operation.Handler }); AssertEx.Equal(children, operation.Children); } public override void VisitUsing(IUsingOperation operation) { Assert.Equal(OperationKind.Using, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Resources, operation.Body }, operation.Children); Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind); Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind); _ = ((UsingOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } // https://github.com/dotnet/roslyn/issues/21281 internal override void VisitFixed(IFixedOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Variables, operation.Body }, operation.Children); } internal override void VisitAggregateQuery(IAggregateQueryOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Group, operation.Aggregation }, operation.Children); } public override void VisitExpressionStatement(IExpressionStatementOperation operation) { Assert.Equal(OperationKind.ExpressionStatement, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } internal override void VisitWithStatement(IWithStatementOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Body }, operation.Children); } public override void VisitStop(IStopOperation operation) { Assert.Equal(OperationKind.Stop, operation.Kind); Assert.Empty(operation.Children); } public override void VisitEnd(IEndOperation operation) { Assert.Equal(OperationKind.End, operation.Kind); Assert.Empty(operation.Children); } public override void VisitInvocation(IInvocationOperation operation) { Assert.Equal(OperationKind.Invocation, operation.Kind); Assert.NotNull(operation.TargetMethod); var isVirtual = operation.IsVirtual; IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(operation.Arguments); } else { children = operation.Arguments; } AssertEx.Equal(children, operation.Children); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.TargetMethod.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } public override void VisitArgument(IArgumentOperation operation) { Assert.Equal(OperationKind.Argument, operation.Kind); Assert.Contains(operation.ArgumentKind, new[] { ArgumentKind.DefaultValue, ArgumentKind.Explicit, ArgumentKind.ParamArray }); var parameter = operation.Parameter; Assert.Same(operation.Value, operation.Children.Single()); var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.ArgumentKind == ArgumentKind.DefaultValue) { Assert.True(operation.Descendants().All(n => n.IsImplicit), $"Explicit node in default argument value ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}"); } } public override void VisitOmittedArgument(IOmittedArgumentOperation operation) { Assert.Equal(OperationKind.OmittedArgument, operation.Kind); Assert.Empty(operation.Children); } public override void VisitArrayElementReference(IArrayElementReferenceOperation operation) { Assert.Equal(OperationKind.ArrayElementReference, operation.Kind); AssertEx.Equal(new[] { operation.ArrayReference }.Concat(operation.Indices), operation.Children); } internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Same(operation.Pointer, operation.Children.Single()); } public override void VisitLocalReference(ILocalReferenceOperation operation) { Assert.Equal(OperationKind.LocalReference, operation.Kind); Assert.NotNull(operation.Local); var isDeclaration = operation.IsDeclaration; Assert.Empty(operation.Children); } public override void VisitParameterReference(IParameterReferenceOperation operation) { Assert.Equal(OperationKind.ParameterReference, operation.Kind); Assert.NotNull(operation.Parameter); Assert.Empty(operation.Children); } public override void VisitInstanceReference(IInstanceReferenceOperation operation) { Assert.Equal(OperationKind.InstanceReference, operation.Kind); Assert.Empty(operation.Children); var referenceKind = operation.ReferenceKind; } private void VisitMemberReference(IMemberReferenceOperation operation) { VisitMemberReference(operation, Array.Empty<IOperation>()); } private void VisitMemberReference(IMemberReferenceOperation operation, IEnumerable<IOperation> additionalChildren) { Assert.NotNull(operation.Member); IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(additionalChildren); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.Member.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } else { children = additionalChildren; } AssertEx.Equal(children, operation.Children); } public override void VisitFieldReference(IFieldReferenceOperation operation) { Assert.Equal(OperationKind.FieldReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Field); var isDeclaration = operation.IsDeclaration; } public override void VisitMethodReference(IMethodReferenceOperation operation) { Assert.Equal(OperationKind.MethodReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Method); var isVirtual = operation.IsVirtual; } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { Assert.Equal(OperationKind.PropertyReference, operation.Kind); VisitMemberReference(operation, operation.Arguments); Assert.Same(operation.Member, operation.Property); } public override void VisitEventReference(IEventReferenceOperation operation) { Assert.Equal(OperationKind.EventReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Event); } public override void VisitEventAssignment(IEventAssignmentOperation operation) { Assert.Equal(OperationKind.EventAssignment, operation.Kind); var adds = operation.Adds; AssertEx.Equal(new[] { operation.EventReference, operation.HandlerValue }, operation.Children); } public override void VisitConditionalAccess(IConditionalAccessOperation operation) { Assert.Equal(OperationKind.ConditionalAccess, operation.Kind); Assert.NotNull(operation.Type); AssertEx.Equal(new[] { operation.Operation, operation.WhenNotNull }, operation.Children); } public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) { Assert.Equal(OperationKind.ConditionalAccessInstance, operation.Kind); Assert.Empty(operation.Children); } internal override void VisitPlaceholder(IPlaceholderOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Empty(operation.Children); } public override void VisitUnaryOperator(IUnaryOperation operation) { Assert.Equal(OperationKind.UnaryOperator, operation.Kind); Assert.Equal(OperationKind.Unary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitBinaryOperator(IBinaryOperation operation) { Assert.Equal(OperationKind.BinaryOperator, operation.Kind); Assert.Equal(OperationKind.Binary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod; var binaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; var isCompareText = operation.IsCompareText; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation) { Assert.Equal(OperationKind.TupleBinaryOperator, operation.Kind); Assert.Equal(OperationKind.TupleBinary, operation.Kind); var binaryOperationKind = operation.OperatorKind; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitConversion(IConversionOperation operation) { Assert.Equal(OperationKind.Conversion, operation.Kind); var operatorMethod = operation.OperatorMethod; var conversion = operation.Conversion; var isChecked = operation.IsChecked; var isTryCast = operation.IsTryCast; switch (operation.Language) { case LanguageNames.CSharp: CSharp.Conversion csharpConversion = CSharp.CSharpExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => VisualBasic.VisualBasicExtensions.GetConversion(operation)); break; case LanguageNames.VisualBasic: VisualBasic.Conversion visualBasicConversion = VisualBasic.VisualBasicExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => CSharp.CSharpExtensions.GetConversion(operation)); break; default: Debug.Fail($"Language {operation.Language} is unknown!"); break; } Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitConditional(IConditionalOperation operation) { Assert.Equal(OperationKind.Conditional, operation.Kind); bool isRef = operation.IsRef; if (operation.WhenFalse != null) { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue, operation.WhenFalse }, operation.Children); } else { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue }, operation.Children); } } public override void VisitCoalesce(ICoalesceOperation operation) { Assert.Equal(OperationKind.Coalesce, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.WhenNull }, operation.Children); var valueConversion = operation.ValueConversion; } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { Assert.Equal(OperationKind.CoalesceAssignment, operation.Kind); AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitIsType(IIsTypeOperation operation) { Assert.Equal(OperationKind.IsType, operation.Kind); Assert.NotNull(operation.TypeOperand); bool isNegated = operation.IsNegated; Assert.Same(operation.ValueOperand, operation.Children.Single()); } public override void VisitSizeOf(ISizeOfOperation operation) { Assert.Equal(OperationKind.SizeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitTypeOf(ITypeOfOperation operation) { Assert.Equal(OperationKind.TypeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.AnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Same(operation.Body, operation.Children.Single()); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.FlowAnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Empty(operation.Children); } public override void VisitLocalFunction(ILocalFunctionOperation operation) { Assert.Equal(OperationKind.LocalFunction, operation.Kind); Assert.NotNull(operation.Symbol); if (operation.Body != null) { var children = operation.Children.ToImmutableArray(); Assert.Same(operation.Body, children[0]); if (operation.IgnoredBody != null) { Assert.Same(operation.IgnoredBody, children[1]); Assert.Equal(2, children.Length); } else { Assert.Equal(1, children.Length); } } else { Assert.Null(operation.IgnoredBody); Assert.Empty(operation.Children); } } public override void VisitLiteral(ILiteralOperation operation) { Assert.Equal(OperationKind.Literal, operation.Kind); Assert.Empty(operation.Children); } public override void VisitAwait(IAwaitOperation operation) { Assert.Equal(OperationKind.Await, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitNameOf(INameOfOperation operation) { Assert.Equal(OperationKind.NameOf, operation.Kind); Assert.Same(operation.Argument, operation.Children.Single()); } public override void VisitThrow(IThrowOperation operation) { Assert.Equal(OperationKind.Throw, operation.Kind); if (operation.Exception == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Exception, operation.Children.Single()); } } public override void VisitAddressOf(IAddressOfOperation operation) { Assert.Equal(OperationKind.AddressOf, operation.Kind); Assert.Same(operation.Reference, operation.Children.Single()); } public override void VisitObjectCreation(IObjectCreationOperation operation) { Assert.Equal(OperationKind.ObjectCreation, operation.Kind); var constructor = operation.Constructor; // When parameter-less struct constructor is inaccessible, the constructor symbol is null if (!operation.Type.IsValueType) { Assert.NotNull(constructor); if (constructor == null) { Assert.Empty(operation.Arguments); } } IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) { Assert.Equal(OperationKind.AnonymousObjectCreation, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); foreach (var initializer in operation.Initializers) { var simpleAssignment = (ISimpleAssignmentOperation)initializer; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Assert.Empty(propertyReference.Arguments); Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind); Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind); } } public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) { Assert.Equal(OperationKind.DynamicObjectCreation, operation.Kind); IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitDynamicInvocation(IDynamicInvocationOperation operation) { Assert.Equal(OperationKind.DynamicInvocation, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) { Assert.Equal(OperationKind.DynamicIndexerAccess, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) { Assert.Equal(OperationKind.ObjectOrCollectionInitializer, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); } public override void VisitMemberInitializer(IMemberInitializerOperation operation) { Assert.Equal(OperationKind.MemberInitializer, operation.Kind); AssertEx.Equal(new[] { operation.InitializedMember, operation.Initializer }, operation.Children); } private void VisitSymbolInitializer(ISymbolInitializerOperation operation) { VisitLocals(operation.Locals); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitFieldInitializer(IFieldInitializerOperation operation) { Assert.Equal(OperationKind.FieldInitializer, operation.Kind); foreach (var field in operation.InitializedFields) { Assert.NotNull(field); } VisitSymbolInitializer(operation); } public override void VisitVariableInitializer(IVariableInitializerOperation operation) { Assert.Equal(OperationKind.VariableInitializer, operation.Kind); Assert.Empty(operation.Locals); VisitSymbolInitializer(operation); } public override void VisitPropertyInitializer(IPropertyInitializerOperation operation) { Assert.Equal(OperationKind.PropertyInitializer, operation.Kind); foreach (var property in operation.InitializedProperties) { Assert.NotNull(property); } VisitSymbolInitializer(operation); } public override void VisitParameterInitializer(IParameterInitializerOperation operation) { Assert.Equal(OperationKind.ParameterInitializer, operation.Kind); Assert.NotNull(operation.Parameter); VisitSymbolInitializer(operation); } public override void VisitArrayCreation(IArrayCreationOperation operation) { Assert.Equal(OperationKind.ArrayCreation, operation.Kind); IEnumerable<IOperation> children = operation.DimensionSizes; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitArrayInitializer(IArrayInitializerOperation operation) { Assert.Equal(OperationKind.ArrayInitializer, operation.Kind); Assert.Null(operation.Type); AssertEx.Equal(operation.ElementValues, operation.Children); } private void VisitAssignment(IAssignmentOperation operation) { AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { Assert.Equal(OperationKind.SimpleAssignment, operation.Kind); bool isRef = operation.IsRef; VisitAssignment(operation); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { Assert.Equal(OperationKind.CompoundAssignment, operation.Kind); var operatorMethod = operation.OperatorMethod; var binaryOperationKind = operation.OperatorKind; var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.Syntax.Language == LanguageNames.CSharp) { Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetOutConversion(operation)); var inConversionInternal = CSharp.CSharpExtensions.GetInConversion(operation); var outConversionInternal = CSharp.CSharpExtensions.GetOutConversion(operation); } else { Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetOutConversion(operation)); var inConversionInternal = VisualBasic.VisualBasicExtensions.GetInConversion(operation); var outConversionInternal = VisualBasic.VisualBasicExtensions.GetOutConversion(operation); } var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; VisitAssignment(operation); } public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Increment, OperationKind.Decrement }); var operatorMethod = operation.OperatorMethod; var isPostFix = operation.IsPostfix; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitParenthesized(IParenthesizedOperation operation) { Assert.Equal(OperationKind.Parenthesized, operation.Kind); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) { Assert.Equal(OperationKind.DynamicMemberReference, operation.Kind); Assert.NotNull(operation.MemberName); foreach (var typeArg in operation.TypeArguments) { Assert.NotNull(typeArg); } var containingType = operation.ContainingType; if (operation.Instance == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Instance, operation.Children.Single()); } } public override void VisitDefaultValue(IDefaultValueOperation operation) { Assert.Equal(OperationKind.DefaultValue, operation.Kind); Assert.Empty(operation.Children); } public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) { Assert.Equal(OperationKind.TypeParameterObjectCreation, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } public override void VisitInvalid(IInvalidOperation operation) { Assert.Equal(OperationKind.Invalid, operation.Kind); } public override void VisitTuple(ITupleOperation operation) { Assert.Equal(OperationKind.Tuple, operation.Kind); var naturalType = operation.NaturalType; AssertEx.Equal(operation.Elements, operation.Children); } public override void VisitInterpolatedString(IInterpolatedStringOperation operation) { Assert.Equal(OperationKind.InterpolatedString, operation.Kind); AssertEx.Equal(operation.Parts, operation.Children); } public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) { Assert.Equal(OperationKind.InterpolatedStringText, operation.Kind); if (operation.Text.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind); } Assert.Same(operation.Text, operation.Children.Single()); } public override void VisitInterpolation(IInterpolationOperation operation) { Assert.Equal(OperationKind.Interpolation, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Expression }; if (operation.Alignment != null) { children = children.Concat(new[] { operation.Alignment }); } if (operation.FormatString != null) { if (operation.FormatString.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind); } children = children.Concat(new[] { operation.FormatString }); } AssertEx.Equal(children, operation.Children); } private void VisitPatternCommon(IPatternOperation pattern) { Assert.NotNull(pattern.InputType); Assert.NotNull(pattern.NarrowedType); Assert.Null(pattern.Type); Assert.False(pattern.ConstantValue.HasValue); } public override void VisitConstantPattern(IConstantPatternOperation operation) { Assert.Equal(OperationKind.ConstantPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitRelationalPattern(IRelationalPatternOperation operation) { Assert.Equal(OperationKind.RelationalPattern, operation.Kind); Assert.True(operation.OperatorKind is Operations.BinaryOperatorKind.LessThan or Operations.BinaryOperatorKind.LessThanOrEqual or Operations.BinaryOperatorKind.GreaterThan or Operations.BinaryOperatorKind.GreaterThanOrEqual or Operations.BinaryOperatorKind.Equals or // Error cases Operations.BinaryOperatorKind.NotEquals); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitBinaryPattern(IBinaryPatternOperation operation) { Assert.Equal(OperationKind.BinaryPattern, operation.Kind); VisitPatternCommon(operation); Assert.True(operation.OperatorKind switch { Operations.BinaryOperatorKind.Or => true, Operations.BinaryOperatorKind.And => true, _ => false }); var children = operation.Children.ToArray(); Assert.Equal(2, children.Length); Assert.Same(operation.LeftPattern, children[0]); Assert.Same(operation.RightPattern, children[1]); } public override void VisitNegatedPattern(INegatedPatternOperation operation) { Assert.Equal(OperationKind.NegatedPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Pattern, operation.Children.Single()); } public override void VisitTypePattern(ITypePatternOperation operation) { Assert.Equal(OperationKind.TypePattern, operation.Kind); Assert.NotNull(operation.MatchedType); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { Assert.Equal(OperationKind.DeclarationPattern, operation.Kind); VisitPatternCommon(operation); if (operation.Syntax.IsKind(CSharp.SyntaxKind.VarPattern) || // in `var (x, y)`, the syntax here is the designation `x`. operation.Syntax.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.True(operation.MatchesNull); Assert.Null(operation.MatchedType); } else { Assert.False(operation.MatchesNull); Assert.NotNull(operation.MatchedType); } var designation = (operation.Syntax as CSharp.Syntax.DeclarationPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VarPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VariableDesignationSyntax); if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } Assert.Empty(operation.Children); } public override void VisitRecursivePattern(IRecursivePatternOperation operation) { Assert.Equal(OperationKind.RecursivePattern, operation.Kind); VisitPatternCommon(operation); Assert.NotNull(operation.MatchedType); switch (operation.DeconstructSymbol) { case IErrorTypeSymbol error: case null: // OK: indicates deconstruction of a tuple, or an error case break; case IMethodSymbol method: // when we have a method, it is a `Deconstruct` method Assert.Equal("Deconstruct", method.Name); break; case ITypeSymbol type: // when we have a type, it is the type "ITuple" Assert.Equal("ITuple", type.Name); break; default: Assert.True(false, $"Unexpected symbol {operation.DeconstructSymbol}"); break; } var designation = (operation.Syntax as CSharp.Syntax.RecursivePatternSyntax)?.Designation; if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } foreach (var subpat in operation.PropertySubpatterns) { Assert.True(subpat is IPropertySubpatternOperation); } IEnumerable<IOperation> children = operation.DeconstructionSubpatterns.Cast<IOperation>(); children = children.Concat(operation.PropertySubpatterns); AssertEx.Equal(children, operation.Children); } public override void VisitPropertySubpattern(IPropertySubpatternOperation operation) { Assert.NotNull(operation.Pattern); var children = new IOperation[] { operation.Member, operation.Pattern }; AssertEx.Equal(children, operation.Children); if (operation.Member.Kind == OperationKind.Invalid) { return; } Assert.True(operation.Member is IMemberReferenceOperation); var member = (IMemberReferenceOperation)operation.Member; switch (member.Member) { case IFieldSymbol field: case IPropertySymbol prop: break; case var symbol: Assert.True(false, $"Unexpected symbol {symbol}"); break; } } public override void VisitSwitchExpression(ISwitchExpressionOperation operation) { //force the existence of IsExhaustive _ = operation.IsExhaustive; Assert.NotNull(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.Equal(OperationKind.SwitchExpression, operation.Kind); Assert.NotNull(operation.Value); var children = operation.Arms.Cast<IOperation>().Prepend(operation.Value); AssertEx.Equal(children, operation.Children); } public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) { Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.NotNull(operation.Pattern); _ = operation.Guard; Assert.NotNull(operation.Value); VisitLocals(operation.Locals); var children = operation.Guard == null ? new[] { operation.Pattern, operation.Value } : new[] { operation.Pattern, operation.Guard, operation.Value }; AssertEx.Equal(children, operation.Children); } public override void VisitIsPattern(IIsPatternOperation operation) { Assert.Equal(OperationKind.IsPattern, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Pattern }, operation.Children); } public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Pattern, operation.CaseKind); Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label); if (operation.Guard != null) { AssertEx.Equal(new[] { operation.Pattern, operation.Guard }, operation.Children); } else { Assert.Same(operation.Pattern, operation.Children.Single()); } } public override void VisitTranslatedQuery(ITranslatedQueryOperation operation) { Assert.Equal(OperationKind.TranslatedQuery, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation) { Assert.Equal(OperationKind.DeclarationExpression, operation.Kind); Assert.Same(operation.Expression, operation.Children.Single()); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { Assert.Equal(OperationKind.DeconstructionAssignment, operation.Kind); VisitAssignment(operation); } public override void VisitDelegateCreation(IDelegateCreationOperation operation) { Assert.Equal(OperationKind.DelegateCreation, operation.Kind); Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitRaiseEvent(IRaiseEventOperation operation) { Assert.Equal(OperationKind.RaiseEvent, operation.Kind); AssertEx.Equal(new IOperation[] { operation.EventReference }.Concat(operation.Arguments), operation.Children); } public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Range, operation.CaseKind); AssertEx.Equal(new[] { operation.MinimumValue, operation.MaximumValue }, operation.Children); } public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation) { Assert.Equal(OperationKind.ConstructorBodyOperation, operation.Kind); Assert.Equal(OperationKind.ConstructorBody, operation.Kind); VisitLocals(operation.Locals); var builder = ArrayBuilder<IOperation>.GetInstance(); if (operation.Initializer != null) { builder.Add(operation.Initializer); } if (operation.BlockBody != null) { builder.Add(operation.BlockBody); } if (operation.ExpressionBody != null) { builder.Add(operation.ExpressionBody); } AssertEx.Equal(builder, operation.Children); builder.Free(); } public override void VisitMethodBodyOperation(IMethodBodyOperation operation) { Assert.Equal(OperationKind.MethodBodyOperation, operation.Kind); Assert.Equal(OperationKind.MethodBody, operation.Kind); if (operation.BlockBody != null) { if (operation.ExpressionBody != null) { AssertEx.Equal(new[] { operation.BlockBody, operation.ExpressionBody }, operation.Children); } else { Assert.Same(operation.BlockBody, operation.Children.Single()); } } else if (operation.ExpressionBody != null) { Assert.Same(operation.ExpressionBody, operation.Children.Single()); } else { Assert.Empty(operation.Children); } } public override void VisitDiscardOperation(IDiscardOperation operation) { Assert.Equal(OperationKind.Discard, operation.Kind); Assert.Empty(operation.Children); var discardSymbol = operation.DiscardSymbol; Assert.Equal(operation.Type, discardSymbol.Type); } public override void VisitDiscardPattern(IDiscardPatternOperation operation) { Assert.Equal(OperationKind.DiscardPattern, operation.Kind); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitFlowCapture(IFlowCaptureOperation operation) { Assert.Equal(OperationKind.FlowCapture, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Value, operation.Children.Single()); switch (operation.Value.Kind) { case OperationKind.Invalid: case OperationKind.None: case OperationKind.AnonymousFunction: case OperationKind.FlowCaptureReference: case OperationKind.DefaultValue: case OperationKind.FlowAnonymousFunction: // must be an error case like in Microsoft.CodeAnalysis.CSharp.UnitTests.ConditionalOperatorTests.TestBothUntyped unit-test break; case OperationKind.OmittedArgument: case OperationKind.DeclarationExpression: case OperationKind.Discard: Assert.False(true, $"A {operation.Value.Kind} node should not be spilled or captured."); break; default: // Only values can be spilled/captured if (!operation.Value.ConstantValue.HasValue || operation.Value.ConstantValue.Value != null) { Assert.NotNull(operation.Value.Type); } break; } } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { Assert.Equal(OperationKind.FlowCaptureReference, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitIsNull(IIsNullOperation operation) { Assert.Equal(OperationKind.IsNull, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitCaughtException(ICaughtExceptionOperation operation) { Assert.Equal(OperationKind.CaughtException, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) { Assert.Equal(OperationKind.StaticLocalInitializationSemaphore, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); Assert.NotNull(operation.Local); Assert.True(operation.Local.IsStatic); } public override void VisitRangeOperation(IRangeOperation operation) { Assert.Equal(OperationKind.Range, operation.Kind); IOperation[] children = operation.Children.ToArray(); int index = 0; if (operation.LeftOperand != null) { Assert.Same(operation.LeftOperand, children[index++]); } if (operation.RightOperand != null) { Assert.Same(operation.RightOperand, children[index++]); } Assert.Equal(index, children.Length); } public override void VisitReDim(IReDimOperation operation) { Assert.Equal(OperationKind.ReDim, operation.Kind); AssertEx.Equal(operation.Clauses, operation.Children); var preserve = operation.Preserve; } public override void VisitReDimClause(IReDimClauseOperation operation) { Assert.Equal(OperationKind.ReDimClause, operation.Kind); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.DimensionSizes), operation.Children); } public override void VisitUsingDeclaration(IUsingDeclarationOperation operation) { Assert.NotNull(operation.DeclarationGroup); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.DeclarationGroup), operation.Children); Assert.True(operation.DeclarationGroup.IsImplicit); Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); _ = operation.IsAsynchronous; _ = operation.IsImplicit; _ = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } public override void VisitWith(IWithOperation operation) { Assert.Equal(OperationKind.With, operation.Kind); _ = operation.CloneMethod; IEnumerable<IOperation> children = SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.Initializer); AssertEx.Equal(children, operation.Children); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class TestOperationVisitor : OperationVisitor { public static readonly TestOperationVisitor Singleton = new TestOperationVisitor(); private TestOperationVisitor() : base() { } public override void DefaultVisit(IOperation operation) { throw new NotImplementedException(operation.GetType().ToString()); } internal override void VisitNoneOperation(IOperation operation) { #if Test_IOperation_None_Kind Assert.True(false, "Encountered an IOperation with `Kind == OperationKind.None` while walking the operation tree."); #endif Assert.Equal(OperationKind.None, operation.Kind); } public override void Visit(IOperation operation) { if (operation != null) { var syntax = operation.Syntax; var type = operation.Type; var constantValue = operation.ConstantValue; Assert.NotNull(syntax); // operation.Language can throw due to https://github.com/dotnet/roslyn/issues/23821 // Conditional logic below should be removed once the issue is fixed if (syntax is Microsoft.CodeAnalysis.Syntax.SyntaxList) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Equal(LanguageNames.CSharp, operation.Parent.Language); } else { var language = operation.Language; } var isImplicit = operation.IsImplicit; foreach (IOperation child in operation.Children) { Assert.NotNull(child); } if (operation.SemanticModel != null) { Assert.Same(operation.SemanticModel, operation.SemanticModel.ContainingModelOrSelf); } } base.Visit(operation); } public override void VisitBlock(IBlockOperation operation) { Assert.Equal(OperationKind.Block, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Operations, operation.Children); } public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) { Assert.Equal(OperationKind.VariableDeclarationGroup, operation.Kind); AssertEx.Equal(operation.Declarations, operation.Children); } public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { Assert.Equal(OperationKind.VariableDeclarator, operation.Kind); Assert.NotNull(operation.Symbol); IEnumerable<IOperation> children = operation.IgnoredArguments; var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitVariableDeclaration(IVariableDeclarationOperation operation) { Assert.Equal(OperationKind.VariableDeclaration, operation.Kind); IEnumerable<IOperation> children = operation.IgnoredDimensions.Concat(operation.Declarators); var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitSwitch(ISwitchOperation operation) { Assert.Equal(OperationKind.Switch, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ExitLabel); AssertEx.Equal(new[] { operation.Value }.Concat(operation.Cases), operation.Children); } public override void VisitSwitchCase(ISwitchCaseOperation operation) { Assert.Equal(OperationKind.SwitchCase, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Clauses.Concat(operation.Body), operation.Children); VerifySubTree(((SwitchCaseOperation)operation).Condition, hasNonNullParent: true); } internal static void VerifySubTree(IOperation root, bool hasNonNullParent = false) { if (root != null) { if (hasNonNullParent) { // This is only ever true for ISwitchCaseOperation.Condition. Assert.NotNull(root.Parent); Assert.Same(root, ((SwitchCaseOperation)root.Parent).Condition); } else { Assert.Null(root.Parent); } var explicitNodeMap = new Dictionary<SyntaxNode, IOperation>(); foreach (IOperation descendant in root.DescendantsAndSelf()) { if (!descendant.IsImplicit) { try { explicitNodeMap.Add(descendant.Syntax, descendant); } catch (ArgumentException) { Assert.False(true, $"Duplicate explicit node for syntax ({descendant.Syntax.RawKind}): {descendant.Syntax.ToString()}"); } } Singleton.Visit(descendant); } } } public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.SingleValue, operation.CaseKind); AssertEx.Equal(new[] { operation.Value }, operation.Children); } private static void VisitCaseClauseOperation(ICaseClauseOperation operation) { Assert.Equal(OperationKind.CaseClause, operation.Kind); _ = operation.Label; } public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Relational, operation.CaseKind); var relation = operation.Relation; AssertEx.Equal(new[] { operation.Value }, operation.Children); } public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Default, operation.CaseKind); Assert.Empty(operation.Children); } private static void VisitLocals(ImmutableArray<ILocalSymbol> locals) { foreach (var local in locals) { Assert.NotNull(local); } } public override void VisitWhileLoop(IWhileLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.While, operation.LoopKind); var conditionIsTop = operation.ConditionIsTop; var conditionIsUntil = operation.ConditionIsUntil; IEnumerable<IOperation> children; if (conditionIsTop) { if (operation.IgnoredCondition != null) { children = new[] { operation.Condition, operation.Body, operation.IgnoredCondition }; } else { children = new[] { operation.Condition, operation.Body }; } } else { Assert.Null(operation.IgnoredCondition); if (operation.Condition != null) { children = new[] { operation.Body, operation.Condition }; } else { children = new[] { operation.Body }; } } AssertEx.Equal(children, operation.Children); } public override void VisitForLoop(IForLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.For, operation.LoopKind); VisitLocals(operation.Locals); VisitLocals(operation.ConditionLocals); IEnumerable<IOperation> children = operation.Before; if (operation.Condition != null) { children = children.Concat(new[] { operation.Condition }); } children = children.Concat(new[] { operation.Body }); children = children.Concat(operation.AtLoopBottom); AssertEx.Equal(children, operation.Children); } public override void VisitForToLoop(IForToLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForTo, operation.LoopKind); _ = operation.IsChecked; (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; if (userDefinedInfo != null) { VerifySubTree(userDefinedInfo.Addition); VerifySubTree(userDefinedInfo.Subtraction); VerifySubTree(userDefinedInfo.LessThanOrEqual); VerifySubTree(userDefinedInfo.GreaterThanOrEqual); } IEnumerable<IOperation> children; children = new[] { operation.LoopControlVariable, operation.InitialValue, operation.LimitValue, operation.StepValue, operation.Body }; children = children.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); } public override void VisitForEachLoop(IForEachLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForEach, operation.LoopKind); IEnumerable<IOperation> children = new[] { operation.Collection, operation.LoopControlVariable, operation.Body }.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; if (info != null) { visitArguments(info.GetEnumeratorArguments); visitArguments(info.MoveNextArguments); visitArguments(info.CurrentArguments); visitArguments(info.DisposeArguments); } void visitArguments(ImmutableArray<IArgumentOperation> arguments) { if (arguments != null) { foreach (IArgumentOperation arg in arguments) { VerifySubTree(arg); } } } } private static void VisitLoop(ILoopOperation operation) { Assert.Equal(OperationKind.Loop, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ContinueLabel); Assert.NotNull(operation.ExitLabel); } public override void VisitLabeled(ILabeledOperation operation) { Assert.Equal(OperationKind.Labeled, operation.Kind); Assert.NotNull(operation.Label); if (operation.Operation == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Operation, operation.Children.Single()); } } public override void VisitBranch(IBranchOperation operation) { Assert.Equal(OperationKind.Branch, operation.Kind); Assert.NotNull(operation.Target); switch (operation.BranchKind) { case BranchKind.Break: case BranchKind.Continue: case BranchKind.GoTo: break; default: Assert.False(true); break; } Assert.Empty(operation.Children); } public override void VisitEmpty(IEmptyOperation operation) { Assert.Equal(OperationKind.Empty, operation.Kind); Assert.Empty(operation.Children); } public override void VisitReturn(IReturnOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Return, OperationKind.YieldReturn, OperationKind.YieldBreak }); if (operation.ReturnedValue == null) { Assert.NotEqual(OperationKind.YieldReturn, operation.Kind); Assert.Empty(operation.Children); } else { Assert.Same(operation.ReturnedValue, operation.Children.Single()); } } public override void VisitLock(ILockOperation operation) { Assert.Equal(OperationKind.Lock, operation.Kind); AssertEx.Equal(new[] { operation.LockedValue, operation.Body }, operation.Children); } public override void VisitTry(ITryOperation operation) { Assert.Equal(OperationKind.Try, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Body }; _ = operation.ExitLabel; children = children.Concat(operation.Catches); if (operation.Finally != null) { children = children.Concat(new[] { operation.Finally }); } AssertEx.Equal(children, operation.Children); } public override void VisitCatchClause(ICatchClauseOperation operation) { Assert.Equal(OperationKind.CatchClause, operation.Kind); var exceptionType = operation.ExceptionType; VisitLocals(operation.Locals); IEnumerable<IOperation> children = Array.Empty<IOperation>(); if (operation.ExceptionDeclarationOrExpression != null) { children = children.Concat(new[] { operation.ExceptionDeclarationOrExpression }); } if (operation.Filter != null) { children = children.Concat(new[] { operation.Filter }); } children = children.Concat(new[] { operation.Handler }); AssertEx.Equal(children, operation.Children); } public override void VisitUsing(IUsingOperation operation) { Assert.Equal(OperationKind.Using, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Resources, operation.Body }, operation.Children); Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind); Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind); _ = ((UsingOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } // https://github.com/dotnet/roslyn/issues/21281 internal override void VisitFixed(IFixedOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Variables, operation.Body }, operation.Children); } internal override void VisitAggregateQuery(IAggregateQueryOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Group, operation.Aggregation }, operation.Children); } public override void VisitExpressionStatement(IExpressionStatementOperation operation) { Assert.Equal(OperationKind.ExpressionStatement, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } internal override void VisitWithStatement(IWithStatementOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Body }, operation.Children); } public override void VisitStop(IStopOperation operation) { Assert.Equal(OperationKind.Stop, operation.Kind); Assert.Empty(operation.Children); } public override void VisitEnd(IEndOperation operation) { Assert.Equal(OperationKind.End, operation.Kind); Assert.Empty(operation.Children); } public override void VisitInvocation(IInvocationOperation operation) { Assert.Equal(OperationKind.Invocation, operation.Kind); Assert.NotNull(operation.TargetMethod); var isVirtual = operation.IsVirtual; IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(operation.Arguments); } else { children = operation.Arguments; } AssertEx.Equal(children, operation.Children); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.TargetMethod.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } public override void VisitArgument(IArgumentOperation operation) { Assert.Equal(OperationKind.Argument, operation.Kind); Assert.Contains(operation.ArgumentKind, new[] { ArgumentKind.DefaultValue, ArgumentKind.Explicit, ArgumentKind.ParamArray }); var parameter = operation.Parameter; Assert.Same(operation.Value, operation.Children.Single()); var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.ArgumentKind == ArgumentKind.DefaultValue) { Assert.True(operation.Descendants().All(n => n.IsImplicit), $"Explicit node in default argument value ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}"); } } public override void VisitOmittedArgument(IOmittedArgumentOperation operation) { Assert.Equal(OperationKind.OmittedArgument, operation.Kind); Assert.Empty(operation.Children); } public override void VisitArrayElementReference(IArrayElementReferenceOperation operation) { Assert.Equal(OperationKind.ArrayElementReference, operation.Kind); AssertEx.Equal(new[] { operation.ArrayReference }.Concat(operation.Indices), operation.Children); } internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Same(operation.Pointer, operation.Children.Single()); } public override void VisitLocalReference(ILocalReferenceOperation operation) { Assert.Equal(OperationKind.LocalReference, operation.Kind); Assert.NotNull(operation.Local); var isDeclaration = operation.IsDeclaration; Assert.Empty(operation.Children); } public override void VisitParameterReference(IParameterReferenceOperation operation) { Assert.Equal(OperationKind.ParameterReference, operation.Kind); Assert.NotNull(operation.Parameter); Assert.Empty(operation.Children); } public override void VisitInstanceReference(IInstanceReferenceOperation operation) { Assert.Equal(OperationKind.InstanceReference, operation.Kind); Assert.Empty(operation.Children); var referenceKind = operation.ReferenceKind; } private void VisitMemberReference(IMemberReferenceOperation operation) { VisitMemberReference(operation, Array.Empty<IOperation>()); } private void VisitMemberReference(IMemberReferenceOperation operation, IEnumerable<IOperation> additionalChildren) { Assert.NotNull(operation.Member); IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(additionalChildren); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.Member.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } else { children = additionalChildren; } AssertEx.Equal(children, operation.Children); } public override void VisitFieldReference(IFieldReferenceOperation operation) { Assert.Equal(OperationKind.FieldReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Field); var isDeclaration = operation.IsDeclaration; } public override void VisitMethodReference(IMethodReferenceOperation operation) { Assert.Equal(OperationKind.MethodReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Method); var isVirtual = operation.IsVirtual; } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { Assert.Equal(OperationKind.PropertyReference, operation.Kind); VisitMemberReference(operation, operation.Arguments); Assert.Same(operation.Member, operation.Property); } public override void VisitEventReference(IEventReferenceOperation operation) { Assert.Equal(OperationKind.EventReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Event); } public override void VisitEventAssignment(IEventAssignmentOperation operation) { Assert.Equal(OperationKind.EventAssignment, operation.Kind); var adds = operation.Adds; AssertEx.Equal(new[] { operation.EventReference, operation.HandlerValue }, operation.Children); } public override void VisitConditionalAccess(IConditionalAccessOperation operation) { Assert.Equal(OperationKind.ConditionalAccess, operation.Kind); Assert.NotNull(operation.Type); AssertEx.Equal(new[] { operation.Operation, operation.WhenNotNull }, operation.Children); } public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) { Assert.Equal(OperationKind.ConditionalAccessInstance, operation.Kind); Assert.Empty(operation.Children); } internal override void VisitPlaceholder(IPlaceholderOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Empty(operation.Children); } public override void VisitUnaryOperator(IUnaryOperation operation) { Assert.Equal(OperationKind.UnaryOperator, operation.Kind); Assert.Equal(OperationKind.Unary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitBinaryOperator(IBinaryOperation operation) { Assert.Equal(OperationKind.BinaryOperator, operation.Kind); Assert.Equal(OperationKind.Binary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod; var binaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; var isCompareText = operation.IsCompareText; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation) { Assert.Equal(OperationKind.TupleBinaryOperator, operation.Kind); Assert.Equal(OperationKind.TupleBinary, operation.Kind); var binaryOperationKind = operation.OperatorKind; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitConversion(IConversionOperation operation) { Assert.Equal(OperationKind.Conversion, operation.Kind); var operatorMethod = operation.OperatorMethod; var conversion = operation.Conversion; var isChecked = operation.IsChecked; var isTryCast = operation.IsTryCast; switch (operation.Language) { case LanguageNames.CSharp: CSharp.Conversion csharpConversion = CSharp.CSharpExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => VisualBasic.VisualBasicExtensions.GetConversion(operation)); break; case LanguageNames.VisualBasic: VisualBasic.Conversion visualBasicConversion = VisualBasic.VisualBasicExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => CSharp.CSharpExtensions.GetConversion(operation)); break; default: Debug.Fail($"Language {operation.Language} is unknown!"); break; } Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitConditional(IConditionalOperation operation) { Assert.Equal(OperationKind.Conditional, operation.Kind); bool isRef = operation.IsRef; if (operation.WhenFalse != null) { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue, operation.WhenFalse }, operation.Children); } else { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue }, operation.Children); } } public override void VisitCoalesce(ICoalesceOperation operation) { Assert.Equal(OperationKind.Coalesce, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.WhenNull }, operation.Children); var valueConversion = operation.ValueConversion; } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { Assert.Equal(OperationKind.CoalesceAssignment, operation.Kind); AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitIsType(IIsTypeOperation operation) { Assert.Equal(OperationKind.IsType, operation.Kind); Assert.NotNull(operation.TypeOperand); bool isNegated = operation.IsNegated; Assert.Same(operation.ValueOperand, operation.Children.Single()); } public override void VisitSizeOf(ISizeOfOperation operation) { Assert.Equal(OperationKind.SizeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitTypeOf(ITypeOfOperation operation) { Assert.Equal(OperationKind.TypeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.AnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Same(operation.Body, operation.Children.Single()); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.FlowAnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Empty(operation.Children); } public override void VisitLocalFunction(ILocalFunctionOperation operation) { Assert.Equal(OperationKind.LocalFunction, operation.Kind); Assert.NotNull(operation.Symbol); if (operation.Body != null) { var children = operation.Children.ToImmutableArray(); Assert.Same(operation.Body, children[0]); if (operation.IgnoredBody != null) { Assert.Same(operation.IgnoredBody, children[1]); Assert.Equal(2, children.Length); } else { Assert.Equal(1, children.Length); } } else { Assert.Null(operation.IgnoredBody); Assert.Empty(operation.Children); } } public override void VisitLiteral(ILiteralOperation operation) { Assert.Equal(OperationKind.Literal, operation.Kind); Assert.Empty(operation.Children); } public override void VisitAwait(IAwaitOperation operation) { Assert.Equal(OperationKind.Await, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitNameOf(INameOfOperation operation) { Assert.Equal(OperationKind.NameOf, operation.Kind); Assert.Same(operation.Argument, operation.Children.Single()); } public override void VisitThrow(IThrowOperation operation) { Assert.Equal(OperationKind.Throw, operation.Kind); if (operation.Exception == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Exception, operation.Children.Single()); } } public override void VisitAddressOf(IAddressOfOperation operation) { Assert.Equal(OperationKind.AddressOf, operation.Kind); Assert.Same(operation.Reference, operation.Children.Single()); } public override void VisitObjectCreation(IObjectCreationOperation operation) { Assert.Equal(OperationKind.ObjectCreation, operation.Kind); var constructor = operation.Constructor; // When parameter-less struct constructor is inaccessible, the constructor symbol is null if (!operation.Type.IsValueType) { Assert.NotNull(constructor); if (constructor == null) { Assert.Empty(operation.Arguments); } } IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) { Assert.Equal(OperationKind.AnonymousObjectCreation, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); foreach (var initializer in operation.Initializers) { var simpleAssignment = (ISimpleAssignmentOperation)initializer; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Assert.Empty(propertyReference.Arguments); Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind); Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind); } } public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) { Assert.Equal(OperationKind.DynamicObjectCreation, operation.Kind); IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitDynamicInvocation(IDynamicInvocationOperation operation) { Assert.Equal(OperationKind.DynamicInvocation, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) { Assert.Equal(OperationKind.DynamicIndexerAccess, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) { Assert.Equal(OperationKind.ObjectOrCollectionInitializer, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); } public override void VisitMemberInitializer(IMemberInitializerOperation operation) { Assert.Equal(OperationKind.MemberInitializer, operation.Kind); AssertEx.Equal(new[] { operation.InitializedMember, operation.Initializer }, operation.Children); } private void VisitSymbolInitializer(ISymbolInitializerOperation operation) { VisitLocals(operation.Locals); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitFieldInitializer(IFieldInitializerOperation operation) { Assert.Equal(OperationKind.FieldInitializer, operation.Kind); foreach (var field in operation.InitializedFields) { Assert.NotNull(field); } VisitSymbolInitializer(operation); } public override void VisitVariableInitializer(IVariableInitializerOperation operation) { Assert.Equal(OperationKind.VariableInitializer, operation.Kind); Assert.Empty(operation.Locals); VisitSymbolInitializer(operation); } public override void VisitPropertyInitializer(IPropertyInitializerOperation operation) { Assert.Equal(OperationKind.PropertyInitializer, operation.Kind); foreach (var property in operation.InitializedProperties) { Assert.NotNull(property); } VisitSymbolInitializer(operation); } public override void VisitParameterInitializer(IParameterInitializerOperation operation) { Assert.Equal(OperationKind.ParameterInitializer, operation.Kind); Assert.NotNull(operation.Parameter); VisitSymbolInitializer(operation); } public override void VisitArrayCreation(IArrayCreationOperation operation) { Assert.Equal(OperationKind.ArrayCreation, operation.Kind); IEnumerable<IOperation> children = operation.DimensionSizes; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitArrayInitializer(IArrayInitializerOperation operation) { Assert.Equal(OperationKind.ArrayInitializer, operation.Kind); Assert.Null(operation.Type); AssertEx.Equal(operation.ElementValues, operation.Children); } private void VisitAssignment(IAssignmentOperation operation) { AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { Assert.Equal(OperationKind.SimpleAssignment, operation.Kind); bool isRef = operation.IsRef; VisitAssignment(operation); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { Assert.Equal(OperationKind.CompoundAssignment, operation.Kind); var operatorMethod = operation.OperatorMethod; var binaryOperationKind = operation.OperatorKind; var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.Syntax.Language == LanguageNames.CSharp) { Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetOutConversion(operation)); var inConversionInternal = CSharp.CSharpExtensions.GetInConversion(operation); var outConversionInternal = CSharp.CSharpExtensions.GetOutConversion(operation); } else { Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetOutConversion(operation)); var inConversionInternal = VisualBasic.VisualBasicExtensions.GetInConversion(operation); var outConversionInternal = VisualBasic.VisualBasicExtensions.GetOutConversion(operation); } var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; VisitAssignment(operation); } public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Increment, OperationKind.Decrement }); var operatorMethod = operation.OperatorMethod; var isPostFix = operation.IsPostfix; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitParenthesized(IParenthesizedOperation operation) { Assert.Equal(OperationKind.Parenthesized, operation.Kind); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) { Assert.Equal(OperationKind.DynamicMemberReference, operation.Kind); Assert.NotNull(operation.MemberName); foreach (var typeArg in operation.TypeArguments) { Assert.NotNull(typeArg); } var containingType = operation.ContainingType; if (operation.Instance == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Instance, operation.Children.Single()); } } public override void VisitDefaultValue(IDefaultValueOperation operation) { Assert.Equal(OperationKind.DefaultValue, operation.Kind); Assert.Empty(operation.Children); } public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) { Assert.Equal(OperationKind.TypeParameterObjectCreation, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } public override void VisitInvalid(IInvalidOperation operation) { Assert.Equal(OperationKind.Invalid, operation.Kind); } public override void VisitTuple(ITupleOperation operation) { Assert.Equal(OperationKind.Tuple, operation.Kind); var naturalType = operation.NaturalType; AssertEx.Equal(operation.Elements, operation.Children); } public override void VisitInterpolatedString(IInterpolatedStringOperation operation) { Assert.Equal(OperationKind.InterpolatedString, operation.Kind); AssertEx.Equal(operation.Parts, operation.Children); } public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) { Assert.Equal(OperationKind.InterpolatedStringText, operation.Kind); if (operation.Text.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind); } Assert.Same(operation.Text, operation.Children.Single()); } public override void VisitInterpolation(IInterpolationOperation operation) { Assert.Equal(OperationKind.Interpolation, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Expression }; if (operation.Alignment != null) { children = children.Concat(new[] { operation.Alignment }); } if (operation.FormatString != null) { if (operation.FormatString.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind); } children = children.Concat(new[] { operation.FormatString }); } AssertEx.Equal(children, operation.Children); } public override void VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation) { Assert.Equal(OperationKind.InterpolatedStringHandlerCreation, operation.Kind); IEnumerable<IOperation> children = new[] { operation.HandlerCreation, operation.Content }; AssertEx.Equal(children, operation.Children); Assert.True(operation.HandlerCreation is IObjectCreationOperation or IDynamicObjectCreationOperation or IInvalidOperation); Assert.True(operation.Content is IInterpolatedStringAdditionOperation or IInterpolatedStringOperation); _ = operation.HandlerCreationHasSuccessParameter; _ = operation.HandlerAppendCallsReturnBool; } public override void VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation) { Assert.Equal(OperationKind.InterpolatedStringAddition, operation.Kind); AssertEx.Equal(new[] { operation.Left, operation.Right }, operation.Children); Assert.True(operation.Left is IInterpolatedStringAdditionOperation or IInterpolatedStringOperation); Assert.True(operation.Right is IInterpolatedStringAdditionOperation or IInterpolatedStringOperation); } public override void VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation) { Assert.Equal(OperationKind.InterpolatedStringHandlerArgumentPlaceholder, operation.Kind); if (operation.PlaceholderKind is InterpolatedStringArgumentPlaceholderKind.CallsiteReceiver or InterpolatedStringArgumentPlaceholderKind.TrailingValidityArgument) { Assert.Equal(-1, operation.ArgumentIndex); } else { Assert.Equal(InterpolatedStringArgumentPlaceholderKind.CallsiteArgument, operation.PlaceholderKind); Assert.True(operation.ArgumentIndex >= 0); } } public override void VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation) { Assert.True(operation.Kind is OperationKind.InterpolatedStringAppendFormatted or OperationKind.InterpolatedStringAppendLiteral or OperationKind.InterpolatedStringAppendInvalid); Assert.True(operation.AppendCall is IInvocationOperation or IDynamicInvocationOperation or IInvalidOperation); } private void VisitPatternCommon(IPatternOperation pattern) { Assert.NotNull(pattern.InputType); Assert.NotNull(pattern.NarrowedType); Assert.Null(pattern.Type); Assert.False(pattern.ConstantValue.HasValue); } public override void VisitConstantPattern(IConstantPatternOperation operation) { Assert.Equal(OperationKind.ConstantPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitRelationalPattern(IRelationalPatternOperation operation) { Assert.Equal(OperationKind.RelationalPattern, operation.Kind); Assert.True(operation.OperatorKind is Operations.BinaryOperatorKind.LessThan or Operations.BinaryOperatorKind.LessThanOrEqual or Operations.BinaryOperatorKind.GreaterThan or Operations.BinaryOperatorKind.GreaterThanOrEqual or Operations.BinaryOperatorKind.Equals or // Error cases Operations.BinaryOperatorKind.NotEquals); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitBinaryPattern(IBinaryPatternOperation operation) { Assert.Equal(OperationKind.BinaryPattern, operation.Kind); VisitPatternCommon(operation); Assert.True(operation.OperatorKind switch { Operations.BinaryOperatorKind.Or => true, Operations.BinaryOperatorKind.And => true, _ => false }); var children = operation.Children.ToArray(); Assert.Equal(2, children.Length); Assert.Same(operation.LeftPattern, children[0]); Assert.Same(operation.RightPattern, children[1]); } public override void VisitNegatedPattern(INegatedPatternOperation operation) { Assert.Equal(OperationKind.NegatedPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Pattern, operation.Children.Single()); } public override void VisitTypePattern(ITypePatternOperation operation) { Assert.Equal(OperationKind.TypePattern, operation.Kind); Assert.NotNull(operation.MatchedType); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { Assert.Equal(OperationKind.DeclarationPattern, operation.Kind); VisitPatternCommon(operation); if (operation.Syntax.IsKind(CSharp.SyntaxKind.VarPattern) || // in `var (x, y)`, the syntax here is the designation `x`. operation.Syntax.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.True(operation.MatchesNull); Assert.Null(operation.MatchedType); } else { Assert.False(operation.MatchesNull); Assert.NotNull(operation.MatchedType); } var designation = (operation.Syntax as CSharp.Syntax.DeclarationPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VarPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VariableDesignationSyntax); if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } Assert.Empty(operation.Children); } public override void VisitRecursivePattern(IRecursivePatternOperation operation) { Assert.Equal(OperationKind.RecursivePattern, operation.Kind); VisitPatternCommon(operation); Assert.NotNull(operation.MatchedType); switch (operation.DeconstructSymbol) { case IErrorTypeSymbol error: case null: // OK: indicates deconstruction of a tuple, or an error case break; case IMethodSymbol method: // when we have a method, it is a `Deconstruct` method Assert.Equal("Deconstruct", method.Name); break; case ITypeSymbol type: // when we have a type, it is the type "ITuple" Assert.Equal("ITuple", type.Name); break; default: Assert.True(false, $"Unexpected symbol {operation.DeconstructSymbol}"); break; } var designation = (operation.Syntax as CSharp.Syntax.RecursivePatternSyntax)?.Designation; if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } foreach (var subpat in operation.PropertySubpatterns) { Assert.True(subpat is IPropertySubpatternOperation); } IEnumerable<IOperation> children = operation.DeconstructionSubpatterns.Cast<IOperation>(); children = children.Concat(operation.PropertySubpatterns); AssertEx.Equal(children, operation.Children); } public override void VisitPropertySubpattern(IPropertySubpatternOperation operation) { Assert.NotNull(operation.Pattern); var children = new IOperation[] { operation.Member, operation.Pattern }; AssertEx.Equal(children, operation.Children); if (operation.Member.Kind == OperationKind.Invalid) { return; } Assert.True(operation.Member is IMemberReferenceOperation); var member = (IMemberReferenceOperation)operation.Member; switch (member.Member) { case IFieldSymbol field: case IPropertySymbol prop: break; case var symbol: Assert.True(false, $"Unexpected symbol {symbol}"); break; } } public override void VisitSwitchExpression(ISwitchExpressionOperation operation) { //force the existence of IsExhaustive _ = operation.IsExhaustive; Assert.NotNull(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.Equal(OperationKind.SwitchExpression, operation.Kind); Assert.NotNull(operation.Value); var children = operation.Arms.Cast<IOperation>().Prepend(operation.Value); AssertEx.Equal(children, operation.Children); } public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) { Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.NotNull(operation.Pattern); _ = operation.Guard; Assert.NotNull(operation.Value); VisitLocals(operation.Locals); var children = operation.Guard == null ? new[] { operation.Pattern, operation.Value } : new[] { operation.Pattern, operation.Guard, operation.Value }; AssertEx.Equal(children, operation.Children); } public override void VisitIsPattern(IIsPatternOperation operation) { Assert.Equal(OperationKind.IsPattern, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Pattern }, operation.Children); } public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Pattern, operation.CaseKind); Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label); if (operation.Guard != null) { AssertEx.Equal(new[] { operation.Pattern, operation.Guard }, operation.Children); } else { Assert.Same(operation.Pattern, operation.Children.Single()); } } public override void VisitTranslatedQuery(ITranslatedQueryOperation operation) { Assert.Equal(OperationKind.TranslatedQuery, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation) { Assert.Equal(OperationKind.DeclarationExpression, operation.Kind); Assert.Same(operation.Expression, operation.Children.Single()); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { Assert.Equal(OperationKind.DeconstructionAssignment, operation.Kind); VisitAssignment(operation); } public override void VisitDelegateCreation(IDelegateCreationOperation operation) { Assert.Equal(OperationKind.DelegateCreation, operation.Kind); Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitRaiseEvent(IRaiseEventOperation operation) { Assert.Equal(OperationKind.RaiseEvent, operation.Kind); AssertEx.Equal(new IOperation[] { operation.EventReference }.Concat(operation.Arguments), operation.Children); } public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Range, operation.CaseKind); AssertEx.Equal(new[] { operation.MinimumValue, operation.MaximumValue }, operation.Children); } public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation) { Assert.Equal(OperationKind.ConstructorBodyOperation, operation.Kind); Assert.Equal(OperationKind.ConstructorBody, operation.Kind); VisitLocals(operation.Locals); var builder = ArrayBuilder<IOperation>.GetInstance(); if (operation.Initializer != null) { builder.Add(operation.Initializer); } if (operation.BlockBody != null) { builder.Add(operation.BlockBody); } if (operation.ExpressionBody != null) { builder.Add(operation.ExpressionBody); } AssertEx.Equal(builder, operation.Children); builder.Free(); } public override void VisitMethodBodyOperation(IMethodBodyOperation operation) { Assert.Equal(OperationKind.MethodBodyOperation, operation.Kind); Assert.Equal(OperationKind.MethodBody, operation.Kind); if (operation.BlockBody != null) { if (operation.ExpressionBody != null) { AssertEx.Equal(new[] { operation.BlockBody, operation.ExpressionBody }, operation.Children); } else { Assert.Same(operation.BlockBody, operation.Children.Single()); } } else if (operation.ExpressionBody != null) { Assert.Same(operation.ExpressionBody, operation.Children.Single()); } else { Assert.Empty(operation.Children); } } public override void VisitDiscardOperation(IDiscardOperation operation) { Assert.Equal(OperationKind.Discard, operation.Kind); Assert.Empty(operation.Children); var discardSymbol = operation.DiscardSymbol; Assert.Equal(operation.Type, discardSymbol.Type); } public override void VisitDiscardPattern(IDiscardPatternOperation operation) { Assert.Equal(OperationKind.DiscardPattern, operation.Kind); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitFlowCapture(IFlowCaptureOperation operation) { Assert.Equal(OperationKind.FlowCapture, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Value, operation.Children.Single()); switch (operation.Value.Kind) { case OperationKind.Invalid: case OperationKind.None: case OperationKind.AnonymousFunction: case OperationKind.FlowCaptureReference: case OperationKind.DefaultValue: case OperationKind.FlowAnonymousFunction: // must be an error case like in Microsoft.CodeAnalysis.CSharp.UnitTests.ConditionalOperatorTests.TestBothUntyped unit-test break; case OperationKind.OmittedArgument: case OperationKind.DeclarationExpression: case OperationKind.Discard: Assert.False(true, $"A {operation.Value.Kind} node should not be spilled or captured."); break; default: // Only values can be spilled/captured if (!operation.Value.ConstantValue.HasValue || operation.Value.ConstantValue.Value != null) { Assert.NotNull(operation.Value.Type); } break; } } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { Assert.Equal(OperationKind.FlowCaptureReference, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitIsNull(IIsNullOperation operation) { Assert.Equal(OperationKind.IsNull, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitCaughtException(ICaughtExceptionOperation operation) { Assert.Equal(OperationKind.CaughtException, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) { Assert.Equal(OperationKind.StaticLocalInitializationSemaphore, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); Assert.NotNull(operation.Local); Assert.True(operation.Local.IsStatic); } public override void VisitRangeOperation(IRangeOperation operation) { Assert.Equal(OperationKind.Range, operation.Kind); IOperation[] children = operation.Children.ToArray(); int index = 0; if (operation.LeftOperand != null) { Assert.Same(operation.LeftOperand, children[index++]); } if (operation.RightOperand != null) { Assert.Same(operation.RightOperand, children[index++]); } Assert.Equal(index, children.Length); } public override void VisitReDim(IReDimOperation operation) { Assert.Equal(OperationKind.ReDim, operation.Kind); AssertEx.Equal(operation.Clauses, operation.Children); var preserve = operation.Preserve; } public override void VisitReDimClause(IReDimClauseOperation operation) { Assert.Equal(OperationKind.ReDimClause, operation.Kind); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.DimensionSizes), operation.Children); } public override void VisitUsingDeclaration(IUsingDeclarationOperation operation) { Assert.NotNull(operation.DeclarationGroup); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.DeclarationGroup), operation.Children); Assert.True(operation.DeclarationGroup.IsImplicit); Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); _ = operation.IsAsynchronous; _ = operation.IsImplicit; _ = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } public override void VisitWith(IWithOperation operation) { Assert.Equal(OperationKind.With, operation.Kind); _ = operation.CloneMethod; IEnumerable<IOperation> children = SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.Initializer); AssertEx.Equal(children, operation.Children); } } }
1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Options.EditorConfig; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity { [ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.ConfigureSeverity, LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] [ExtensionOrder(After = PredefinedConfigurationFixProviderNames.Suppression)] internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigurationFixProvider { private static readonly ImmutableArray<(string name, string value)> s_editorConfigSeverityStrings = ImmutableArray.Create( (nameof(EditorConfigSeverityStrings.None), EditorConfigSeverityStrings.None), (nameof(EditorConfigSeverityStrings.Silent), EditorConfigSeverityStrings.Silent), (nameof(EditorConfigSeverityStrings.Suggestion), EditorConfigSeverityStrings.Suggestion), (nameof(EditorConfigSeverityStrings.Warning), EditorConfigSeverityStrings.Warning), (nameof(EditorConfigSeverityStrings.Error), EditorConfigSeverityStrings.Error)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConfigureSeverityLevelCodeFixProvider() { } // We only offer fix for configurable diagnostics. // Also skip suppressed diagnostics defensively, though the code fix engine should ideally never call us for suppressed diagnostics. public bool IsFixableDiagnostic(Diagnostic diagnostic) => !diagnostic.IsSuppressed && !SuppressionHelpers.IsNotConfigurableDiagnostic(diagnostic); public FixAllProvider? GetFixAllProvider() => null; public Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) => Task.FromResult(GetConfigurations(document.Project, diagnostics, cancellationToken)); public Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) => Task.FromResult(GetConfigurations(project, diagnostics, cancellationToken)); private static ImmutableArray<CodeFix> GetConfigurations(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { var result = ArrayBuilder<CodeFix>.GetInstance(); var analyzerDiagnosticsByCategory = new SortedDictionary<string, ArrayBuilder<Diagnostic>>(); using var disposer = ArrayBuilder<Diagnostic>.GetInstance(out var analyzerDiagnostics); foreach (var diagnostic in diagnostics) { var nestedActions = ArrayBuilder<CodeAction>.GetInstance(); foreach (var (name, value) in s_editorConfigSeverityStrings) { nestedActions.Add( new SolutionChangeAction( name, solution => ConfigurationUpdater.ConfigureSeverityAsync(value, diagnostic, project, cancellationToken), name)); } var codeAction = new TopLevelConfigureSeverityCodeAction(diagnostic, nestedActions.ToImmutableAndFree()); result.Add(new CodeFix(project, codeAction, diagnostic)); // Bulk configuration is only supported for analyzer diagnostics. if (!SuppressionHelpers.IsCompilerDiagnostic(diagnostic)) { // Ensure diagnostic has a valid non-empty 'Category' for category based configuration. if (!string.IsNullOrEmpty(diagnostic.Descriptor.Category)) { var diagnosticsForCategory = analyzerDiagnosticsByCategory.GetOrAdd(diagnostic.Descriptor.Category, _ => ArrayBuilder<Diagnostic>.GetInstance()); diagnosticsForCategory.Add(diagnostic); } analyzerDiagnostics.Add(diagnostic); } } foreach (var (category, diagnosticsWithCategory) in analyzerDiagnosticsByCategory) { AddBulkConfigurationCodeFixes(diagnosticsWithCategory.ToImmutableAndFree(), category); } if (analyzerDiagnostics.Count > 0) { AddBulkConfigurationCodeFixes(analyzerDiagnostics.ToImmutable(), category: null); } return result.ToImmutableAndFree(); void AddBulkConfigurationCodeFixes(ImmutableArray<Diagnostic> diagnostics, string? category) { var nestedActions = ArrayBuilder<CodeAction>.GetInstance(); foreach (var (name, value) in s_editorConfigSeverityStrings) { nestedActions.Add( new SolutionChangeAction( name, solution => category != null ? ConfigurationUpdater.BulkConfigureSeverityAsync(value, category, project, cancellationToken) : ConfigurationUpdater.BulkConfigureSeverityAsync(value, project, cancellationToken), name)); } var codeAction = new TopLevelBulkConfigureSeverityCodeAction(nestedActions.ToImmutableAndFree(), category); result.Add(new CodeFix(project, codeAction, 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. using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Options.EditorConfig; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity { [ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.ConfigureSeverity, LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] [ExtensionOrder(After = PredefinedConfigurationFixProviderNames.Suppression)] internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigurationFixProvider { private static readonly ImmutableArray<(string name, string value)> s_editorConfigSeverityStrings = ImmutableArray.Create( (nameof(EditorConfigSeverityStrings.None), EditorConfigSeverityStrings.None), (nameof(EditorConfigSeverityStrings.Silent), EditorConfigSeverityStrings.Silent), (nameof(EditorConfigSeverityStrings.Suggestion), EditorConfigSeverityStrings.Suggestion), (nameof(EditorConfigSeverityStrings.Warning), EditorConfigSeverityStrings.Warning), (nameof(EditorConfigSeverityStrings.Error), EditorConfigSeverityStrings.Error)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConfigureSeverityLevelCodeFixProvider() { } // We only offer fix for configurable diagnostics. // Also skip suppressed diagnostics defensively, though the code fix engine should ideally never call us for suppressed diagnostics. public bool IsFixableDiagnostic(Diagnostic diagnostic) => !diagnostic.IsSuppressed && !SuppressionHelpers.IsNotConfigurableDiagnostic(diagnostic); public FixAllProvider? GetFixAllProvider() => null; public Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) => Task.FromResult(GetConfigurations(document.Project, diagnostics, cancellationToken)); public Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) => Task.FromResult(GetConfigurations(project, diagnostics, cancellationToken)); private static ImmutableArray<CodeFix> GetConfigurations(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { var result = ArrayBuilder<CodeFix>.GetInstance(); var analyzerDiagnosticsByCategory = new SortedDictionary<string, ArrayBuilder<Diagnostic>>(); using var disposer = ArrayBuilder<Diagnostic>.GetInstance(out var analyzerDiagnostics); foreach (var diagnostic in diagnostics) { var nestedActions = ArrayBuilder<CodeAction>.GetInstance(); foreach (var (name, value) in s_editorConfigSeverityStrings) { nestedActions.Add( new SolutionChangeAction( name, solution => ConfigurationUpdater.ConfigureSeverityAsync(value, diagnostic, project, cancellationToken), name)); } var codeAction = new TopLevelConfigureSeverityCodeAction(diagnostic, nestedActions.ToImmutableAndFree()); result.Add(new CodeFix(project, codeAction, diagnostic)); // Bulk configuration is only supported for analyzer diagnostics. if (!SuppressionHelpers.IsCompilerDiagnostic(diagnostic)) { // Ensure diagnostic has a valid non-empty 'Category' for category based configuration. if (!string.IsNullOrEmpty(diagnostic.Descriptor.Category)) { var diagnosticsForCategory = analyzerDiagnosticsByCategory.GetOrAdd(diagnostic.Descriptor.Category, _ => ArrayBuilder<Diagnostic>.GetInstance()); diagnosticsForCategory.Add(diagnostic); } analyzerDiagnostics.Add(diagnostic); } } foreach (var (category, diagnosticsWithCategory) in analyzerDiagnosticsByCategory) { AddBulkConfigurationCodeFixes(diagnosticsWithCategory.ToImmutableAndFree(), category); } if (analyzerDiagnostics.Count > 0) { AddBulkConfigurationCodeFixes(analyzerDiagnostics.ToImmutable(), category: null); } return result.ToImmutableAndFree(); void AddBulkConfigurationCodeFixes(ImmutableArray<Diagnostic> diagnostics, string? category) { var nestedActions = ArrayBuilder<CodeAction>.GetInstance(); foreach (var (name, value) in s_editorConfigSeverityStrings) { nestedActions.Add( new SolutionChangeAction( name, solution => category != null ? ConfigurationUpdater.BulkConfigureSeverityAsync(value, category, project, cancellationToken) : ConfigurationUpdater.BulkConfigureSeverityAsync(value, project, cancellationToken), name)); } var codeAction = new TopLevelBulkConfigureSeverityCodeAction(nestedActions.ToImmutableAndFree(), category); result.Add(new CodeFix(project, codeAction, diagnostics)); } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TriviaDataWithList.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics; namespace Microsoft.CodeAnalysis.Formatting { internal abstract class TriviaDataWithList : TriviaData { public TriviaDataWithList(AnalyzerConfigOptions options, string language) : base(options, language) { } public abstract SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Formatting { internal abstract class TriviaDataWithList : TriviaData { public TriviaDataWithList(AnalyzerConfigOptions options, string language) : base(options, language) { } public abstract SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Analyzers/CSharp/Tests/UseInferredMemberName/UseInferredMemberNameTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseInferredMemberName; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InferredMemberName { [Trait(Traits.Feature, Traits.Features.CodeActionsUseInferredMemberName)] public class UseInferredMemberNameTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseInferredMemberNameTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseInferredMemberNameDiagnosticAnalyzer(), new CSharpUseInferredMemberNameCodeFixProvider()); private static readonly CSharpParseOptions s_parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); [Fact] public async Task TestInferredTupleName() { await TestAsync( @" class C { void M() { int a = 1; var t = ([||]a: a, 2); } }", @" class C { void M() { int a = 1; var t = (a, 2); } }", parseOptions: s_parseOptions); } [Fact] [WorkItem(24480, "https://github.com/dotnet/roslyn/issues/24480")] public async Task TestInferredTupleName_WithAmbiguity() { await TestMissingAsync( @" class C { void M() { int alice = 1; (int, int, string) t = ([||]alice: alice, alice, null); } }", parameters: new TestParameters(parseOptions: s_parseOptions)); } [Fact] public async Task TestInferredTupleNameAfterCommaWithCSharp6() { await TestActionCountAsync( @" class C { void M() { int a = 2; var t = (1, [||]a: a); } }", count: 0, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact] public async Task TestInferredTupleNameAfterCommaWithCSharp7() { await TestActionCountAsync( @" class C { void M() { int a = 2; var t = (1, [||]a: a); } }", count: 0, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7))); } [Fact] public async Task TestFixAllInferredTupleNameWithTrivia() { await TestAsync( @" class C { void M() { int a = 1; int b = 2; var t = ( /*before*/ {|FixAllInDocument:a:|} /*middle*/ a /*after*/, /*before*/ b: /*middle*/ b /*after*/); } }", @" class C { void M() { int a = 1; int b = 2; var t = ( /*before*/ /*middle*/ a /*after*/, /*before*/ /*middle*/ b /*after*/); } }", parseOptions: s_parseOptions); } [Fact] public async Task TestInferredAnonymousTypeMemberName() { await TestAsync( @" class C { void M() { int a = 1; var t = new { [||]a= a, 2 }; } }", @" class C { void M() { int a = 1; var t = new { a, 2 }; } }", parseOptions: s_parseOptions); } [Fact] [WorkItem(24480, "https://github.com/dotnet/roslyn/issues/24480")] public async Task TestInferredAnonymousTypeMemberName_WithAmbiguity() { await TestMissingAsync( @" class C { void M() { int alice = 1; var t = new { [||]alice=alice, alice }; } }", parameters: new TestParameters(parseOptions: s_parseOptions)); } [Fact] public async Task TestFixAllInferredAnonymousTypeMemberNameWithTrivia() { await TestAsync( @" class C { void M() { int a = 1; int b = 2; var t = new { /*before*/ {|FixAllInDocument:a =|} /*middle*/ a /*after*/, /*before*/ b = /*middle*/ b /*after*/ }; } }", @" class C { void M() { int a = 1; int b = 2; var t = new { /*before*/ /*middle*/ a /*after*/, /*before*/ /*middle*/ b /*after*/ }; } }", parseOptions: s_parseOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseInferredMemberName; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InferredMemberName { [Trait(Traits.Feature, Traits.Features.CodeActionsUseInferredMemberName)] public class UseInferredMemberNameTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseInferredMemberNameTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseInferredMemberNameDiagnosticAnalyzer(), new CSharpUseInferredMemberNameCodeFixProvider()); private static readonly CSharpParseOptions s_parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); [Fact] public async Task TestInferredTupleName() { await TestAsync( @" class C { void M() { int a = 1; var t = ([||]a: a, 2); } }", @" class C { void M() { int a = 1; var t = (a, 2); } }", parseOptions: s_parseOptions); } [Fact] [WorkItem(24480, "https://github.com/dotnet/roslyn/issues/24480")] public async Task TestInferredTupleName_WithAmbiguity() { await TestMissingAsync( @" class C { void M() { int alice = 1; (int, int, string) t = ([||]alice: alice, alice, null); } }", parameters: new TestParameters(parseOptions: s_parseOptions)); } [Fact] public async Task TestInferredTupleNameAfterCommaWithCSharp6() { await TestActionCountAsync( @" class C { void M() { int a = 2; var t = (1, [||]a: a); } }", count: 0, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact] public async Task TestInferredTupleNameAfterCommaWithCSharp7() { await TestActionCountAsync( @" class C { void M() { int a = 2; var t = (1, [||]a: a); } }", count: 0, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7))); } [Fact] public async Task TestFixAllInferredTupleNameWithTrivia() { await TestAsync( @" class C { void M() { int a = 1; int b = 2; var t = ( /*before*/ {|FixAllInDocument:a:|} /*middle*/ a /*after*/, /*before*/ b: /*middle*/ b /*after*/); } }", @" class C { void M() { int a = 1; int b = 2; var t = ( /*before*/ /*middle*/ a /*after*/, /*before*/ /*middle*/ b /*after*/); } }", parseOptions: s_parseOptions); } [Fact] public async Task TestInferredAnonymousTypeMemberName() { await TestAsync( @" class C { void M() { int a = 1; var t = new { [||]a= a, 2 }; } }", @" class C { void M() { int a = 1; var t = new { a, 2 }; } }", parseOptions: s_parseOptions); } [Fact] [WorkItem(24480, "https://github.com/dotnet/roslyn/issues/24480")] public async Task TestInferredAnonymousTypeMemberName_WithAmbiguity() { await TestMissingAsync( @" class C { void M() { int alice = 1; var t = new { [||]alice=alice, alice }; } }", parameters: new TestParameters(parseOptions: s_parseOptions)); } [Fact] public async Task TestFixAllInferredAnonymousTypeMemberNameWithTrivia() { await TestAsync( @" class C { void M() { int a = 1; int b = 2; var t = new { /*before*/ {|FixAllInDocument:a =|} /*middle*/ a /*after*/, /*before*/ b = /*middle*/ b /*after*/ }; } }", @" class C { void M() { int a = 1; int b = 2; var t = new { /*before*/ /*middle*/ a /*after*/, /*before*/ /*middle*/ b /*after*/ }; } }", parseOptions: s_parseOptions); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Empty.Dictionary.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Dictionary<TKey, TValue> #nullable disable // Note: if the interfaces we implement weren't oblivious, then we'd warn about the `[MaybeNullWhen(false)] out TValue value` parameter below // We can remove this once `IDictionary` is annotated with `[MaybeNullWhen(false)]` : Collection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> #nullable enable where TKey : notnull { public static new readonly Dictionary<TKey, TValue> Instance = new(); private Dictionary() { } public void Add(TKey key, TValue value) { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return false; } public ICollection<TKey> Keys { get { return Collection<TKey>.Instance; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys; IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values; public bool Remove(TKey key) { throw new NotSupportedException(); } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { value = default!; return false; } public ICollection<TValue> Values { get { return Collection<TValue>.Instance; } } public TValue this[TKey key] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Dictionary<TKey, TValue> #nullable disable // Note: if the interfaces we implement weren't oblivious, then we'd warn about the `[MaybeNullWhen(false)] out TValue value` parameter below // We can remove this once `IDictionary` is annotated with `[MaybeNullWhen(false)]` : Collection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> #nullable enable where TKey : notnull { public static new readonly Dictionary<TKey, TValue> Instance = new(); private Dictionary() { } public void Add(TKey key, TValue value) { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return false; } public ICollection<TKey> Keys { get { return Collection<TKey>.Instance; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys; IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values; public bool Remove(TKey key) { throw new NotSupportedException(); } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { value = default!; return false; } public ICollection<TValue> Values { get { return Collection<TValue>.Instance; } } public TValue this[TKey key] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/CoreTest/Host/WorkspaceServices/TestProjectCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.UnitTests.Persistence { [ExportWorkspaceService(typeof(IProjectCacheHostService), ServiceLayer.Test), Shared, PartNotDiscoverable] public class TestProjectCacheService : IProjectCacheHostService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestProjectCacheService() { } T IProjectCacheHostService.CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T instance) => instance; T IProjectCacheHostService.CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T instance) => instance; IDisposable IProjectCacheService.EnableCaching(ProjectId key) => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.UnitTests.Persistence { [ExportWorkspaceService(typeof(IProjectCacheHostService), ServiceLayer.Test), Shared, PartNotDiscoverable] public class TestProjectCacheService : IProjectCacheHostService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestProjectCacheService() { } T IProjectCacheHostService.CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T instance) => instance; T IProjectCacheHostService.CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T instance) => instance; IDisposable IProjectCacheService.EnableCaching(ProjectId key) => null; } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/FormatSpecifierTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class FormatSpecifierTests : CSharpResultProviderTestBase { [Fact] public void NoQuotes_String() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes); var stringType = runtime.GetType(typeof(string)); // null var value = CreateDkmClrValue(null, type: stringType); var evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "null", "string", "s", editableValue: null, flags: DkmEvaluationResultFlags.None)); // "" value = CreateDkmClrValue(string.Empty, type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "", "string", "s", editableValue: "\"\"", flags: DkmEvaluationResultFlags.RawString)); // "'" value = CreateDkmClrValue("'", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "'", "string", "s", editableValue: "\"'\"", flags: DkmEvaluationResultFlags.RawString)); // "\"" value = CreateDkmClrValue("\"", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\"", "string", "s", editableValue: "\"\\\"\"", flags: DkmEvaluationResultFlags.RawString)); // "\\" value = CreateDkmClrValue("\\", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\\", "string", "s", editableValue: "\"\\\\\"", flags: DkmEvaluationResultFlags.RawString)); // "a\r\n\t\v\b\u001eb" value = CreateDkmClrValue("a\r\n\tb\v\b\u001ec", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "a\r\n\tb\v\b\u001ec", "string", "s", editableValue: "\"a\\r\\n\\tb\\v\\b\\u001ec\"", flags: DkmEvaluationResultFlags.RawString)); // "a\0b" value = CreateDkmClrValue("a\0b", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "a\0b", "string", "s", editableValue: "\"a\\0b\"", flags: DkmEvaluationResultFlags.RawString)); // "\u007f\u009f" value = CreateDkmClrValue("\u007f\u009f", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\u007f\u009f", "string", "s", editableValue: "\"\\u007f\\u009f\"", flags: DkmEvaluationResultFlags.RawString)); // " " with alias value = CreateDkmClrValue(" ", type: stringType, alias: "$1", evalFlags: DkmEvaluationResultFlags.HasObjectId); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", " {$1}", "string", "s", editableValue: "\" \"", flags: DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.HasObjectId)); // array value = CreateDkmClrValue(new string[] { "1" }, type: stringType.MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{string[1]}", "string[]", "a", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); // DkmInspectionContext should not be inherited. Verify(children, EvalResult("[0]", "\"1\"", "string", "a[0]", editableValue: "\"1\"", flags: DkmEvaluationResultFlags.RawString)); } [Fact] public void NoQuotes_Char() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes); var charType = runtime.GetType(typeof(char)); // 0 var value = CreateDkmClrValue((char)0, type: charType); var evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "0 \0", "char", "c", editableValue: "'\\0'", flags: DkmEvaluationResultFlags.None)); // '\'' value = CreateDkmClrValue('\'', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "39 '", "char", "c", editableValue: "'\\''", flags: DkmEvaluationResultFlags.None)); // '"' value = CreateDkmClrValue('"', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "34 \"", "char", "c", editableValue: "'\"'", flags: DkmEvaluationResultFlags.None)); // '\\' value = CreateDkmClrValue('\\', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "92 \\", "char", "c", editableValue: "'\\\\'", flags: DkmEvaluationResultFlags.None)); // '\n' value = CreateDkmClrValue('\n', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "10 \n", "char", "c", editableValue: "'\\n'", flags: DkmEvaluationResultFlags.None)); // '\u001e' value = CreateDkmClrValue('\u001e', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "30 \u001e", "char", "c", editableValue: "'\\u001e'", flags: DkmEvaluationResultFlags.None)); // '\u007f' value = CreateDkmClrValue('\u007f', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "127 \u007f", "char", "c", editableValue: "'\\u007f'", flags: DkmEvaluationResultFlags.None)); // array value = CreateDkmClrValue(new char[] { '1' }, type: charType.MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{char[1]}", "char[]", "a", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); // DkmInspectionContext should not be inherited. Verify(children, EvalResult("[0]", "49 '1'", "char", "a[0]", editableValue: "'1'", flags: DkmEvaluationResultFlags.None)); } [Fact] public void NoQuotes_DebuggerDisplay() { var source = @"using System.Diagnostics; [DebuggerDisplay(""{F}+{G}"")] class C { string F = ""f""; object G = 'g'; }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes)); Verify(evalResult, EvalResult("o", "f+103 g", "C", "o", DkmEvaluationResultFlags.Expandable)); } } [Fact] public void RawView_NoProxy() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw); // int var value = CreateDkmClrValue(1, type: runtime.GetType(typeof(int))); var evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("i", "1", "int", "i, raw", editableValue: null, flags: DkmEvaluationResultFlags.None)); // string value = CreateDkmClrValue(string.Empty, type: runtime.GetType(typeof(string))); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\"\"", "string", "s, raw", editableValue: "\"\"", flags: DkmEvaluationResultFlags.RawString)); // object[] value = CreateDkmClrValue(new object[] { 1, 2, 3 }, type: runtime.GetType(typeof(object)).MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{object[3]}", "object[]", "a, raw", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); } [Fact] public void RawView() { var source = @"using System.Diagnostics; internal class P { public P(C c) { this.G = c.F != null; } public readonly bool G; } [DebuggerTypeProxy(typeof(P))] class C { internal C() : this(new C(null)) { } internal C(C f) { this.F = f; } internal readonly C F; } class Program { static void Main() { var o = new C(); System.Diagnostics.Debugger.Break(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); // Non-null value. var value = type.Instantiate(); var evalResult = FormatResult("o", "o, raw", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, raw", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{C}", "C", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); children = GetChildren(children[0]); // ShowValueRaw is not inherited. Verify(children, EvalResult("G", "false", "bool", "new P(o.F).G", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Null value. value = CreateDkmClrValue( value: null, type: type); evalResult = FormatResult("o", "o, raw", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw)); Verify(evalResult, EvalResult("o", "null", "C", "o, raw")); } } [Fact] public void ResultsView_FrameworkTypes() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly); // object: not enumerable var value = CreateDkmClrValue(new object(), type: runtime.GetType(typeof(object))); var evalResult = FormatResult("o", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("o", "Only Enumerable types can have Results View", fullName: null)); // string: not considered enumerable which is consistent with legacy EE value = CreateDkmClrValue("", type: runtime.GetType(typeof(string))); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("s", "Only Enumerable types can have Results View")); // Array: not considered enumerable which is consistent with legacy EE value = CreateDkmClrValue(new[] { 1 }, type: runtime.GetType(typeof(int[]))); evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("i", "Only Enumerable types can have Results View")); // ArrayList value = CreateDkmClrValue(new System.Collections.ArrayList(new[] { 2 }), type: runtime.GetType(typeof(System.Collections.ArrayList))); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "Count = 1", "System.Collections.ArrayList", "a, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(a).Items[0]")); // List<object> value = CreateDkmClrValue(new System.Collections.Generic.List<object>(new object[] { 3 }), type: runtime.GetType(typeof(System.Collections.Generic.List<object>))); evalResult = FormatResult("l", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("l", "Count = 1", "System.Collections.Generic.List<object>", "l, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "3", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(l).Items[0]")); // int? value = CreateDkmClrValue(1, type: runtime.GetType(typeof(System.Nullable<>)).MakeGenericType(runtime.GetType(typeof(int)))); evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("i", "Only Enumerable types can have Results View")); } [Fact] public void ResultsView_IEnumerable() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return new C(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results, d", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, results, d", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); // ResultsOnly is not inherited. Verify(children, EvalResult("[0]", "{C}", "object {C}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]")); } } [Fact] public void ResultsView_IEnumerableOfT() { var source = @"using System; using System.Collections; using System.Collections.Generic; struct S<T> : IEnumerable<T> { private readonly T t; internal S(T t) { this.t = t; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { yield return t; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("S`1").MakeGenericType(runtime.GetType(typeof(int))); var value = type.Instantiate(2); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{S<int>}", "S<int>", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]")); } } /// <summary> /// ResultsOnly is ignored for GetChildren and GetItems. /// </summary> [Fact] public void ResultsView_GetChildren() { var source = @"using System.Collections; using System.Collections.Generic; class C { IEnumerable<int> F { get { yield return 1; } } IEnumerable G { get { yield return 2; } } int H { get { return 3; } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // GetChildren without ResultsOnly var children = GetChildren(evalResult, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.None)); Verify(children, EvalResult("F", "{C.<get_F>d__1}", "System.Collections.Generic.IEnumerable<int> {C.<get_F>d__1}", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite), EvalResult("G", "{C.<get_G>d__3}", "System.Collections.IEnumerable {C.<get_G>d__3}", "o.G", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite), EvalResult("H", "3", "int", "o.H", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite)); // GetChildren with ResultsOnly children = GetChildren(evalResult, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(children, EvalResult("F", "{C.<get_F>d__1}", "System.Collections.Generic.IEnumerable<int> {C.<get_F>d__1}", "o.F, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult("G", "{C.<get_G>d__3}", "System.Collections.IEnumerable {C.<get_G>d__3}", "o.G, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalFailedResult("H", "Only Enumerable types can have Results View", fullName: null)); } } /// <summary> /// [DebuggerTypeProxy] should be ignored. /// </summary> [Fact] public void ResultsView_TypeProxy() { var source = @"using System.Collections; using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } } class P { public P(C c) { } public object F { get { return 2; } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); } } [Fact] public void ResultsView_ExceptionThrown() { var source = @"using System; using System.Collections; class E : Exception, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 1; } } class C { internal ArrayList P { get { throw new NotImplementedException(); } } internal ArrayList Q { get { throw new E(); } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); var evalResult = FormatResult("o.P", "o.P, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.P", "'o.P' threw an exception of type 'System.NotImplementedException'")); memberValue = value.GetMemberValue("Q", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); evalResult = FormatResult("o.Q", "o.Q, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.Q", "'o.Q' threw an exception of type 'E'")); } } /// <summary> /// Report the error message for error values, regardless /// of whether the value is actually enumerable. /// </summary> [Fact] public void ResultsView_Error() { var source = @"using System.Collections; class C { bool f; internal ArrayList P { get { while (!this.f) { } return new ArrayList(); } } internal int Q { get { while (!this.f) { } return 3; } } }"; DkmClrRuntimeInstance runtime = null; VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue getMemberValue(VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue v, string m) { switch (m) { case "P": return CreateErrorValue(runtime.GetType(typeof(System.Collections.ArrayList)), "Property 'P' evaluation timed out"); case "Q": return CreateErrorValue(runtime.GetType(typeof(string)), "Property 'Q' evaluation timed out"); default: return null; } } runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); var evalResult = FormatResult("o.P", "o.P, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.P", "Property 'P' evaluation timed out")); memberValue = value.GetMemberValue("Q", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); evalResult = FormatResult("o.Q", "o.Q, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.Q", "Property 'Q' evaluation timed out")); } } [Fact] public void ResultsView_NoSystemCore() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o", "Results View requires System.Core.dll to be referenced")); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class FormatSpecifierTests : CSharpResultProviderTestBase { [Fact] public void NoQuotes_String() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes); var stringType = runtime.GetType(typeof(string)); // null var value = CreateDkmClrValue(null, type: stringType); var evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "null", "string", "s", editableValue: null, flags: DkmEvaluationResultFlags.None)); // "" value = CreateDkmClrValue(string.Empty, type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "", "string", "s", editableValue: "\"\"", flags: DkmEvaluationResultFlags.RawString)); // "'" value = CreateDkmClrValue("'", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "'", "string", "s", editableValue: "\"'\"", flags: DkmEvaluationResultFlags.RawString)); // "\"" value = CreateDkmClrValue("\"", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\"", "string", "s", editableValue: "\"\\\"\"", flags: DkmEvaluationResultFlags.RawString)); // "\\" value = CreateDkmClrValue("\\", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\\", "string", "s", editableValue: "\"\\\\\"", flags: DkmEvaluationResultFlags.RawString)); // "a\r\n\t\v\b\u001eb" value = CreateDkmClrValue("a\r\n\tb\v\b\u001ec", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "a\r\n\tb\v\b\u001ec", "string", "s", editableValue: "\"a\\r\\n\\tb\\v\\b\\u001ec\"", flags: DkmEvaluationResultFlags.RawString)); // "a\0b" value = CreateDkmClrValue("a\0b", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "a\0b", "string", "s", editableValue: "\"a\\0b\"", flags: DkmEvaluationResultFlags.RawString)); // "\u007f\u009f" value = CreateDkmClrValue("\u007f\u009f", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\u007f\u009f", "string", "s", editableValue: "\"\\u007f\\u009f\"", flags: DkmEvaluationResultFlags.RawString)); // " " with alias value = CreateDkmClrValue(" ", type: stringType, alias: "$1", evalFlags: DkmEvaluationResultFlags.HasObjectId); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", " {$1}", "string", "s", editableValue: "\" \"", flags: DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.HasObjectId)); // array value = CreateDkmClrValue(new string[] { "1" }, type: stringType.MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{string[1]}", "string[]", "a", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); // DkmInspectionContext should not be inherited. Verify(children, EvalResult("[0]", "\"1\"", "string", "a[0]", editableValue: "\"1\"", flags: DkmEvaluationResultFlags.RawString)); } [Fact] public void NoQuotes_Char() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes); var charType = runtime.GetType(typeof(char)); // 0 var value = CreateDkmClrValue((char)0, type: charType); var evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "0 \0", "char", "c", editableValue: "'\\0'", flags: DkmEvaluationResultFlags.None)); // '\'' value = CreateDkmClrValue('\'', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "39 '", "char", "c", editableValue: "'\\''", flags: DkmEvaluationResultFlags.None)); // '"' value = CreateDkmClrValue('"', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "34 \"", "char", "c", editableValue: "'\"'", flags: DkmEvaluationResultFlags.None)); // '\\' value = CreateDkmClrValue('\\', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "92 \\", "char", "c", editableValue: "'\\\\'", flags: DkmEvaluationResultFlags.None)); // '\n' value = CreateDkmClrValue('\n', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "10 \n", "char", "c", editableValue: "'\\n'", flags: DkmEvaluationResultFlags.None)); // '\u001e' value = CreateDkmClrValue('\u001e', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "30 \u001e", "char", "c", editableValue: "'\\u001e'", flags: DkmEvaluationResultFlags.None)); // '\u007f' value = CreateDkmClrValue('\u007f', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "127 \u007f", "char", "c", editableValue: "'\\u007f'", flags: DkmEvaluationResultFlags.None)); // array value = CreateDkmClrValue(new char[] { '1' }, type: charType.MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{char[1]}", "char[]", "a", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); // DkmInspectionContext should not be inherited. Verify(children, EvalResult("[0]", "49 '1'", "char", "a[0]", editableValue: "'1'", flags: DkmEvaluationResultFlags.None)); } [Fact] public void NoQuotes_DebuggerDisplay() { var source = @"using System.Diagnostics; [DebuggerDisplay(""{F}+{G}"")] class C { string F = ""f""; object G = 'g'; }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes)); Verify(evalResult, EvalResult("o", "f+103 g", "C", "o", DkmEvaluationResultFlags.Expandable)); } } [Fact] public void RawView_NoProxy() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw); // int var value = CreateDkmClrValue(1, type: runtime.GetType(typeof(int))); var evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("i", "1", "int", "i, raw", editableValue: null, flags: DkmEvaluationResultFlags.None)); // string value = CreateDkmClrValue(string.Empty, type: runtime.GetType(typeof(string))); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\"\"", "string", "s, raw", editableValue: "\"\"", flags: DkmEvaluationResultFlags.RawString)); // object[] value = CreateDkmClrValue(new object[] { 1, 2, 3 }, type: runtime.GetType(typeof(object)).MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{object[3]}", "object[]", "a, raw", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); } [Fact] public void RawView() { var source = @"using System.Diagnostics; internal class P { public P(C c) { this.G = c.F != null; } public readonly bool G; } [DebuggerTypeProxy(typeof(P))] class C { internal C() : this(new C(null)) { } internal C(C f) { this.F = f; } internal readonly C F; } class Program { static void Main() { var o = new C(); System.Diagnostics.Debugger.Break(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); // Non-null value. var value = type.Instantiate(); var evalResult = FormatResult("o", "o, raw", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, raw", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{C}", "C", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); children = GetChildren(children[0]); // ShowValueRaw is not inherited. Verify(children, EvalResult("G", "false", "bool", "new P(o.F).G", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Null value. value = CreateDkmClrValue( value: null, type: type); evalResult = FormatResult("o", "o, raw", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw)); Verify(evalResult, EvalResult("o", "null", "C", "o, raw")); } } [Fact] public void ResultsView_FrameworkTypes() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly); // object: not enumerable var value = CreateDkmClrValue(new object(), type: runtime.GetType(typeof(object))); var evalResult = FormatResult("o", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("o", "Only Enumerable types can have Results View", fullName: null)); // string: not considered enumerable which is consistent with legacy EE value = CreateDkmClrValue("", type: runtime.GetType(typeof(string))); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("s", "Only Enumerable types can have Results View")); // Array: not considered enumerable which is consistent with legacy EE value = CreateDkmClrValue(new[] { 1 }, type: runtime.GetType(typeof(int[]))); evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("i", "Only Enumerable types can have Results View")); // ArrayList value = CreateDkmClrValue(new System.Collections.ArrayList(new[] { 2 }), type: runtime.GetType(typeof(System.Collections.ArrayList))); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "Count = 1", "System.Collections.ArrayList", "a, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(a).Items[0]")); // List<object> value = CreateDkmClrValue(new System.Collections.Generic.List<object>(new object[] { 3 }), type: runtime.GetType(typeof(System.Collections.Generic.List<object>))); evalResult = FormatResult("l", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("l", "Count = 1", "System.Collections.Generic.List<object>", "l, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "3", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(l).Items[0]")); // int? value = CreateDkmClrValue(1, type: runtime.GetType(typeof(System.Nullable<>)).MakeGenericType(runtime.GetType(typeof(int)))); evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("i", "Only Enumerable types can have Results View")); } [Fact] public void ResultsView_IEnumerable() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return new C(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results, d", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, results, d", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); // ResultsOnly is not inherited. Verify(children, EvalResult("[0]", "{C}", "object {C}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]")); } } [Fact] public void ResultsView_IEnumerableOfT() { var source = @"using System; using System.Collections; using System.Collections.Generic; struct S<T> : IEnumerable<T> { private readonly T t; internal S(T t) { this.t = t; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { yield return t; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("S`1").MakeGenericType(runtime.GetType(typeof(int))); var value = type.Instantiate(2); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{S<int>}", "S<int>", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]")); } } /// <summary> /// ResultsOnly is ignored for GetChildren and GetItems. /// </summary> [Fact] public void ResultsView_GetChildren() { var source = @"using System.Collections; using System.Collections.Generic; class C { IEnumerable<int> F { get { yield return 1; } } IEnumerable G { get { yield return 2; } } int H { get { return 3; } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // GetChildren without ResultsOnly var children = GetChildren(evalResult, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.None)); Verify(children, EvalResult("F", "{C.<get_F>d__1}", "System.Collections.Generic.IEnumerable<int> {C.<get_F>d__1}", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite), EvalResult("G", "{C.<get_G>d__3}", "System.Collections.IEnumerable {C.<get_G>d__3}", "o.G", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite), EvalResult("H", "3", "int", "o.H", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite)); // GetChildren with ResultsOnly children = GetChildren(evalResult, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(children, EvalResult("F", "{C.<get_F>d__1}", "System.Collections.Generic.IEnumerable<int> {C.<get_F>d__1}", "o.F, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult("G", "{C.<get_G>d__3}", "System.Collections.IEnumerable {C.<get_G>d__3}", "o.G, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalFailedResult("H", "Only Enumerable types can have Results View", fullName: null)); } } /// <summary> /// [DebuggerTypeProxy] should be ignored. /// </summary> [Fact] public void ResultsView_TypeProxy() { var source = @"using System.Collections; using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } } class P { public P(C c) { } public object F { get { return 2; } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); } } [Fact] public void ResultsView_ExceptionThrown() { var source = @"using System; using System.Collections; class E : Exception, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 1; } } class C { internal ArrayList P { get { throw new NotImplementedException(); } } internal ArrayList Q { get { throw new E(); } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); var evalResult = FormatResult("o.P", "o.P, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.P", "'o.P' threw an exception of type 'System.NotImplementedException'")); memberValue = value.GetMemberValue("Q", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); evalResult = FormatResult("o.Q", "o.Q, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.Q", "'o.Q' threw an exception of type 'E'")); } } /// <summary> /// Report the error message for error values, regardless /// of whether the value is actually enumerable. /// </summary> [Fact] public void ResultsView_Error() { var source = @"using System.Collections; class C { bool f; internal ArrayList P { get { while (!this.f) { } return new ArrayList(); } } internal int Q { get { while (!this.f) { } return 3; } } }"; DkmClrRuntimeInstance runtime = null; VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue getMemberValue(VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue v, string m) { switch (m) { case "P": return CreateErrorValue(runtime.GetType(typeof(System.Collections.ArrayList)), "Property 'P' evaluation timed out"); case "Q": return CreateErrorValue(runtime.GetType(typeof(string)), "Property 'Q' evaluation timed out"); default: return null; } } runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); var evalResult = FormatResult("o.P", "o.P, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.P", "Property 'P' evaluation timed out")); memberValue = value.GetMemberValue("Q", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); evalResult = FormatResult("o.Q", "o.Q, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.Q", "Property 'Q' evaluation timed out")); } } [Fact] public void ResultsView_NoSystemCore() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o", "Results View requires System.Core.dll to be referenced")); } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/CSharpTest/Structure/ParenthesizedLambdaStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class ParenthesizedLambdaStructureTests : AbstractCSharpSyntaxNodeStructureTests<ParenthesizedLambdaExpressionSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new ParenthesizedLambdaExpressionStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambda() { const string code = @" class C { void M() { {|hint:$$() => {|textspan:{ x(); };|}|} } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInForLoop() { const string code = @" class C { void M() { for (Action a = $$() => { }; true; a()) { } } }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall1() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$(x, y, z) => {|textspan:{ return x + y + z; }|}|}, ""other arguments""); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall2() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$(x, y, z) => {|textspan:{ return x + y + z; }|}|}); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class ParenthesizedLambdaStructureTests : AbstractCSharpSyntaxNodeStructureTests<ParenthesizedLambdaExpressionSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new ParenthesizedLambdaExpressionStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambda() { const string code = @" class C { void M() { {|hint:$$() => {|textspan:{ x(); };|}|} } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInForLoop() { const string code = @" class C { void M() { for (Action a = $$() => { }; true; a()) { } } }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall1() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$(x, y, z) => {|textspan:{ return x + y + z; }|}|}, ""other arguments""); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall2() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$(x, y, z) => {|textspan:{ return x + y + z; }|}|}); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpProjectShim.ICSInputSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal partial class CSharpProjectShim : ICSInputSet { public ICSCompiler GetCompiler() => throw new NotImplementedException(); public void AddSourceFile(string filename) { // Nothing to do here. We watch addition/removal of source files via the ICSharpProjectSite methods. } public void RemoveSourceFile(string filename) { // Nothing to do here. We watch addition/removal of source files via the ICSharpProjectSite methods. } public void RemoveAllSourceFiles() => throw new NotImplementedException(); public void AddResourceFile(string filename, string ident, bool embed, bool vis) => throw new NotImplementedException(); public void RemoveResourceFile(string filename, string ident, bool embed, bool vis) => throw new NotImplementedException(); public void SetWin32Resource(string filename) { // This file is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetOutputFileName(string filename) { // Some projects like web projects give us just a filename; those aren't really useful (they're just filler) so we'll ignore them for purposes of tracking the path if (PathUtilities.IsAbsolute(filename)) { VisualStudioProject.CompilationOutputAssemblyFilePath = filename; } if (filename != null) { VisualStudioProject.AssemblyName = Path.GetFileNameWithoutExtension(filename); } RefreshBinOutputPath(); } public void SetOutputFileType(OutputFileType fileType) => VisualStudioProjectOptionsProcessor.SetOutputFileType(fileType); public void SetImageBase(uint imageBase) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetMainClass(string fullyQualifiedClassName) => VisualStudioProjectOptionsProcessor.SetMainTypeName(fullyQualifiedClassName); public void SetWin32Icon(string iconFileName) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetFileAlignment(uint align) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetImageBase2(ulong imageBase) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetPdbFileName(string filename) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public string GetWin32Resource() => throw new NotImplementedException(); public void SetWin32Manifest(string manifestFileName) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this 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 System; using System.IO; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal partial class CSharpProjectShim : ICSInputSet { public ICSCompiler GetCompiler() => throw new NotImplementedException(); public void AddSourceFile(string filename) { // Nothing to do here. We watch addition/removal of source files via the ICSharpProjectSite methods. } public void RemoveSourceFile(string filename) { // Nothing to do here. We watch addition/removal of source files via the ICSharpProjectSite methods. } public void RemoveAllSourceFiles() => throw new NotImplementedException(); public void AddResourceFile(string filename, string ident, bool embed, bool vis) => throw new NotImplementedException(); public void RemoveResourceFile(string filename, string ident, bool embed, bool vis) => throw new NotImplementedException(); public void SetWin32Resource(string filename) { // This file is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetOutputFileName(string filename) { // Some projects like web projects give us just a filename; those aren't really useful (they're just filler) so we'll ignore them for purposes of tracking the path if (PathUtilities.IsAbsolute(filename)) { VisualStudioProject.CompilationOutputAssemblyFilePath = filename; } if (filename != null) { VisualStudioProject.AssemblyName = Path.GetFileNameWithoutExtension(filename); } RefreshBinOutputPath(); } public void SetOutputFileType(OutputFileType fileType) => VisualStudioProjectOptionsProcessor.SetOutputFileType(fileType); public void SetImageBase(uint imageBase) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetMainClass(string fullyQualifiedClassName) => VisualStudioProjectOptionsProcessor.SetMainTypeName(fullyQualifiedClassName); public void SetWin32Icon(string iconFileName) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetFileAlignment(uint align) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetImageBase2(ulong imageBase) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public void SetPdbFileName(string filename) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } public string GetWin32Resource() => throw new NotImplementedException(); public void SetWin32Manifest(string manifestFileName) { // This option is used only during emit. Since we no longer use our in-proc workspace to emit, we can ignore this value. } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedStatementHighlighterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class CheckedStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(CheckedStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { short x = 0; short y = 100; while (true) { {|Cursor:[|checked|]|} { x++; } unchecked { y++; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { void M() { short x = 0; short y = 100; while (true) { checked { x++; } {|Cursor:[|unchecked|]|} { y++; } } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class CheckedStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(CheckedStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { short x = 0; short y = 100; while (true) { {|Cursor:[|checked|]|} { x++; } unchecked { y++; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { void M() { short x = 0; short y = 100; while (true) { checked { x++; } {|Cursor:[|unchecked|]|} { y++; } } } }"); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/Core/Tagging/AsynchronousTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal abstract class AsynchronousTaggerProvider<TTag> : AbstractAsynchronousTaggerProvider<TTag>, ITaggerProvider where TTag : ITag { protected AsynchronousTaggerProvider( IThreadingContext threadingContext, IAsynchronousOperationListener asyncListener) : base(threadingContext, asyncListener) { } public ITagger<T> CreateTagger<T>(ITextBuffer subjectBuffer) where T : ITag { if (subjectBuffer == null) throw new ArgumentNullException(nameof(subjectBuffer)); return this.CreateTaggerWorker<T>(null, subjectBuffer); } ITagger<T> ITaggerProvider.CreateTagger<T>(ITextBuffer buffer) => CreateTagger<T>(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. #nullable disable using System; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal abstract class AsynchronousTaggerProvider<TTag> : AbstractAsynchronousTaggerProvider<TTag>, ITaggerProvider where TTag : ITag { protected AsynchronousTaggerProvider( IThreadingContext threadingContext, IAsynchronousOperationListener asyncListener) : base(threadingContext, asyncListener) { } public ITagger<T> CreateTagger<T>(ITextBuffer subjectBuffer) where T : ITag { if (subjectBuffer == null) throw new ArgumentNullException(nameof(subjectBuffer)); return this.CreateTaggerWorker<T>(null, subjectBuffer); } ITagger<T> ITaggerProvider.CreateTagger<T>(ITextBuffer buffer) => CreateTagger<T>(buffer); } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/StackTraceExplorer/StackTraceExplorerViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ObjectModel; using System.Linq; using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.StackTraceExplorer; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Text.Classification; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Editor.Host; namespace Microsoft.VisualStudio.LanguageServices.StackTraceExplorer { internal class StackTraceExplorerViewModel : ViewModelBase { private readonly IThreadingContext _threadingContext; private readonly Workspace _workspace; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; public ObservableCollection<FrameViewModel> Frames { get; } = new(); private bool _isLoading; private readonly ClassificationTypeMap _classificationTypeMap; private readonly IClassificationFormatMap _formatMap; public bool IsLoading { get => _isLoading; set => SetProperty(ref _isLoading, value); } private FrameViewModel? _selection; public FrameViewModel? Selection { get => _selection; set => SetProperty(ref _selection, value); } public bool IsListVisible => Frames.Count > 0; public bool IsInstructionTextVisible => Frames.Count == 0; internal void OnClear() { Frames.Clear(); } public string InstructionText => ServicesVSResources.Paste_valid_stack_trace; public StackTraceExplorerViewModel(IThreadingContext threadingContext, Workspace workspace, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap formatMap, IStreamingFindUsagesPresenter streamingFindUsagesPresenter) { _threadingContext = threadingContext; _workspace = workspace; workspace.WorkspaceChanged += Workspace_WorkspaceChanged; _classificationTypeMap = classificationTypeMap; _formatMap = formatMap; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; Frames.CollectionChanged += CallstackLines_CollectionChanged; } private void CallstackLines_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { NotifyPropertyChanged(nameof(IsListVisible)); NotifyPropertyChanged(nameof(IsInstructionTextVisible)); } private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { if (e.Kind == WorkspaceChangeKind.SolutionChanged) { Selection = null; Frames.Clear(); } } internal void OnPaste() { Frames.Clear(); var textObject = Clipboard.GetData(DataFormats.Text); if (textObject is string text) { OnPaste(text); } } internal void OnPaste(string text) { System.Threading.Tasks.Task.Run(async () => { try { var result = await StackTraceAnalyzer.AnalyzeAsync(text, _threadingContext.DisposalToken).ConfigureAwait(false); var viewModels = result.ParsedFrames.Select(l => GetViewModel(l)); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); Selection = null; Frames.Clear(); foreach (var vm in viewModels) { Frames.Add(vm); } } finally { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); IsLoading = false; } }, _threadingContext.DisposalToken); } private FrameViewModel GetViewModel(ParsedFrame frame) => frame switch { IgnoredFrame ignoredFrame => new IgnoredFrameViewModel(ignoredFrame, _formatMap, _classificationTypeMap), ParsedStackFrame stackFrame => new StackFrameViewModel(stackFrame, _threadingContext, _workspace, _formatMap, _classificationTypeMap, _streamingFindUsagesPresenter), _ => throw ExceptionUtilities.UnexpectedValue(frame) }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ObjectModel; using System.Linq; using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.StackTraceExplorer; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Text.Classification; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Editor.Host; namespace Microsoft.VisualStudio.LanguageServices.StackTraceExplorer { internal class StackTraceExplorerViewModel : ViewModelBase { private readonly IThreadingContext _threadingContext; private readonly Workspace _workspace; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; public ObservableCollection<FrameViewModel> Frames { get; } = new(); private bool _isLoading; private readonly ClassificationTypeMap _classificationTypeMap; private readonly IClassificationFormatMap _formatMap; public bool IsLoading { get => _isLoading; set => SetProperty(ref _isLoading, value); } private FrameViewModel? _selection; public FrameViewModel? Selection { get => _selection; set => SetProperty(ref _selection, value); } public bool IsListVisible => Frames.Count > 0; public bool IsInstructionTextVisible => Frames.Count == 0; internal void OnClear() { Frames.Clear(); } public string InstructionText => ServicesVSResources.Paste_valid_stack_trace; public StackTraceExplorerViewModel(IThreadingContext threadingContext, Workspace workspace, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap formatMap, IStreamingFindUsagesPresenter streamingFindUsagesPresenter) { _threadingContext = threadingContext; _workspace = workspace; workspace.WorkspaceChanged += Workspace_WorkspaceChanged; _classificationTypeMap = classificationTypeMap; _formatMap = formatMap; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; Frames.CollectionChanged += CallstackLines_CollectionChanged; } private void CallstackLines_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { NotifyPropertyChanged(nameof(IsListVisible)); NotifyPropertyChanged(nameof(IsInstructionTextVisible)); } private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { if (e.Kind == WorkspaceChangeKind.SolutionChanged) { Selection = null; Frames.Clear(); } } internal void OnPaste() { Frames.Clear(); var textObject = Clipboard.GetData(DataFormats.Text); if (textObject is string text) { OnPaste(text); } } internal void OnPaste(string text) { System.Threading.Tasks.Task.Run(async () => { try { var result = await StackTraceAnalyzer.AnalyzeAsync(text, _threadingContext.DisposalToken).ConfigureAwait(false); var viewModels = result.ParsedFrames.Select(l => GetViewModel(l)); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); Selection = null; Frames.Clear(); foreach (var vm in viewModels) { Frames.Add(vm); } } finally { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); IsLoading = false; } }, _threadingContext.DisposalToken); } private FrameViewModel GetViewModel(ParsedFrame frame) => frame switch { IgnoredFrame ignoredFrame => new IgnoredFrameViewModel(ignoredFrame, _formatMap, _classificationTypeMap), ParsedStackFrame stackFrame => new StackFrameViewModel(stackFrame, _threadingContext, _workspace, _formatMap, _classificationTypeMap, _streamingFindUsagesPresenter), _ => throw ExceptionUtilities.UnexpectedValue(frame) }; } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractTableEntriesSnapshot.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Base implementation of ITableEntriesSnapshot /// </summary> internal abstract class AbstractTableEntriesSnapshot<TItem> : ITableEntriesSnapshot where TItem : TableItem { // TODO : remove these once we move to new drop which contains API change from editor team protected const string ProjectNames = StandardTableKeyNames.ProjectName + "s"; protected const string ProjectGuids = StandardTableKeyNames.ProjectGuid + "s"; private readonly int _version; private readonly ImmutableArray<TItem> _items; private ImmutableArray<ITrackingPoint> _trackingPoints; protected AbstractTableEntriesSnapshot(int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints) { _version = version; _items = items; _trackingPoints = trackingPoints; } public abstract bool TryNavigateTo(int index, bool previewTab, bool activate, CancellationToken cancellationToken); public abstract bool TryGetValue(int index, string columnName, out object content); public int VersionNumber { get { return _version; } } public int Count { get { return _items.Length; } } public int IndexOf(int index, ITableEntriesSnapshot newerSnapshot) { var item = GetItem(index); if (item == null) { return -1; } if (newerSnapshot is not AbstractTableEntriesSnapshot<TItem> ourSnapshot || ourSnapshot.Count == 0) { // not ours, we don't know how to track index return -1; } // quick path - this will deal with a case where we update data without any actual change if (Count == ourSnapshot.Count) { var newItem = ourSnapshot.GetItem(index); if (newItem != null && newItem.Equals(item)) { return index; } } // slow path. for (var i = 0; i < ourSnapshot.Count; i++) { var newItem = ourSnapshot.GetItem(i); if (item.EqualsIgnoringLocation(newItem)) { return i; } } // no similar item exist. table control itself will try to maintain selection return -1; } public void StopTracking() { // remove tracking points _trackingPoints = default; } public void Dispose() => StopTracking(); internal TItem GetItem(int index) { if (index < 0 || _items.Length <= index) { return null; } return _items[index]; } protected LinePosition GetTrackingLineColumn(Document document, int index) { if (_trackingPoints.IsDefaultOrEmpty) { return LinePosition.Zero; } var trackingPoint = _trackingPoints[index]; if (!document.TryGetText(out var text)) { return LinePosition.Zero; } var snapshot = text.FindCorrespondingEditorTextSnapshot(); if (snapshot != null) { return GetLinePosition(snapshot, trackingPoint); } var textBuffer = text.Container.TryGetTextBuffer(); if (textBuffer == null) { return LinePosition.Zero; } var currentSnapshot = textBuffer.CurrentSnapshot; return GetLinePosition(currentSnapshot, trackingPoint); } private static LinePosition GetLinePosition(ITextSnapshot snapshot, ITrackingPoint trackingPoint) { var point = trackingPoint.GetPoint(snapshot); var line = point.GetContainingLine(); return new LinePosition(line.LineNumber, point.Position - line.Start); } protected static bool TryNavigateTo(Workspace workspace, DocumentId documentId, LinePosition position, bool previewTab, bool activate, CancellationToken cancellationToken) { var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); if (navigationService == null) { return false; } var solution = workspace.CurrentSolution; var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, previewTab) .WithChangedOption(NavigationOptions.ActivateTab, activate); return navigationService.TryNavigateToLineAndOffset(workspace, documentId, position.Line, position.Character, options, cancellationToken); } protected bool TryNavigateToItem(int index, bool previewTab, bool activate, CancellationToken cancellationToken) { var item = GetItem(index); var documentId = item?.DocumentId; if (documentId == null) { return false; } var workspace = item.Workspace; var solution = workspace.CurrentSolution; var document = solution.GetDocument(documentId); if (document == null) { return false; } LinePosition position; LinePosition trackingLinePosition; if (workspace.IsDocumentOpen(documentId) && (trackingLinePosition = GetTrackingLineColumn(document, index)) != LinePosition.Zero) { position = trackingLinePosition; } else { position = item.GetOriginalPosition(); } return TryNavigateTo(workspace, documentId, position, previewTab, activate, cancellationToken); } // we don't use these #pragma warning disable IDE0060 // Remove unused parameter - Implements interface method for sub-type public object Identity(int index) #pragma warning restore IDE0060 // Remove unused parameter => null; public void StartCaching() { } public void StopCaching() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Base implementation of ITableEntriesSnapshot /// </summary> internal abstract class AbstractTableEntriesSnapshot<TItem> : ITableEntriesSnapshot where TItem : TableItem { // TODO : remove these once we move to new drop which contains API change from editor team protected const string ProjectNames = StandardTableKeyNames.ProjectName + "s"; protected const string ProjectGuids = StandardTableKeyNames.ProjectGuid + "s"; private readonly int _version; private readonly ImmutableArray<TItem> _items; private ImmutableArray<ITrackingPoint> _trackingPoints; protected AbstractTableEntriesSnapshot(int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints) { _version = version; _items = items; _trackingPoints = trackingPoints; } public abstract bool TryNavigateTo(int index, bool previewTab, bool activate, CancellationToken cancellationToken); public abstract bool TryGetValue(int index, string columnName, out object content); public int VersionNumber { get { return _version; } } public int Count { get { return _items.Length; } } public int IndexOf(int index, ITableEntriesSnapshot newerSnapshot) { var item = GetItem(index); if (item == null) { return -1; } if (newerSnapshot is not AbstractTableEntriesSnapshot<TItem> ourSnapshot || ourSnapshot.Count == 0) { // not ours, we don't know how to track index return -1; } // quick path - this will deal with a case where we update data without any actual change if (Count == ourSnapshot.Count) { var newItem = ourSnapshot.GetItem(index); if (newItem != null && newItem.Equals(item)) { return index; } } // slow path. for (var i = 0; i < ourSnapshot.Count; i++) { var newItem = ourSnapshot.GetItem(i); if (item.EqualsIgnoringLocation(newItem)) { return i; } } // no similar item exist. table control itself will try to maintain selection return -1; } public void StopTracking() { // remove tracking points _trackingPoints = default; } public void Dispose() => StopTracking(); internal TItem GetItem(int index) { if (index < 0 || _items.Length <= index) { return null; } return _items[index]; } protected LinePosition GetTrackingLineColumn(Document document, int index) { if (_trackingPoints.IsDefaultOrEmpty) { return LinePosition.Zero; } var trackingPoint = _trackingPoints[index]; if (!document.TryGetText(out var text)) { return LinePosition.Zero; } var snapshot = text.FindCorrespondingEditorTextSnapshot(); if (snapshot != null) { return GetLinePosition(snapshot, trackingPoint); } var textBuffer = text.Container.TryGetTextBuffer(); if (textBuffer == null) { return LinePosition.Zero; } var currentSnapshot = textBuffer.CurrentSnapshot; return GetLinePosition(currentSnapshot, trackingPoint); } private static LinePosition GetLinePosition(ITextSnapshot snapshot, ITrackingPoint trackingPoint) { var point = trackingPoint.GetPoint(snapshot); var line = point.GetContainingLine(); return new LinePosition(line.LineNumber, point.Position - line.Start); } protected static bool TryNavigateTo(Workspace workspace, DocumentId documentId, LinePosition position, bool previewTab, bool activate, CancellationToken cancellationToken) { var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); if (navigationService == null) { return false; } var solution = workspace.CurrentSolution; var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, previewTab) .WithChangedOption(NavigationOptions.ActivateTab, activate); return navigationService.TryNavigateToLineAndOffset(workspace, documentId, position.Line, position.Character, options, cancellationToken); } protected bool TryNavigateToItem(int index, bool previewTab, bool activate, CancellationToken cancellationToken) { var item = GetItem(index); var documentId = item?.DocumentId; if (documentId == null) { return false; } var workspace = item.Workspace; var solution = workspace.CurrentSolution; var document = solution.GetDocument(documentId); if (document == null) { return false; } LinePosition position; LinePosition trackingLinePosition; if (workspace.IsDocumentOpen(documentId) && (trackingLinePosition = GetTrackingLineColumn(document, index)) != LinePosition.Zero) { position = trackingLinePosition; } else { position = item.GetOriginalPosition(); } return TryNavigateTo(workspace, documentId, position, previewTab, activate, cancellationToken); } // we don't use these #pragma warning disable IDE0060 // Remove unused parameter - Implements interface method for sub-type public object Identity(int index) #pragma warning restore IDE0060 // Remove unused parameter => null; public void StartCaching() { } public void StopCaching() { } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DynamicFlagsCustomTypeInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicFlagsCustomTypeInfoTests : CSharpResultProviderTestBase { [Fact] public void ToBytes() { ValidateToBytes(new bool[0]); ValidateToBytes(new bool[] { false }); ValidateToBytes(new bool[] { true }, 0x01); ValidateToBytes(new bool[] { false, false }); ValidateToBytes(new bool[] { true, false }, 0x01); ValidateToBytes(new bool[] { false, true }, 0x02); ValidateToBytes(new bool[] { true, true }, 0x03); ValidateToBytes(new bool[] { false, false, true }, 0x04); ValidateToBytes(new bool[] { false, false, false, true }, 0x08); ValidateToBytes(new bool[] { false, false, false, false, true }, 0x10); ValidateToBytes(new bool[] { false, false, false, false, false, true }, 0x20); ValidateToBytes(new bool[] { false, false, false, false, false, false, true }, 0x40); ValidateToBytes(new bool[] { false, false, false, false, false, false, false, true }, 0x80); ValidateToBytes(new bool[] { false, false, false, false, false, false, false, false, true }, 0x00, 0x01); } [Fact] public void CopyTo() { ValidateCopyTo(new byte[0]); ValidateCopyTo(new byte[] { 0x00 }, false, false, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x01 }, true, false, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x02 }, false, true, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x03 }, true, true, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x04 }, false, false, true, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x08 }, false, false, false, true, false, false, false, false); ValidateCopyTo(new byte[] { 0x10 }, false, false, false, false, true, false, false, false); ValidateCopyTo(new byte[] { 0x20 }, false, false, false, false, false, true, false, false); ValidateCopyTo(new byte[] { 0x40 }, false, false, false, false, false, false, true, false); ValidateCopyTo(new byte[] { 0x80 }, false, false, false, false, false, false, false, true); ValidateCopyTo(new byte[] { 0x00, 0x01 }, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false); } [Fact] public void EncodeAndDecode() { var encoded = CustomTypeInfo.Encode(null, null); Assert.Null(encoded); ReadOnlyCollection<byte> bytes; ReadOnlyCollection<string> names; // Exceed max bytes. bytes = GetBytesInRange(0, 256); encoded = CustomTypeInfo.Encode(bytes, null); Assert.Null(encoded); // Max bytes. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, null); Assert.Equal(256, encoded.Count); Assert.Equal(255, encoded[0]); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Null(tupleElementNames); // Empty dynamic flags collection bytes = new ReadOnlyCollection<byte>(new byte[0]); // ... with names. names = new ReadOnlyCollection<string>(new[] { "A" }); encoded = CustomTypeInfo.Encode(bytes, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without names. encoded = CustomTypeInfo.Encode(bytes, null); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); // Empty names collection names = new ReadOnlyCollection<string>(new string[0]); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Null(tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); // Single null name names = new ReadOnlyCollection<string>(new string[] { null }); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); Assert.Equal(255, encoded[0]); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); // Multiple names names = new ReadOnlyCollection<string>(new[] { null, "A", null, "B" }); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); Assert.Equal(255, encoded[0]); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); } private static ReadOnlyCollection<byte> GetBytesInRange(int start, int length) { return new ReadOnlyCollection<byte>(Enumerable.Range(start, length).Select(i => (byte)(i % 256)).ToArray()); } [Fact] public void CustomTypeInfoConstructor() { ValidateCustomTypeInfo(); ValidateCustomTypeInfo(0x00); ValidateCustomTypeInfo(0x01); ValidateCustomTypeInfo(0x02); ValidateCustomTypeInfo(0x03); ValidateCustomTypeInfo(0x04); ValidateCustomTypeInfo(0x08); ValidateCustomTypeInfo(0x10); ValidateCustomTypeInfo(0x20); ValidateCustomTypeInfo(0x40); ValidateCustomTypeInfo(0x80); ValidateCustomTypeInfo(0x00, 0x01); } [Fact] public void CustomTypeInfoConstructor_OtherGuid() { var customTypeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 0x01 })); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode( customTypeInfo.PayloadTypeId, customTypeInfo.Payload, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); } [Fact] public void Indexer() { ValidateIndexer(null); ValidateIndexer(false); ValidateIndexer(true); ValidateIndexer(false, false); ValidateIndexer(false, true); ValidateIndexer(true, false); ValidateIndexer(true, true); ValidateIndexer(false, false, true); ValidateIndexer(false, false, false, true); ValidateIndexer(false, false, false, false, true); ValidateIndexer(false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, false, false, true); } [Fact] public void SkipOne() { ValidateBytes(DynamicFlagsCustomTypeInfo.SkipOne(null)); var dynamicFlagsCustomTypeInfo = new ReadOnlyCollection<byte>(new byte[] { 0x80 }); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x40); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x20); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x10); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x08); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x04); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x02); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x01); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo); dynamicFlagsCustomTypeInfo = new ReadOnlyCollection<byte>(new byte[] { 0x00, 0x02 }); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x00, 0x01); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x80, 0x00); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x40, 0x00); } private static void ValidateCustomTypeInfo(params byte[] payload) { Assert.NotNull(payload); var dkmClrCustomTypeInfo = CustomTypeInfo.Create(new ReadOnlyCollection<byte>(payload), null); Assert.Equal(CustomTypeInfo.PayloadTypeId, dkmClrCustomTypeInfo.PayloadTypeId); Assert.NotNull(dkmClrCustomTypeInfo.Payload); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode( dkmClrCustomTypeInfo.PayloadTypeId, dkmClrCustomTypeInfo.Payload, out dynamicFlags, out tupleElementNames); ValidateBytes(dynamicFlags, payload); Assert.Null(tupleElementNames); } private static void ValidateIndexer(params bool[] dynamicFlags) { if (dynamicFlags == null) { Assert.False(DynamicFlagsCustomTypeInfo.GetFlag(null, 0)); } else { var builder = ArrayBuilder<bool>.GetInstance(dynamicFlags.Length); builder.AddRange(dynamicFlags); var customTypeInfo = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); AssertEx.All(dynamicFlags.Select((f, i) => f == DynamicFlagsCustomTypeInfo.GetFlag(customTypeInfo, i)), x => x); Assert.False(DynamicFlagsCustomTypeInfo.GetFlag(customTypeInfo, dynamicFlags.Length)); } } private static void ValidateToBytes(bool[] dynamicFlags, params byte[] expectedBytes) { Assert.NotNull(dynamicFlags); Assert.NotNull(expectedBytes); var builder = ArrayBuilder<bool>.GetInstance(dynamicFlags.Length); builder.AddRange(dynamicFlags); var actualBytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); ValidateBytes(actualBytes, expectedBytes); } private static void ValidateCopyTo(byte[] dynamicFlags, params bool[] expectedFlags) { var builder = ArrayBuilder<bool>.GetInstance(); DynamicFlagsCustomTypeInfo.CopyTo(new ReadOnlyCollection<byte>(dynamicFlags), builder); var actualFlags = builder.ToArrayAndFree(); Assert.Equal(expectedFlags, actualFlags); } private static void ValidateBytes(ReadOnlyCollection<byte> actualBytes, params byte[] expectedBytes) { Assert.NotNull(expectedBytes); if (expectedBytes.Length == 0) { Assert.Null(actualBytes); } else { Assert.Equal(expectedBytes, actualBytes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicFlagsCustomTypeInfoTests : CSharpResultProviderTestBase { [Fact] public void ToBytes() { ValidateToBytes(new bool[0]); ValidateToBytes(new bool[] { false }); ValidateToBytes(new bool[] { true }, 0x01); ValidateToBytes(new bool[] { false, false }); ValidateToBytes(new bool[] { true, false }, 0x01); ValidateToBytes(new bool[] { false, true }, 0x02); ValidateToBytes(new bool[] { true, true }, 0x03); ValidateToBytes(new bool[] { false, false, true }, 0x04); ValidateToBytes(new bool[] { false, false, false, true }, 0x08); ValidateToBytes(new bool[] { false, false, false, false, true }, 0x10); ValidateToBytes(new bool[] { false, false, false, false, false, true }, 0x20); ValidateToBytes(new bool[] { false, false, false, false, false, false, true }, 0x40); ValidateToBytes(new bool[] { false, false, false, false, false, false, false, true }, 0x80); ValidateToBytes(new bool[] { false, false, false, false, false, false, false, false, true }, 0x00, 0x01); } [Fact] public void CopyTo() { ValidateCopyTo(new byte[0]); ValidateCopyTo(new byte[] { 0x00 }, false, false, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x01 }, true, false, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x02 }, false, true, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x03 }, true, true, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x04 }, false, false, true, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x08 }, false, false, false, true, false, false, false, false); ValidateCopyTo(new byte[] { 0x10 }, false, false, false, false, true, false, false, false); ValidateCopyTo(new byte[] { 0x20 }, false, false, false, false, false, true, false, false); ValidateCopyTo(new byte[] { 0x40 }, false, false, false, false, false, false, true, false); ValidateCopyTo(new byte[] { 0x80 }, false, false, false, false, false, false, false, true); ValidateCopyTo(new byte[] { 0x00, 0x01 }, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false); } [Fact] public void EncodeAndDecode() { var encoded = CustomTypeInfo.Encode(null, null); Assert.Null(encoded); ReadOnlyCollection<byte> bytes; ReadOnlyCollection<string> names; // Exceed max bytes. bytes = GetBytesInRange(0, 256); encoded = CustomTypeInfo.Encode(bytes, null); Assert.Null(encoded); // Max bytes. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, null); Assert.Equal(256, encoded.Count); Assert.Equal(255, encoded[0]); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Null(tupleElementNames); // Empty dynamic flags collection bytes = new ReadOnlyCollection<byte>(new byte[0]); // ... with names. names = new ReadOnlyCollection<string>(new[] { "A" }); encoded = CustomTypeInfo.Encode(bytes, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without names. encoded = CustomTypeInfo.Encode(bytes, null); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); // Empty names collection names = new ReadOnlyCollection<string>(new string[0]); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Null(tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); // Single null name names = new ReadOnlyCollection<string>(new string[] { null }); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); Assert.Equal(255, encoded[0]); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); // Multiple names names = new ReadOnlyCollection<string>(new[] { null, "A", null, "B" }); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); Assert.Equal(255, encoded[0]); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); } private static ReadOnlyCollection<byte> GetBytesInRange(int start, int length) { return new ReadOnlyCollection<byte>(Enumerable.Range(start, length).Select(i => (byte)(i % 256)).ToArray()); } [Fact] public void CustomTypeInfoConstructor() { ValidateCustomTypeInfo(); ValidateCustomTypeInfo(0x00); ValidateCustomTypeInfo(0x01); ValidateCustomTypeInfo(0x02); ValidateCustomTypeInfo(0x03); ValidateCustomTypeInfo(0x04); ValidateCustomTypeInfo(0x08); ValidateCustomTypeInfo(0x10); ValidateCustomTypeInfo(0x20); ValidateCustomTypeInfo(0x40); ValidateCustomTypeInfo(0x80); ValidateCustomTypeInfo(0x00, 0x01); } [Fact] public void CustomTypeInfoConstructor_OtherGuid() { var customTypeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 0x01 })); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode( customTypeInfo.PayloadTypeId, customTypeInfo.Payload, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); } [Fact] public void Indexer() { ValidateIndexer(null); ValidateIndexer(false); ValidateIndexer(true); ValidateIndexer(false, false); ValidateIndexer(false, true); ValidateIndexer(true, false); ValidateIndexer(true, true); ValidateIndexer(false, false, true); ValidateIndexer(false, false, false, true); ValidateIndexer(false, false, false, false, true); ValidateIndexer(false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, false, false, true); } [Fact] public void SkipOne() { ValidateBytes(DynamicFlagsCustomTypeInfo.SkipOne(null)); var dynamicFlagsCustomTypeInfo = new ReadOnlyCollection<byte>(new byte[] { 0x80 }); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x40); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x20); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x10); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x08); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x04); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x02); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x01); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo); dynamicFlagsCustomTypeInfo = new ReadOnlyCollection<byte>(new byte[] { 0x00, 0x02 }); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x00, 0x01); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x80, 0x00); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x40, 0x00); } private static void ValidateCustomTypeInfo(params byte[] payload) { Assert.NotNull(payload); var dkmClrCustomTypeInfo = CustomTypeInfo.Create(new ReadOnlyCollection<byte>(payload), null); Assert.Equal(CustomTypeInfo.PayloadTypeId, dkmClrCustomTypeInfo.PayloadTypeId); Assert.NotNull(dkmClrCustomTypeInfo.Payload); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode( dkmClrCustomTypeInfo.PayloadTypeId, dkmClrCustomTypeInfo.Payload, out dynamicFlags, out tupleElementNames); ValidateBytes(dynamicFlags, payload); Assert.Null(tupleElementNames); } private static void ValidateIndexer(params bool[] dynamicFlags) { if (dynamicFlags == null) { Assert.False(DynamicFlagsCustomTypeInfo.GetFlag(null, 0)); } else { var builder = ArrayBuilder<bool>.GetInstance(dynamicFlags.Length); builder.AddRange(dynamicFlags); var customTypeInfo = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); AssertEx.All(dynamicFlags.Select((f, i) => f == DynamicFlagsCustomTypeInfo.GetFlag(customTypeInfo, i)), x => x); Assert.False(DynamicFlagsCustomTypeInfo.GetFlag(customTypeInfo, dynamicFlags.Length)); } } private static void ValidateToBytes(bool[] dynamicFlags, params byte[] expectedBytes) { Assert.NotNull(dynamicFlags); Assert.NotNull(expectedBytes); var builder = ArrayBuilder<bool>.GetInstance(dynamicFlags.Length); builder.AddRange(dynamicFlags); var actualBytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); ValidateBytes(actualBytes, expectedBytes); } private static void ValidateCopyTo(byte[] dynamicFlags, params bool[] expectedFlags) { var builder = ArrayBuilder<bool>.GetInstance(); DynamicFlagsCustomTypeInfo.CopyTo(new ReadOnlyCollection<byte>(dynamicFlags), builder); var actualFlags = builder.ToArrayAndFree(); Assert.Equal(expectedFlags, actualFlags); } private static void ValidateBytes(ReadOnlyCollection<byte> actualBytes, params byte[] expectedBytes) { Assert.NotNull(expectedBytes); if (expectedBytes.Length == 0) { Assert.Null(actualBytes); } else { Assert.Equal(expectedBytes, actualBytes); } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Server/VBCSCompiler/VisualBasicCompilerServer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class VisualBasicCompilerServer : VisualBasicCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader, GeneratorDriverCache driverCache) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader, driverCache) { } internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader, GeneratorDriverCache driverCache) : base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader, driverCache) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class VisualBasicCompilerServer : VisualBasicCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader, GeneratorDriverCache driverCache) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader, driverCache) { } internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader, GeneratorDriverCache driverCache) : base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader, driverCache) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Portable/Compilation/CSharpSemanticModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Allows asking semantic questions about a tree of syntax nodes in a Compilation. Typically, /// an instance is obtained by a call to <see cref="Compilation"/>.<see /// cref="Compilation.GetSemanticModel(SyntaxTree, bool)"/>. /// </summary> /// <remarks> /// <para>An instance of <see cref="CSharpSemanticModel"/> caches local symbols and semantic /// information. Thus, it is much more efficient to use a single instance of <see /// cref="CSharpSemanticModel"/> when asking multiple questions about a syntax tree, because /// information from the first question may be reused. This also means that holding onto an /// instance of SemanticModel for a long time may keep a significant amount of memory from being /// garbage collected. /// </para> /// <para> /// When an answer is a named symbol that is reachable by traversing from the root of the symbol /// table, (that is, from an <see cref="AssemblySymbol"/> of the <see cref="Compilation"/>), /// that symbol will be returned (i.e. the returned value will be reference-equal to one /// reachable from the root of the symbol table). Symbols representing entities without names /// (e.g. array-of-int) may or may not exhibit reference equality. However, some named symbols /// (such as local variables) are not reachable from the root. These symbols are visible as /// answers to semantic questions. When the same SemanticModel object is used, the answers /// exhibit reference-equality. /// </para> /// </remarks> internal abstract class CSharpSemanticModel : SemanticModel { /// <summary> /// The compilation this object was obtained from. /// </summary> public new abstract CSharpCompilation Compilation { get; } /// <summary> /// The root node of the syntax tree that this binding is based on. /// </summary> internal new abstract CSharpSyntaxNode Root { get; } // Is this node one that could be successfully interrogated by GetSymbolInfo/GetTypeInfo/GetMemberGroup/GetConstantValue? // WARN: If isSpeculative is true, then don't look at .Parent - there might not be one. internal static bool CanGetSemanticInfo(CSharpSyntaxNode node, bool allowNamedArgumentName = false, bool isSpeculative = false) { Debug.Assert(node != null); if (!isSpeculative && IsInStructuredTriviaOtherThanCrefOrNameAttribute(node)) { return false; } switch (node.Kind()) { case SyntaxKind.CollectionInitializerExpression: case SyntaxKind.ObjectInitializerExpression: // new CollectionClass() { 1, 2, 3 } // ~~~~~~~~~~~ // OR // // new ObjectClass() { field = 1, prop = 2 } // ~~~~~~~~~~~~~~~~~~~~~~~ // CollectionInitializerExpression and ObjectInitializerExpression are not really expressions in the language sense. // We do not allow getting the semantic info for these syntax nodes. However, we do allow getting semantic info // for each of the individual initializer elements or member assignments. return false; case SyntaxKind.ComplexElementInitializerExpression: // new Collection { 1, {2, 3} } // ~~~~~~ // ComplexElementInitializerExpression are also not true expressions in the language sense, so we disallow getting the // semantic info for it. However, we may be interested in getting the semantic info for the compiler generated Add // method invoked with initializer expressions as arguments. Roslyn bug 11987 tracks this work item. return false; case SyntaxKind.IdentifierName: // The alias of a using directive is a declaration, so there is no semantic info - use GetDeclaredSymbol instead. if (!isSpeculative && node.Parent != null && node.Parent.Kind() == SyntaxKind.NameEquals && node.Parent.Parent.Kind() == SyntaxKind.UsingDirective) { return false; } goto default; case SyntaxKind.OmittedTypeArgument: case SyntaxKind.RefExpression: case SyntaxKind.RefType: // These are just placeholders and are not separately meaningful. return false; default: // If we are being asked for binding info on a "missing" syntax node // then there's no point in doing any work at all. For example, the user might // have something like "class C { [] void M() {} }". The caller might obtain // the attribute declaration syntax and then attempt to ask for type information // about the contents of the attribute. But the parser has recovered from the // missing attribute type and filled in a "missing" node in its place. There's // nothing we can do with that, so let's not allow it. if (node.IsMissing) { return false; } return (node is ExpressionSyntax && (isSpeculative || allowNamedArgumentName || !SyntaxFacts.IsNamedArgumentName(node))) || (node is ConstructorInitializerSyntax) || (node is PrimaryConstructorBaseTypeSyntax) || (node is AttributeSyntax) || (node is CrefSyntax); } } #region Abstract worker methods /// <summary> /// Gets symbol information about a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="options">Options to control behavior.</param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets symbol information about the 'Add' method corresponding to an expression syntax <paramref name="node"/> within collection initializer. /// This is the worker function that is overridden in various derived kinds of Semantic Models. It can assume that /// CheckSyntaxNode has already been called and the <paramref name="node"/> is in the right place in the syntax tree. /// </summary> internal abstract SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets type information about a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Binds the provided expression in the given context. /// </summary> /// <param name="position">The position to bind at.</param> /// <param name="expression">The expression to bind</param> /// <param name="bindingOption">How to speculatively bind the given expression. If this is <see cref="SpeculativeBindingOption.BindAsTypeOrNamespace"/> /// then the provided expression should be a <see cref="TypeSyntax"/>.</param> /// <param name="binder">The binder that was used to bind the given syntax.</param> /// <param name="crefSymbols">The symbols used in a cref. If this is not default, then the return is null.</param> /// <returns>The expression that was bound. If <paramref name="crefSymbols"/> is not default, this is null.</returns> internal abstract BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols); /// <summary> /// Gets a list of method or indexed property symbols for a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="options"></param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of indexer symbols for a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="options"></param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the constant value for a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); #endregion Abstract worker methods #region Helpers for speculative binding internal Binder GetSpeculativeBinder(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { Debug.Assert(expression != null); position = CheckAndAdjustPosition(position); if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace) { if (!(expression is TypeSyntax)) { return null; } } Binder binder = this.GetEnclosingBinder(position); if (binder == null) { return null; } if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace && IsInTypeofExpression(position)) { // If position is within a typeof expression, GetEnclosingBinder may return a // TypeofBinder. However, this TypeofBinder will have been constructed with the // actual syntax of the typeof argument and we want to use the given syntax. // Wrap the binder in another TypeofBinder to overrule its description of where // unbound generic types are allowed. //Debug.Assert(binder is TypeofBinder); // Expectation, not requirement. binder = new TypeofBinder(expression, binder); } binder = new WithNullableContextBinder(SyntaxTree, position, binder); return new ExecutableCodeBinder(expression, binder.ContainingMemberOrLambda, binder).GetBinder(expression); } private Binder GetSpeculativeBinderForAttribute(int position, AttributeSyntax attribute) { position = CheckAndAdjustPositionForSpeculativeAttribute(position); var binder = this.GetEnclosingBinder(position); if (binder == null) { return null; } return new ExecutableCodeBinder(attribute, binder.ContainingMemberOrLambda, binder).GetBinder(attribute); } private static BoundExpression GetSpeculativelyBoundExpressionHelper(Binder binder, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { Debug.Assert(binder != null); Debug.Assert(binder.IsSemanticModelBinder); Debug.Assert(expression != null); Debug.Assert(bindingOption != SpeculativeBindingOption.BindAsTypeOrNamespace || expression is TypeSyntax); BoundExpression boundNode; if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace || binder.Flags.Includes(BinderFlags.CrefParameterOrReturnType)) { boundNode = binder.BindNamespaceOrType(expression, BindingDiagnosticBag.Discarded); } else { Debug.Assert(bindingOption == SpeculativeBindingOption.BindAsExpression); boundNode = binder.BindExpression(expression, BindingDiagnosticBag.Discarded); } return boundNode; } /// <summary> /// Bind the given expression speculatively at the given position, and return back /// the resulting bound node. May return null in some error cases. /// </summary> /// <remarks> /// Keep in sync with Binder.BindCrefParameterOrReturnType. /// </remarks> protected BoundExpression GetSpeculativelyBoundExpressionWithoutNullability(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } crefSymbols = default(ImmutableArray<Symbol>); expression = SyntaxFactory.GetStandaloneExpression(expression); binder = this.GetSpeculativeBinder(position, expression, bindingOption); if (binder == null) { return null; } if (binder.Flags.Includes(BinderFlags.CrefParameterOrReturnType)) { crefSymbols = ImmutableArray.Create<Symbol>(binder.BindType(expression, BindingDiagnosticBag.Discarded).Type); return null; } else if (binder.InCref) { if (expression.IsKind(SyntaxKind.QualifiedName)) { var qualified = (QualifiedNameSyntax)expression; var crefWrapper = SyntaxFactory.QualifiedCref(qualified.Left, SyntaxFactory.NameMemberCref(qualified.Right)); crefSymbols = BindCref(crefWrapper, binder); } else if (expression is TypeSyntax typeSyntax) { var crefWrapper = typeSyntax is PredefinedTypeSyntax ? (CrefSyntax)SyntaxFactory.TypeCref(typeSyntax) : SyntaxFactory.NameMemberCref(typeSyntax); crefSymbols = BindCref(crefWrapper, binder); } return null; } var boundNode = GetSpeculativelyBoundExpressionHelper(binder, expression, bindingOption); return boundNode; } internal static ImmutableArray<Symbol> BindCref(CrefSyntax crefSyntax, Binder binder) { Symbol unusedAmbiguityWinner; var symbols = binder.BindCref(crefSyntax, out unusedAmbiguityWinner, BindingDiagnosticBag.Discarded); return symbols; } internal SymbolInfo GetCrefSymbolInfo(int position, CrefSyntax crefSyntax, SymbolInfoOptions options, bool hasParameterList) { var binder = this.GetEnclosingBinder(position); if (binder?.InCref == true) { ImmutableArray<Symbol> symbols = BindCref(crefSyntax, binder); return GetCrefSymbolInfo(symbols, options, hasParameterList); } return SymbolInfo.None; } internal static bool HasParameterList(CrefSyntax crefSyntax) { while (crefSyntax.Kind() == SyntaxKind.QualifiedCref) { crefSyntax = ((QualifiedCrefSyntax)crefSyntax).Member; } switch (crefSyntax.Kind()) { case SyntaxKind.NameMemberCref: return ((NameMemberCrefSyntax)crefSyntax).Parameters != null; case SyntaxKind.IndexerMemberCref: return ((IndexerMemberCrefSyntax)crefSyntax).Parameters != null; case SyntaxKind.OperatorMemberCref: return ((OperatorMemberCrefSyntax)crefSyntax).Parameters != null; case SyntaxKind.ConversionOperatorMemberCref: return ((ConversionOperatorMemberCrefSyntax)crefSyntax).Parameters != null; } return false; } private static SymbolInfo GetCrefSymbolInfo(ImmutableArray<Symbol> symbols, SymbolInfoOptions options, bool hasParameterList) { switch (symbols.Length) { case 0: return SymbolInfo.None; case 1: // Might have to expand an ExtendedErrorTypeSymbol into multiple candidates. return GetSymbolInfoForSymbol(symbols[0], options); default: if ((options & SymbolInfoOptions.ResolveAliases) == SymbolInfoOptions.ResolveAliases) { symbols = UnwrapAliases(symbols); } LookupResultKind resultKind = LookupResultKind.Ambiguous; // The boundary between Ambiguous and OverloadResolutionFailure is let clear-cut for crefs. // We'll say that overload resolution failed if the syntax has a parameter list and if // all of the candidates have the same kind. SymbolKind firstCandidateKind = symbols[0].Kind; if (hasParameterList && symbols.All(s => s.Kind == firstCandidateKind)) { resultKind = LookupResultKind.OverloadResolutionFailure; } return SymbolInfoFactory.Create(symbols, resultKind, isDynamic: false); } } /// <summary> /// Bind the given attribute speculatively at the given position, and return back /// the resulting bound node. May return null in some error cases. /// </summary> private BoundAttribute GetSpeculativelyBoundAttribute(int position, AttributeSyntax attribute, out Binder binder) { if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } binder = this.GetSpeculativeBinderForAttribute(position, attribute); if (binder == null) { return null; } AliasSymbol aliasOpt; // not needed. NamedTypeSymbol attributeType = (NamedTypeSymbol)binder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type; var boundNode = new ExecutableCodeBinder(attribute, binder.ContainingMemberOrLambda, binder).BindAttribute(attribute, attributeType, BindingDiagnosticBag.Discarded); return boundNode; } // When speculatively binding an attribute, we have to use the name lookup rules for an attribute, // even if the position isn't within an attribute. For example: // class C { // class DAttribute: Attribute {} // } // // If we speculatively bind the attribute "D" with position at the beginning of "class C", it should // bind to DAttribute. // // But GetBinderForPosition won't do that; it only handles the case where position is inside an attribute. // This function adds a special case: if the position (after first adjustment) is at the exact beginning // of a type or method, the position is adjusted so the right binder is chosen to get the right things // in scope. private int CheckAndAdjustPositionForSpeculativeAttribute(int position) { position = CheckAndAdjustPosition(position); SyntaxToken token = Root.FindToken(position); if (position == 0 && position != token.SpanStart) return position; CSharpSyntaxNode node = (CSharpSyntaxNode)token.Parent; if (position == node.SpanStart) { // There are two cases where the binder chosen for a position at the beginning of a symbol // is incorrect for binding an attribute: // // For a type, the binder should be the one that is used for the interior of the type, where // the types members (and type parameters) are in scope. We adjust the position to the "{" to get // that binder. // // For a generic method, the binder should not include the type parameters. We adjust the position to // the method name to get that binder. if (node is BaseTypeDeclarationSyntax typeDecl) { // We're at the beginning of a type declaration. We want the members to be in scope for attributes, // so use the open brace token. position = typeDecl.OpenBraceToken.SpanStart; } var methodDecl = node.FirstAncestorOrSelf<MethodDeclarationSyntax>(); if (methodDecl?.SpanStart == position) { // We're at the beginning of a method declaration. We want the type parameters to NOT be in scope. position = methodDecl.Identifier.SpanStart; } } return position; } #endregion Helpers for speculative binding protected override IOperation GetOperationCore(SyntaxNode node, CancellationToken cancellationToken) { var csnode = (CSharpSyntaxNode)node; CheckSyntaxNode(csnode); return this.GetOperationWorker(csnode, cancellationToken); } internal virtual IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { return null; } #region GetSymbolInfo /// <summary> /// Gets the semantic information for an ordering clause in an orderby query clause. /// </summary> public abstract SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the semantic information associated with a select or group clause. /// </summary> public abstract SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the SymbolInfo for the Deconstruct method used for a deconstruction pattern clause, if any. /// </summary> public SymbolInfo GetSymbolInfo(PositionalPatternClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); return this.GetSymbolInfoWorker(node, SymbolInfoOptions.DefaultOptions, cancellationToken); } /// <summary> /// Returns what symbol(s), if any, the given expression syntax bound to in the program. /// /// An AliasSymbol will never be returned by this method. What the alias refers to will be /// returned instead. To get information about aliases, call GetAliasInfo. /// /// If binding the type name C in the expression "new C(...)" the actual constructor bound to /// will be returned (or all constructor if overload resolution failed). This occurs as long as C /// unambiguously binds to a single type that has a constructor. If C ambiguously binds to multiple /// types, or C binds to a static class, then type(s) are returned. /// </summary> public SymbolInfo GetSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); if (!CanGetSemanticInfo(expression, allowNamedArgumentName: true)) { return SymbolInfo.None; } else if (SyntaxFacts.IsNamedArgumentName(expression)) { // Named arguments handled in special way. return this.GetNamedArgumentSymbolInfo((IdentifierNameSyntax)expression, cancellationToken); } else if (SyntaxFacts.IsDeclarationExpressionType(expression, out DeclarationExpressionSyntax parent)) { switch (parent.Designation.Kind()) { case SyntaxKind.SingleVariableDesignation: return GetSymbolInfoFromSymbolOrNone(TypeFromVariable((SingleVariableDesignationSyntax)parent.Designation, cancellationToken).Type); case SyntaxKind.DiscardDesignation: return GetSymbolInfoFromSymbolOrNone(GetTypeInfoWorker(parent, cancellationToken).Type.GetPublicSymbol()); case SyntaxKind.ParenthesizedVariableDesignation: if (((TypeSyntax)expression).IsVar) { return SymbolInfo.None; } break; } } else if (expression is DeclarationExpressionSyntax declaration) { if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { return SymbolInfo.None; } var symbol = GetDeclaredSymbol((SingleVariableDesignationSyntax)declaration.Designation, cancellationToken); if ((object)symbol == null) { return SymbolInfo.None; } return new SymbolInfo(symbol); } return this.GetSymbolInfoWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken); } private static SymbolInfo GetSymbolInfoFromSymbolOrNone(ITypeSymbol type) { if (type?.Kind != SymbolKind.ErrorType) { return new SymbolInfo(type); } return SymbolInfo.None; } /// <summary> /// Given a variable designation (typically in the left-hand-side of a deconstruction declaration statement), /// figure out its type by looking at the declared symbol of the corresponding variable. /// </summary> private (ITypeSymbol Type, CodeAnalysis.NullableAnnotation Annotation) TypeFromVariable(SingleVariableDesignationSyntax variableDesignation, CancellationToken cancellationToken) { var variable = GetDeclaredSymbol(variableDesignation, cancellationToken); switch (variable) { case ILocalSymbol local: return (local.Type, local.NullableAnnotation); case IFieldSymbol field: return (field.Type, field.NullableAnnotation); } return default; } /// <summary> /// Returns what 'Add' method symbol(s), if any, corresponds to the given expression syntax /// within <see cref="BaseObjectCreationExpressionSyntax.Initializer"/>. /// </summary> public SymbolInfo GetCollectionInitializerSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); if (expression.Parent != null && expression.Parent.Kind() == SyntaxKind.CollectionInitializerExpression) { // Find containing object creation expression InitializerExpressionSyntax initializer = (InitializerExpressionSyntax)expression.Parent; // Skip containing object initializers while (initializer.Parent != null && initializer.Parent.Kind() == SyntaxKind.SimpleAssignmentExpression && ((AssignmentExpressionSyntax)initializer.Parent).Right == initializer && initializer.Parent.Parent != null && initializer.Parent.Parent.Kind() == SyntaxKind.ObjectInitializerExpression) { initializer = (InitializerExpressionSyntax)initializer.Parent.Parent; } if (initializer.Parent is BaseObjectCreationExpressionSyntax objectCreation && objectCreation.Initializer == initializer && CanGetSemanticInfo(objectCreation, allowNamedArgumentName: false)) { return GetCollectionInitializerSymbolInfoWorker((InitializerExpressionSyntax)expression.Parent, expression, cancellationToken); } } return SymbolInfo.None; } /// <summary> /// Returns what symbol(s), if any, the given constructor initializer syntax bound to in the program. /// </summary> /// <param name="constructorInitializer">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public SymbolInfo GetSymbolInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(constructorInitializer); return CanGetSemanticInfo(constructorInitializer) ? GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken) : SymbolInfo.None; } /// <summary> /// Returns what symbol(s), if any, the given constructor initializer syntax bound to in the program. /// </summary> /// <param name="constructorInitializer">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public SymbolInfo GetSymbolInfo(PrimaryConstructorBaseTypeSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(constructorInitializer); return CanGetSemanticInfo(constructorInitializer) ? GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken) : SymbolInfo.None; } /// <summary> /// Returns what symbol(s), if any, the given attribute syntax bound to in the program. /// </summary> /// <param name="attributeSyntax">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public SymbolInfo GetSymbolInfo(AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(attributeSyntax); return CanGetSemanticInfo(attributeSyntax) ? GetSymbolInfoWorker(attributeSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken) : SymbolInfo.None; } /// <summary> /// Gets the semantic information associated with a documentation comment cref. /// </summary> public SymbolInfo GetSymbolInfo(CrefSyntax crefSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(crefSyntax); return CanGetSemanticInfo(crefSyntax) ? GetSymbolInfoWorker(crefSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken) : SymbolInfo.None; } /// <summary> /// Binds the expression in the context of the specified location and gets symbol information. /// This method is used to get symbol information about an expression that did not actually /// appear in the source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and /// accessibility. This character position must be within the FullSpan of the Root syntax /// node in this SemanticModel. /// </param> /// <param name="expression">A syntax node that represents a parsed expression. This syntax /// node need not and typically does not appear in the source code referred to by the /// SemanticModel instance.</param> /// <param name="bindingOption">Indicates whether to binding the expression as a full expressions, /// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then /// expression should derive from TypeSyntax.</param> /// <returns>The symbol information for the topmost node of the expression.</returns> /// <remarks> /// The passed in expression is interpreted as a stand-alone expression, as if it /// appeared by itself somewhere within the scope that encloses "position". /// /// <paramref name="bindingOption"/> is ignored if <paramref name="position"/> is within a documentation /// comment cref attribute value. /// </remarks> public SymbolInfo GetSpeculativeSymbolInfo(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { if (!CanGetSemanticInfo(expression, isSpeculative: true)) return SymbolInfo.None; Binder binder; ImmutableArray<Symbol> crefSymbols; BoundNode boundNode = GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); //calls CheckAndAdjustPosition Debug.Assert(boundNode == null || crefSymbols.IsDefault); if (boundNode == null) { return crefSymbols.IsDefault ? SymbolInfo.None : GetCrefSymbolInfo(crefSymbols, SymbolInfoOptions.DefaultOptions, hasParameterList: false); } var symbolInfo = this.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundNode, boundNode, boundNodeForSyntacticParent: null, binderOpt: binder); return symbolInfo; } /// <summary> /// Bind the attribute in the context of the specified location and get semantic information /// such as type, symbols and diagnostics. This method is used to get semantic information about an attribute /// that did not actually appear in the source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. In order to obtain /// the correct scoping rules for the attribute, position should be the Start position of the Span of the symbol that /// the attribute is being applied to. /// </param> /// <param name="attribute">A syntax node that represents a parsed attribute. This syntax node /// need not and typically does not appear in the source code referred to SemanticModel instance.</param> /// <returns>The semantic information for the topmost node of the attribute.</returns> public SymbolInfo GetSpeculativeSymbolInfo(int position, AttributeSyntax attribute) { Debug.Assert(CanGetSemanticInfo(attribute, isSpeculative: true)); Binder binder; BoundNode boundNode = GetSpeculativelyBoundAttribute(position, attribute, out binder); //calls CheckAndAdjustPosition if (boundNode == null) return SymbolInfo.None; var symbolInfo = this.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundNode, boundNode, boundNodeForSyntacticParent: null, binderOpt: binder); return symbolInfo; } /// <summary> /// Bind the constructor initializer in the context of the specified location and get semantic information /// such as type, symbols and diagnostics. This method is used to get semantic information about a constructor /// initializer that did not actually appear in the source code. /// /// NOTE: This will only work in locations where there is already a constructor initializer. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// Furthermore, it must be within the span of an existing constructor initializer. /// </param> /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. This syntax node /// need not and typically does not appear in the source code referred to SemanticModel instance.</param> /// <returns>The semantic information for the topmost node of the constructor initializer.</returns> public SymbolInfo GetSpeculativeSymbolInfo(int position, ConstructorInitializerSyntax constructorInitializer) { Debug.Assert(CanGetSemanticInfo(constructorInitializer, isSpeculative: true)); position = CheckAndAdjustPosition(position); if (constructorInitializer == null) { throw new ArgumentNullException(nameof(constructorInitializer)); } // NOTE: since we're going to be depending on a MemberModel to do the binding for us, // we need to find a constructor initializer in the tree of this semantic model. // NOTE: This approach will not allow speculative binding of a constructor initializer // on a constructor that didn't formerly have one. // TODO: Should we support positions that are not in existing constructor initializers? // If so, we will need to build up the context that would otherwise be built up by // InitializerMemberModel. var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<ConstructorInitializerSyntax>().FirstOrDefault(); if (existingConstructorInitializer == null) { return SymbolInfo.None; } MemberSemanticModel memberModel = GetMemberModel(existingConstructorInitializer); if (memberModel == null) { return SymbolInfo.None; } var binder = memberModel.GetEnclosingBinder(position); if (binder != null) { binder = new ExecutableCodeBinder(constructorInitializer, binder.ContainingMemberOrLambda, binder); BoundExpressionStatement bnode = binder.BindConstructorInitializer(constructorInitializer, BindingDiagnosticBag.Discarded); var binfo = GetSymbolInfoFromBoundConstructorInitializer(memberModel, binder, bnode); return binfo; } else { return SymbolInfo.None; } } private static SymbolInfo GetSymbolInfoFromBoundConstructorInitializer(MemberSemanticModel memberModel, Binder binder, BoundExpressionStatement bnode) { BoundExpression expression = bnode.Expression; while (expression is BoundSequence sequence) { expression = sequence.Value; } return memberModel.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, expression, expression, boundNodeForSyntacticParent: null, binderOpt: binder); } /// <summary> /// Bind the constructor initializer in the context of the specified location and get semantic information /// about symbols. This method is used to get semantic information about a constructor /// initializer that did not actually appear in the source code. /// /// NOTE: This will only work in locations where there is already a constructor initializer. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the span of an existing constructor initializer. /// </param> /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. This syntax node /// need not and typically does not appear in the source code referred to SemanticModel instance.</param> /// <returns>The semantic information for the topmost node of the constructor initializer.</returns> public SymbolInfo GetSpeculativeSymbolInfo(int position, PrimaryConstructorBaseTypeSyntax constructorInitializer) { Debug.Assert(CanGetSemanticInfo(constructorInitializer, isSpeculative: true)); position = CheckAndAdjustPosition(position); if (constructorInitializer == null) { throw new ArgumentNullException(nameof(constructorInitializer)); } // NOTE: since we're going to be depending on a MemberModel to do the binding for us, // we need to find a constructor initializer in the tree of this semantic model. // NOTE: This approach will not allow speculative binding of a constructor initializer // on a constructor that didn't formerly have one. // TODO: Should we support positions that are not in existing constructor initializers? // If so, we will need to build up the context that would otherwise be built up by // InitializerMemberModel. var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<PrimaryConstructorBaseTypeSyntax>().FirstOrDefault(); if (existingConstructorInitializer == null) { return SymbolInfo.None; } MemberSemanticModel memberModel = GetMemberModel(existingConstructorInitializer); if (memberModel == null) { return SymbolInfo.None; } var argumentList = existingConstructorInitializer.ArgumentList; var binder = memberModel.GetEnclosingBinder(LookupPosition.IsBetweenTokens(position, argumentList.OpenParenToken, argumentList.CloseParenToken) ? position : argumentList.OpenParenToken.SpanStart); if (binder != null) { binder = new ExecutableCodeBinder(constructorInitializer, binder.ContainingMemberOrLambda, binder); BoundExpressionStatement bnode = binder.BindConstructorInitializer(constructorInitializer, BindingDiagnosticBag.Discarded); SymbolInfo binfo = GetSymbolInfoFromBoundConstructorInitializer(memberModel, binder, bnode); return binfo; } else { return SymbolInfo.None; } } /// <summary> /// Bind the cref in the context of the specified location and get semantic information /// such as type, symbols and diagnostics. This method is used to get semantic information about a cref /// that did not actually appear in the source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. In order to obtain /// the correct scoping rules for the cref, position should be the Start position of the Span of the original cref. /// </param> /// <param name="cref">A syntax node that represents a parsed cref. This syntax node /// need not and typically does not appear in the source code referred to SemanticModel instance.</param> /// <param name="options">SymbolInfo options.</param> /// <returns>The semantic information for the topmost node of the cref.</returns> public SymbolInfo GetSpeculativeSymbolInfo(int position, CrefSyntax cref, SymbolInfoOptions options = SymbolInfoOptions.DefaultOptions) { Debug.Assert(CanGetSemanticInfo(cref, isSpeculative: true)); position = CheckAndAdjustPosition(position); return this.GetCrefSymbolInfo(position, cref, options, HasParameterList(cref)); } #endregion GetSymbolInfo #region GetTypeInfo /// <summary> /// Gets type information about a constructor initializer. /// </summary> /// <param name="constructorInitializer">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public TypeInfo GetTypeInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(constructorInitializer); return CanGetSemanticInfo(constructorInitializer) ? GetTypeInfoWorker(constructorInitializer, cancellationToken) : CSharpTypeInfo.None; } public abstract TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); public TypeInfo GetTypeInfo(PatternSyntax pattern, CancellationToken cancellationToken = default(CancellationToken)) { while (pattern is ParenthesizedPatternSyntax pp) pattern = pp.Pattern; CheckSyntaxNode(pattern); return GetTypeInfoWorker(pattern, cancellationToken); } /// <summary> /// Gets type information about an expression. /// </summary> /// <param name="expression">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public TypeInfo GetTypeInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); if (!CanGetSemanticInfo(expression)) { return CSharpTypeInfo.None; } else if (SyntaxFacts.IsDeclarationExpressionType(expression, out DeclarationExpressionSyntax parent)) { switch (parent.Designation.Kind()) { case SyntaxKind.SingleVariableDesignation: var (declarationType, annotation) = ((ITypeSymbol, CodeAnalysis.NullableAnnotation))TypeFromVariable((SingleVariableDesignationSyntax)parent.Designation, cancellationToken); var declarationTypeSymbol = declarationType.GetSymbol(); var nullabilityInfo = annotation.ToNullabilityInfo(declarationTypeSymbol); return new CSharpTypeInfo(declarationTypeSymbol, declarationTypeSymbol, nullabilityInfo, nullabilityInfo, Conversion.Identity); case SyntaxKind.DiscardDesignation: var declarationInfo = GetTypeInfoWorker(parent, cancellationToken); return new CSharpTypeInfo(declarationInfo.Type, declarationInfo.Type, declarationInfo.Nullability, declarationInfo.Nullability, Conversion.Identity); case SyntaxKind.ParenthesizedVariableDesignation: if (((TypeSyntax)expression).IsVar) { return CSharpTypeInfo.None; } break; } } return GetTypeInfoWorker(expression, cancellationToken); } /// <summary> /// Gets type information about an attribute. /// </summary> /// <param name="attributeSyntax">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public TypeInfo GetTypeInfo(AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(attributeSyntax); return CanGetSemanticInfo(attributeSyntax) ? GetTypeInfoWorker(attributeSyntax, cancellationToken) : CSharpTypeInfo.None; } /// <summary> /// Gets the conversion that occurred between the expression's type and type implied by the expression's context. /// </summary> public Conversion GetConversion(SyntaxNode expression, CancellationToken cancellationToken = default(CancellationToken)) { var csnode = (CSharpSyntaxNode)expression; CheckSyntaxNode(csnode); var info = CanGetSemanticInfo(csnode) ? GetTypeInfoWorker(csnode, cancellationToken) : CSharpTypeInfo.None; return info.ImplicitConversion; } /// <summary> /// Binds the expression in the context of the specified location and gets type information. /// This method is used to get type information about an expression that did not actually /// appear in the source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and /// accessibility. This character position must be within the FullSpan of the Root syntax /// node in this SemanticModel. /// </param> /// <param name="expression">A syntax node that represents a parsed expression. This syntax /// node need not and typically does not appear in the source code referred to by the /// SemanticModel instance.</param> /// <param name="bindingOption">Indicates whether to binding the expression as a full expressions, /// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then /// expression should derive from TypeSyntax.</param> /// <returns>The type information for the topmost node of the expression.</returns> /// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it /// appeared by itself somewhere within the scope that encloses "position".</remarks> public TypeInfo GetSpeculativeTypeInfo(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { return GetSpeculativeTypeInfoWorker(position, expression, bindingOption); } internal CSharpTypeInfo GetSpeculativeTypeInfoWorker(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { if (!CanGetSemanticInfo(expression, isSpeculative: true)) { return CSharpTypeInfo.None; } ImmutableArray<Symbol> crefSymbols; BoundNode boundNode = GetSpeculativelyBoundExpression(position, expression, bindingOption, out _, out crefSymbols); //calls CheckAndAdjustPosition Debug.Assert(boundNode == null || crefSymbols.IsDefault); if (boundNode == null) { return !crefSymbols.IsDefault && crefSymbols.Length == 1 ? GetTypeInfoForSymbol(crefSymbols[0]) : CSharpTypeInfo.None; } var typeInfo = GetTypeInfoForNode(boundNode, boundNode, boundNodeForSyntacticParent: null); return typeInfo; } /// <summary> /// Gets the conversion that occurred between the expression's type and type implied by the expression's context. /// </summary> public Conversion GetSpeculativeConversion(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { var info = this.GetSpeculativeTypeInfoWorker(position, expression, bindingOption); return info.ImplicitConversion; } #endregion GetTypeInfo #region GetMemberGroup /// <summary> /// Gets a list of method or indexed property symbols for a syntax node. /// </summary> /// <param name="expression">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public ImmutableArray<ISymbol> GetMemberGroup(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); return CanGetSemanticInfo(expression) ? this.GetMemberGroupWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols() : ImmutableArray<ISymbol>.Empty; } /// <summary> /// Gets a list of method or indexed property symbols for a syntax node. /// </summary> /// <param name="attribute">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public ImmutableArray<ISymbol> GetMemberGroup(AttributeSyntax attribute, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(attribute); return CanGetSemanticInfo(attribute) ? this.GetMemberGroupWorker(attribute, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols() : ImmutableArray<ISymbol>.Empty; } /// <summary> /// Gets a list of method symbols for a syntax node. /// </summary> /// <param name="initializer">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public ImmutableArray<ISymbol> GetMemberGroup(ConstructorInitializerSyntax initializer, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(initializer); return CanGetSemanticInfo(initializer) ? this.GetMemberGroupWorker(initializer, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols() : ImmutableArray<ISymbol>.Empty; } #endregion GetMemberGroup #region GetIndexerGroup /// <summary> /// Returns the list of accessible, non-hidden indexers that could be invoked with the given expression as receiver. /// </summary> /// <param name="expression">Potential indexer receiver.</param> /// <param name="cancellationToken">To cancel the computation.</param> /// <returns>Accessible, non-hidden indexers.</returns> /// <remarks> /// If the receiver is an indexer expression, the list will contain the indexers that could be applied to the result /// of accessing the indexer, not the set of candidates that were considered during construction of the indexer expression. /// </remarks> public ImmutableArray<IPropertySymbol> GetIndexerGroup(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); return CanGetSemanticInfo(expression) ? this.GetIndexerGroupWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken) : ImmutableArray<IPropertySymbol>.Empty; } #endregion GetIndexerGroup #region GetConstantValue public Optional<object> GetConstantValue(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); return CanGetSemanticInfo(expression) ? this.GetConstantValueWorker(expression, cancellationToken) : default(Optional<object>); } #endregion GetConstantValue /// <summary> /// Gets the semantic information associated with a query clause. /// </summary> public abstract QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// If <paramref name="nameSyntax"/> resolves to an alias name, return the AliasSymbol corresponding /// to A. Otherwise return null. /// </summary> public IAliasSymbol GetAliasInfo(IdentifierNameSyntax nameSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(nameSyntax); if (!CanGetSemanticInfo(nameSyntax)) return null; SymbolInfo info = GetSymbolInfoWorker(nameSyntax, SymbolInfoOptions.PreferTypeToConstructors | SymbolInfoOptions.PreserveAliases, cancellationToken); return info.Symbol as IAliasSymbol; } /// <summary> /// Binds the name in the context of the specified location and sees if it resolves to an /// alias name. If it does, return the AliasSymbol corresponding to it. Otherwise, return null. /// </summary> /// <param name="position">A character position used to identify a declaration scope and /// accessibility. This character position must be within the FullSpan of the Root syntax /// node in this SemanticModel. /// </param> /// <param name="nameSyntax">A syntax node that represents a name. This syntax /// node need not and typically does not appear in the source code referred to by the /// SemanticModel instance.</param> /// <param name="bindingOption">Indicates whether to binding the name as a full expression, /// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then /// expression should derive from TypeSyntax.</param> /// <remarks>The passed in name is interpreted as a stand-alone name, as if it /// appeared by itself somewhere within the scope that encloses "position".</remarks> public IAliasSymbol GetSpeculativeAliasInfo(int position, IdentifierNameSyntax nameSyntax, SpeculativeBindingOption bindingOption) { Binder binder; ImmutableArray<Symbol> crefSymbols; BoundNode boundNode = GetSpeculativelyBoundExpression(position, nameSyntax, bindingOption, out binder, out crefSymbols); //calls CheckAndAdjustPosition Debug.Assert(boundNode == null || crefSymbols.IsDefault); if (boundNode == null) { return !crefSymbols.IsDefault && crefSymbols.Length == 1 ? (crefSymbols[0] as AliasSymbol).GetPublicSymbol() : null; } var symbolInfo = this.GetSymbolInfoForNode(SymbolInfoOptions.PreferTypeToConstructors | SymbolInfoOptions.PreserveAliases, boundNode, boundNode, boundNodeForSyntacticParent: null, binderOpt: binder); return symbolInfo.Symbol as IAliasSymbol; } /// <summary> /// Gets the binder that encloses the position. /// </summary> internal Binder GetEnclosingBinder(int position) { Binder result = GetEnclosingBinderInternal(position); Debug.Assert(result == null || result.IsSemanticModelBinder); return result; } internal abstract Binder GetEnclosingBinderInternal(int position); /// <summary> /// Gets the MemberSemanticModel that contains the node. /// </summary> internal abstract MemberSemanticModel GetMemberModel(SyntaxNode node); internal bool IsInTree(SyntaxNode node) { return node.SyntaxTree == this.SyntaxTree; } private static bool IsInStructuredTriviaOtherThanCrefOrNameAttribute(CSharpSyntaxNode node) { while (node != null) { if (node.Kind() == SyntaxKind.XmlCrefAttribute || node.Kind() == SyntaxKind.XmlNameAttribute) { return false; } else if (node.IsStructuredTrivia) { return true; } else { node = node.ParentOrStructuredTriviaParent; } } return false; } /// <summary> /// Given a position, locates the containing token. If the position is actually within the /// leading trivia of the containing token or if that token is EOF, moves one token to the /// left. Returns the start position of the resulting token. /// /// This has the effect of moving the position left until it hits the beginning of a non-EOF /// token. /// /// Throws an ArgumentOutOfRangeException if position is not within the root of this model. /// </summary> protected int CheckAndAdjustPosition(int position) { SyntaxToken unused; return CheckAndAdjustPosition(position, out unused); } protected int CheckAndAdjustPosition(int position, out SyntaxToken token) { int fullStart = this.Root.Position; int fullEnd = this.Root.FullSpan.End; bool atEOF = position == fullEnd && position == this.SyntaxTree.GetRoot().FullSpan.End; if ((fullStart <= position && position < fullEnd) || atEOF) // allow for EOF { token = (atEOF ? (CSharpSyntaxNode)this.SyntaxTree.GetRoot() : Root).FindTokenIncludingCrefAndNameAttributes(position); if (position < token.SpanStart) // NB: Span, not FullSpan { // If this is already the first token, then the result will be default(SyntaxToken) token = token.GetPreviousToken(); } // If the first token in the root is missing, it's possible to step backwards // past the start of the root. All sorts of bad things will happen in that case, // so just use the start of the root span. // CONSIDER: this should only happen when we step past the first token found, so // the start of that token would be another possible return value. return Math.Max(token.SpanStart, fullStart); } else if (fullStart == fullEnd && position == fullEnd) { // The root is an empty span and isn't the full compilation unit. No other choice here. token = default(SyntaxToken); return fullStart; } throw new ArgumentOutOfRangeException(nameof(position), position, string.Format(CSharpResources.PositionIsNotWithinSyntax, Root.FullSpan)); } /// <summary> /// A convenience method that determines a position from a node. If the node is missing, /// then its position will be adjusted using CheckAndAdjustPosition. /// </summary> protected int GetAdjustedNodePosition(SyntaxNode node) { Debug.Assert(IsInTree(node)); var fullSpan = this.Root.FullSpan; var position = node.SpanStart; // skip zero-width tokens to get the position, but never get past the end of the node SyntaxToken firstToken = node.GetFirstToken(includeZeroWidth: false); if (firstToken.Node is object) { int betterPosition = firstToken.SpanStart; if (betterPosition < node.Span.End) { position = betterPosition; } } if (fullSpan.IsEmpty) { Debug.Assert(position == fullSpan.Start); // At end of zero-width full span. No need to call // CheckAndAdjustPosition since that will simply // return the original position. return position; } else if (position == fullSpan.End) { Debug.Assert(node.Width == 0); // For zero-width node at the end of the full span, // check and adjust the preceding position. return CheckAndAdjustPosition(position - 1); } else if (node.IsMissing || node.HasErrors || node.Width == 0 || node.IsPartOfStructuredTrivia()) { return CheckAndAdjustPosition(position); } else { // No need to adjust position. return position; } } [Conditional("DEBUG")] protected void AssertPositionAdjusted(int position) { Debug.Assert(position == CheckAndAdjustPosition(position), "Expected adjusted position"); } protected void CheckSyntaxNode(CSharpSyntaxNode syntax) { if (syntax == null) { throw new ArgumentNullException(nameof(syntax)); } if (!IsInTree(syntax)) { throw new ArgumentException(CSharpResources.SyntaxNodeIsNotWithinSynt); } } // This method ensures that the given syntax node to speculate is non-null and doesn't belong to a SyntaxTree of any model in the chain. private void CheckModelAndSyntaxNodeToSpeculate(CSharpSyntaxNode syntax) { if (syntax == null) { throw new ArgumentNullException(nameof(syntax)); } if (this.IsSpeculativeSemanticModel) { throw new InvalidOperationException(CSharpResources.ChainingSpeculativeModelIsNotSupported); } if (this.Compilation.ContainsSyntaxTree(syntax.SyntaxTree)) { throw new ArgumentException(CSharpResources.SpeculatedSyntaxNodeCannotBelongToCurrentCompilation); } } /// <summary> /// Gets the available named symbols in the context of the specified location and optional container. Only /// symbols that are accessible and visible from the given location are returned. /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="container">The container to search for symbols within. If null then the enclosing declaration /// scope around position is used.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <param name="includeReducedExtensionMethods">Consider (reduced) extension methods.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if "container" is /// specified, the "position" location is significant for determining which members of "containing" are /// accessible. /// /// Labels are not considered (see <see cref="LookupLabels"/>). /// /// Non-reduced extension methods are considered regardless of the value of <paramref name="includeReducedExtensionMethods"/>. /// </remarks> public ImmutableArray<ISymbol> LookupSymbols( int position, NamespaceOrTypeSymbol container = null, string name = null, bool includeReducedExtensionMethods = false) { var options = includeReducedExtensionMethods ? LookupOptions.IncludeExtensionMethods : LookupOptions.Default; return LookupSymbolsInternal(position, container, name, options, useBaseReferenceAccessibility: false); } /// <summary> /// Gets the available base type members in the context of the specified location. Akin to /// calling <see cref="LookupSymbols"/> with the container set to the immediate base type of /// the type in which <paramref name="position"/> occurs. However, the accessibility rules /// are different: protected members of the base type will be visible. /// /// Consider the following example: /// /// public class Base /// { /// protected void M() { } /// } /// /// public class Derived : Base /// { /// void Test(Base b) /// { /// b.M(); // Error - cannot access protected member. /// base.M(); /// } /// } /// /// Protected members of an instance of another type are only accessible if the instance is known /// to be "this" instance (as indicated by the "base" keyword). /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. /// /// Non-reduced extension methods are considered, but reduced extension methods are not. /// </remarks> public new ImmutableArray<ISymbol> LookupBaseMembers( int position, string name = null) { return LookupSymbolsInternal(position, container: null, name: name, options: LookupOptions.Default, useBaseReferenceAccessibility: true); } /// <summary> /// Gets the available named static member symbols in the context of the specified location and optional container. /// Only members that are accessible and visible from the given location are returned. /// /// Non-reduced extension methods are considered, since they are static methods. /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="container">The container to search for symbols within. If null then the enclosing declaration /// scope around position is used.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if "container" is /// specified, the "position" location is significant for determining which members of "containing" are /// accessible. /// </remarks> public ImmutableArray<ISymbol> LookupStaticMembers( int position, NamespaceOrTypeSymbol container = null, string name = null) { return LookupSymbolsInternal(position, container, name, LookupOptions.MustNotBeInstance, useBaseReferenceAccessibility: false); } /// <summary> /// Gets the available named namespace and type symbols in the context of the specified location and optional container. /// Only members that are accessible and visible from the given location are returned. /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="container">The container to search for symbols within. If null then the enclosing declaration /// scope around position is used.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if "container" is /// specified, the "position" location is significant for determining which members of "containing" are /// accessible. /// /// Does not return NamespaceOrTypeSymbol, because there could be aliases. /// </remarks> public ImmutableArray<ISymbol> LookupNamespacesAndTypes( int position, NamespaceOrTypeSymbol container = null, string name = null) { return LookupSymbolsInternal(position, container, name, LookupOptions.NamespacesOrTypesOnly, useBaseReferenceAccessibility: false); } /// <summary> /// Gets the available named label symbols in the context of the specified location and optional container. /// Only members that are accessible and visible from the given location are returned. /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if "container" is /// specified, the "position" location is significant for determining which members of "containing" are /// accessible. /// </remarks> public new ImmutableArray<ISymbol> LookupLabels( int position, string name = null) { return LookupSymbolsInternal(position, container: null, name: name, options: LookupOptions.LabelsOnly, useBaseReferenceAccessibility: false); } /// <summary> /// Gets the available named symbols in the context of the specified location and optional /// container. Only symbols that are accessible and visible from the given location are /// returned. /// </summary> /// <param name="position">The character position for determining the enclosing declaration /// scope and accessibility.</param> /// <param name="container">The container to search for symbols within. If null then the /// enclosing declaration scope around position is used.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <param name="options">Additional options that affect the lookup process.</param> /// <param name="useBaseReferenceAccessibility">Ignore 'throughType' in accessibility checking. /// Used in checking accessibility of symbols accessed via 'MyBase' or 'base'.</param> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if /// "container" is specified, the "position" location is significant for determining which /// members of "containing" are accessible. /// </remarks> /// <exception cref="ArgumentException">Throws an argument exception if the passed lookup options are invalid.</exception> private ImmutableArray<ISymbol> LookupSymbolsInternal( int position, NamespaceOrTypeSymbol container, string name, LookupOptions options, bool useBaseReferenceAccessibility) { Debug.Assert((options & LookupOptions.UseBaseReferenceAccessibility) == 0, "Use the useBaseReferenceAccessibility parameter."); if (useBaseReferenceAccessibility) { options |= LookupOptions.UseBaseReferenceAccessibility; } Debug.Assert(!options.IsAttributeTypeLookup()); // Not exposed publicly. options.ThrowIfInvalid(); SyntaxToken token; position = CheckAndAdjustPosition(position, out token); if ((object)container == null || container.Kind == SymbolKind.Namespace) { options &= ~LookupOptions.IncludeExtensionMethods; } var binder = GetEnclosingBinder(position); if (binder == null) { return ImmutableArray<ISymbol>.Empty; } if (useBaseReferenceAccessibility) { Debug.Assert((object)container == null); TypeSymbol containingType = binder.ContainingType; TypeSymbol baseType = null; // For a script class or a submission class base should have no members. if ((object)containingType != null && containingType.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)containingType).IsScriptClass) { return ImmutableArray<ISymbol>.Empty; } if ((object)containingType == null || (object)(baseType = containingType.BaseTypeNoUseSiteDiagnostics) == null) { throw new ArgumentException( "Not a valid position for a call to LookupBaseMembers (must be in a type with a base type)", nameof(position)); } container = baseType; } if (!binder.IsInMethodBody && (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0) { // Method type parameters are not in scope outside a method // body unless the position is either: // a) in a type-only context inside an expression, or // b) inside of an XML name attribute in an XML doc comment. var parentExpr = token.Parent as ExpressionSyntax; if (parentExpr != null && !(parentExpr.Parent is XmlNameAttributeSyntax) && !SyntaxFacts.IsInTypeOnlyContext(parentExpr)) { options |= LookupOptions.MustNotBeMethodTypeParameter; } } var info = LookupSymbolsInfo.GetInstance(); info.FilterName = name; if ((object)container == null) { binder.AddLookupSymbolsInfo(info, options); } else { binder.AddMemberLookupSymbolsInfo(info, container, options, binder); } var results = ArrayBuilder<ISymbol>.GetInstance(info.Count); if (name == null) { // If they didn't provide a name, then look up all names and associated arities // and find all the corresponding symbols. foreach (string foundName in info.Names) { AppendSymbolsWithName(results, foundName, binder, container, options, info); } } else { // They provided a name. Find all the arities for that name, and then look all of those up. AppendSymbolsWithName(results, name, binder, container, options, info); } info.Free(); if ((options & LookupOptions.IncludeExtensionMethods) != 0) { var lookupResult = LookupResult.GetInstance(); options |= LookupOptions.AllMethodsOnArityZero; options &= ~LookupOptions.MustBeInstance; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; binder.LookupExtensionMethods(lookupResult, name, 0, options, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { TypeSymbol containingType = (TypeSymbol)container; foreach (MethodSymbol extensionMethod in lookupResult.Symbols) { var reduced = extensionMethod.ReduceExtensionMethod(containingType, Compilation); if ((object)reduced != null) { results.Add(reduced.GetPublicSymbol()); } } } lookupResult.Free(); } ImmutableArray<ISymbol> sealedResults = results.ToImmutableAndFree(); return name == null ? FilterNotReferencable(sealedResults) : sealedResults; } private void AppendSymbolsWithName(ArrayBuilder<ISymbol> results, string name, Binder binder, NamespaceOrTypeSymbol container, LookupOptions options, LookupSymbolsInfo info) { LookupSymbolsInfo.IArityEnumerable arities; Symbol uniqueSymbol; if (info.TryGetAritiesAndUniqueSymbol(name, out arities, out uniqueSymbol)) { if ((object)uniqueSymbol != null) { // This name mapped to something unique. We don't need to proceed // with a costly lookup. Just add it straight to the results. results.Add(RemapSymbolIfNecessary(uniqueSymbol).GetPublicSymbol()); } else { // The name maps to multiple symbols. Actually do a real lookup so // that we will properly figure out hiding and whatnot. if (arities != null) { foreach (var arity in arities) { this.AppendSymbolsWithNameAndArity(results, name, arity, binder, container, options); } } else { //non-unique symbol with non-zero arity doesn't seem possible. this.AppendSymbolsWithNameAndArity(results, name, 0, binder, container, options); } } } } private void AppendSymbolsWithNameAndArity( ArrayBuilder<ISymbol> results, string name, int arity, Binder binder, NamespaceOrTypeSymbol container, LookupOptions options) { Debug.Assert(results != null); // Don't need to de-dup since AllMethodsOnArityZero can't be set at this point (not exposed in CommonLookupOptions). Debug.Assert((options & LookupOptions.AllMethodsOnArityZero) == 0); var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; binder.LookupSymbolsSimpleName( lookupResult, container, name, arity, basesBeingResolved: null, options: options & ~LookupOptions.IncludeExtensionMethods, diagnose: false, useSiteInfo: ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { if (lookupResult.Symbols.Any(t => t.Kind == SymbolKind.NamedType || t.Kind == SymbolKind.Namespace || t.Kind == SymbolKind.ErrorType)) { // binder.ResultSymbol is defined only for type/namespace lookups bool wasError; Symbol singleSymbol = binder.ResultSymbol(lookupResult, name, arity, this.Root, BindingDiagnosticBag.Discarded, true, out wasError, container, options); if (!wasError) { results.Add(RemapSymbolIfNecessary(singleSymbol).GetPublicSymbol()); } else { foreach (var symbol in lookupResult.Symbols) { results.Add(RemapSymbolIfNecessary(symbol).GetPublicSymbol()); } } } else { foreach (var symbol in lookupResult.Symbols) { results.Add(RemapSymbolIfNecessary(symbol).GetPublicSymbol()); } } } lookupResult.Free(); } private Symbol RemapSymbolIfNecessary(Symbol symbol) { switch (symbol) { case LocalSymbol _: case ParameterSymbol _: case MethodSymbol { MethodKind: MethodKind.LambdaMethod }: return RemapSymbolIfNecessaryCore(symbol); default: return symbol; } } /// <summary> /// Remaps a local, parameter, localfunction, or lambda symbol, if that symbol or its containing /// symbols were reinferred. This should only be called when nullable semantic analysis is enabled. /// </summary> internal abstract Symbol RemapSymbolIfNecessaryCore(Symbol symbol); private static ImmutableArray<ISymbol> FilterNotReferencable(ImmutableArray<ISymbol> sealedResults) { ArrayBuilder<ISymbol> builder = null; int pos = 0; foreach (var result in sealedResults) { if (result.CanBeReferencedByName) { builder?.Add(result); } else if (builder == null) { builder = ArrayBuilder<ISymbol>.GetInstance(); builder.AddRange(sealedResults, pos); } pos++; } return builder?.ToImmutableAndFree() ?? sealedResults; } /// <summary> /// Determines if the symbol is accessible from the specified location. /// </summary> /// <param name="position">A character position used to identify a declaration scope and /// accessibility. This character position must be within the FullSpan of the Root syntax /// node in this SemanticModel. /// </param> /// <param name="symbol">The symbol that we are checking to see if it accessible.</param> /// <returns> /// True if "symbol is accessible, false otherwise.</returns> /// <remarks> /// This method only checks accessibility from the point of view of the accessibility /// modifiers on symbol and its containing types. Even if true is returned, the given symbol /// may not be able to be referenced for other reasons, such as name hiding. /// </remarks> public bool IsAccessible(int position, Symbol symbol) { position = CheckAndAdjustPosition(position); if ((object)symbol == null) { throw new ArgumentNullException(nameof(symbol)); } var binder = this.GetEnclosingBinder(position); if (binder != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return binder.IsAccessible(symbol, ref discardedUseSiteInfo, null); } return false; } /// <summary> /// Field-like events can be used as fields in types that can access private /// members of the declaring type of the event. /// </summary> public bool IsEventUsableAsField(int position, EventSymbol symbol) { return symbol is object && symbol.HasAssociatedField && this.IsAccessible(position, symbol.AssociatedField); //calls CheckAndAdjustPosition } private bool IsInTypeofExpression(int position) { var token = this.Root.FindToken(position); var curr = token.Parent; while (curr != this.Root) { if (curr.IsKind(SyntaxKind.TypeOfExpression)) { return true; } curr = curr.ParentOrStructuredTriviaParent; } return false; } // Gets the semantic info from a specific bound node and a set of diagnostics // lowestBoundNode: The lowest node in the bound tree associated with node // highestBoundNode: The highest node in the bound tree associated with node // boundNodeForSyntacticParent: The lowest node in the bound tree associated with node.Parent. // binderOpt: If this is null, then the one enclosing the bound node's syntax will be used (unsafe during speculative binding). [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Provide " + nameof(ArrayBuilder<Symbol>) + " capacity to reduce number of allocations.")] internal SymbolInfo GetSymbolInfoForNode( SymbolInfoOptions options, BoundNode lowestBoundNode, BoundNode highestBoundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt) { BoundExpression boundExpr; switch (highestBoundNode) { case BoundRecursivePattern pat: return GetSymbolInfoForDeconstruction(pat); } switch (lowestBoundNode) { case BoundPositionalSubpattern subpattern: return GetSymbolInfoForSubpattern(subpattern.Symbol); case BoundPropertySubpattern subpattern: return GetSymbolInfoForSubpattern(subpattern.Member?.Symbol); case BoundPropertySubpatternMember subpatternMember: return GetSymbolInfoForSubpattern(subpatternMember.Symbol); case BoundExpression boundExpr2: boundExpr = boundExpr2; break; default: return SymbolInfo.None; } // TODO: Should parenthesized expression really not have symbols? At least for C#, I'm not sure that // is right. For example, C# allows the assignment statement: // (i) = 9; // So we don't think this code should special case parenthesized expressions. // Get symbols and result kind from the lowest and highest nodes associated with the // syntax node. ImmutableArray<Symbol> symbols = GetSemanticSymbols( boundExpr, boundNodeForSyntacticParent, binderOpt, options, out bool isDynamic, out LookupResultKind resultKind, out ImmutableArray<Symbol> unusedMemberGroup); if (highestBoundNode is BoundExpression highestBoundExpr) { LookupResultKind highestResultKind; bool highestIsDynamic; ImmutableArray<Symbol> unusedHighestMemberGroup; ImmutableArray<Symbol> highestSymbols = GetSemanticSymbols( highestBoundExpr, boundNodeForSyntacticParent, binderOpt, options, out highestIsDynamic, out highestResultKind, out unusedHighestMemberGroup); if ((symbols.Length != 1 || resultKind == LookupResultKind.OverloadResolutionFailure) && highestSymbols.Length > 0) { symbols = highestSymbols; resultKind = highestResultKind; isDynamic = highestIsDynamic; } else if (highestResultKind != LookupResultKind.Empty && highestResultKind < resultKind) { resultKind = highestResultKind; isDynamic = highestIsDynamic; } else if (highestBoundExpr.Kind == BoundKind.TypeOrValueExpression) { symbols = highestSymbols; resultKind = highestResultKind; isDynamic = highestIsDynamic; } else if (highestBoundExpr.Kind == BoundKind.UnaryOperator) { if (IsUserDefinedTrueOrFalse((BoundUnaryOperator)highestBoundExpr)) { symbols = highestSymbols; resultKind = highestResultKind; isDynamic = highestIsDynamic; } else { Debug.Assert(ReferenceEquals(lowestBoundNode, highestBoundNode), "How is it that this operator has the same syntax node as its operand?"); } } } if (resultKind == LookupResultKind.Empty) { // Empty typically indicates an error symbol that was created because no real // symbol actually existed. return SymbolInfoFactory.Create(ImmutableArray<Symbol>.Empty, LookupResultKind.Empty, isDynamic); } else { // Caas clients don't want ErrorTypeSymbol in the symbols, but the best guess // instead. If no best guess, then nothing is returned. var builder = ArrayBuilder<Symbol>.GetInstance(symbols.Length); foreach (Symbol symbol in symbols) { AddUnwrappingErrorTypes(builder, symbol); } symbols = builder.ToImmutableAndFree(); } if ((options & SymbolInfoOptions.ResolveAliases) != 0) { symbols = UnwrapAliases(symbols); } if (resultKind == LookupResultKind.Viable && symbols.Length > 1) { resultKind = LookupResultKind.OverloadResolutionFailure; } return SymbolInfoFactory.Create(symbols, resultKind, isDynamic); } private static SymbolInfo GetSymbolInfoForSubpattern(Symbol subpatternSymbol) { if (subpatternSymbol?.OriginalDefinition is ErrorTypeSymbol originalErrorType) { return new SymbolInfo(symbol: null, originalErrorType.CandidateSymbols.GetPublicSymbols(), originalErrorType.ResultKind.ToCandidateReason()); } return new SymbolInfo(subpatternSymbol.GetPublicSymbol(), CandidateReason.None); } private SymbolInfo GetSymbolInfoForDeconstruction(BoundRecursivePattern pat) { return new SymbolInfo(pat.DeconstructMethod.GetPublicSymbol(), CandidateReason.None); } private static void AddUnwrappingErrorTypes(ArrayBuilder<Symbol> builder, Symbol s) { var originalErrorSymbol = s.OriginalDefinition as ErrorTypeSymbol; if ((object)originalErrorSymbol != null) { builder.AddRange(originalErrorSymbol.CandidateSymbols); } else { builder.Add(s); } } private static bool IsUserDefinedTrueOrFalse(BoundUnaryOperator @operator) { UnaryOperatorKind operatorKind = @operator.OperatorKind; return operatorKind == UnaryOperatorKind.UserDefinedTrue || operatorKind == UnaryOperatorKind.UserDefinedFalse; } // Gets the semantic info from a specific bound node and a set of diagnostics // lowestBoundNode: The lowest node in the bound tree associated with node // highestBoundNode: The highest node in the bound tree associated with node // boundNodeForSyntacticParent: The lowest node in the bound tree associated with node.Parent. internal CSharpTypeInfo GetTypeInfoForNode( BoundNode lowestBoundNode, BoundNode highestBoundNode, BoundNode boundNodeForSyntacticParent) { BoundPattern pattern = lowestBoundNode as BoundPattern ?? highestBoundNode as BoundPattern ?? (highestBoundNode is BoundSubpattern sp ? sp.Pattern : null); if (pattern != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // https://github.com/dotnet/roslyn/issues/35032: support patterns return new CSharpTypeInfo( pattern.InputType, pattern.NarrowedType, nullability: default, convertedNullability: default, Compilation.Conversions.ClassifyBuiltInConversion(pattern.InputType, pattern.NarrowedType, ref discardedUseSiteInfo)); } if (lowestBoundNode is BoundPropertySubpatternMember member) { return new CSharpTypeInfo(member.Type, member.Type, nullability: default, convertedNullability: default, Conversion.Identity); } var boundExpr = lowestBoundNode as BoundExpression; var highestBoundExpr = highestBoundNode as BoundExpression; if (boundExpr != null && !(boundNodeForSyntacticParent != null && boundNodeForSyntacticParent.Syntax.Kind() == SyntaxKind.ObjectCreationExpression && ((ObjectCreationExpressionSyntax)boundNodeForSyntacticParent.Syntax).Type == boundExpr.Syntax)) // Do not return any type information for a ObjectCreationExpressionSyntax.Type node. { // TODO: Should parenthesized expression really not have symbols? At least for C#, I'm not sure that // is right. For example, C# allows the assignment statement: // (i) = 9; // So I don't assume this code should special case parenthesized expressions. TypeSymbol type = null; NullabilityInfo nullability = boundExpr.TopLevelNullability; if (boundExpr.HasExpressionType()) { type = boundExpr.Type; switch (boundExpr) { case BoundLocal local: { // Use of local before declaration requires some additional fixup. // Due to complications around implicit locals and type inference, we do not // try to obtain a type of a local when it is used before declaration, we use // a special error type symbol. However, semantic model should return the same // type information for usage of a local before and after its declaration. // We will detect the use before declaration cases and replace the error type // symbol with the one obtained from the local. It should be safe to get the type // from the local at this point. if (type is ExtendedErrorTypeSymbol extended && extended.VariableUsedBeforeDeclaration) { type = local.LocalSymbol.Type; nullability = local.LocalSymbol.TypeWithAnnotations.NullableAnnotation.ToNullabilityInfo(type); } break; } case BoundConvertedTupleLiteral { SourceTuple: BoundTupleLiteral original }: { // The bound tree fully binds tuple literals. From the language point of // view, however, converted tuple literals represent tuple conversions // from tuple literal expressions which may or may not have types type = original.Type; break; } } } // we match highestBoundExpr.Kind to various kind frequently, so cache it here. // use NoOp kind for the case when highestBoundExpr == null - NoOp will not match anything below. var highestBoundExprKind = highestBoundExpr?.Kind ?? BoundKind.NoOpStatement; TypeSymbol convertedType; NullabilityInfo convertedNullability; Conversion conversion; if (highestBoundExprKind == BoundKind.Lambda) // the enclosing conversion is explicit { var lambda = (BoundLambda)highestBoundExpr; convertedType = lambda.Type; // The bound tree always fully binds lambda and anonymous functions. From the language point of // view, however, anonymous functions converted to a real delegate type should only have a // ConvertedType, not a Type. So set Type to null here. Otherwise you get the edge case where both // Type and ConvertedType are the same, but the conversion isn't Identity. type = null; nullability = default; convertedNullability = new NullabilityInfo(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableFlowState.NotNull); conversion = new Conversion(ConversionKind.AnonymousFunction, lambda.Symbol, false); } else if ((highestBoundExpr as BoundConversion)?.Conversion.IsTupleLiteralConversion == true) { var tupleLiteralConversion = (BoundConversion)highestBoundExpr; if (tupleLiteralConversion.Operand.Kind == BoundKind.ConvertedTupleLiteral) { var convertedTuple = (BoundConvertedTupleLiteral)tupleLiteralConversion.Operand; type = convertedTuple.SourceTuple.Type; nullability = convertedTuple.TopLevelNullability; } else { (type, nullability) = getTypeAndNullability(tupleLiteralConversion.Operand); } (convertedType, convertedNullability) = getTypeAndNullability(tupleLiteralConversion); conversion = tupleLiteralConversion.Conversion; } else if (highestBoundExprKind == BoundKind.FixedLocalCollectionInitializer) { var initializer = (BoundFixedLocalCollectionInitializer)highestBoundExpr; (convertedType, convertedNullability) = getTypeAndNullability(initializer); (type, nullability) = getTypeAndNullability(initializer.Expression); // the most pertinent conversion is the pointer conversion conversion = BoundNode.GetConversion(initializer.ElementPointerConversion, initializer.ElementPointerPlaceholder); } else if (boundExpr is BoundConvertedSwitchExpression { WasTargetTyped: true } convertedSwitch) { if (highestBoundExpr is BoundConversion { ConversionKind: ConversionKind.SwitchExpression, Conversion: var convertedSwitchConversion }) { // There was an implicit cast. type = convertedSwitch.NaturalTypeOpt; convertedType = convertedSwitch.Type; convertedNullability = convertedSwitch.TopLevelNullability; conversion = convertedSwitchConversion.IsValid ? convertedSwitchConversion : Conversion.NoConversion; } else { // There was an explicit cast on top of this type = convertedSwitch.NaturalTypeOpt; (convertedType, convertedNullability) = (type, nullability); conversion = Conversion.Identity; } } else if (boundExpr is BoundConditionalOperator { WasTargetTyped: true } cond) { if (highestBoundExpr is BoundConversion { ConversionKind: ConversionKind.ConditionalExpression }) { // There was an implicit cast. type = cond.NaturalTypeOpt; convertedType = cond.Type; convertedNullability = nullability; conversion = Conversion.MakeConditionalExpression(ImmutableArray<Conversion>.Empty); } else { // There was an explicit cast on top of this. type = cond.NaturalTypeOpt; (convertedType, convertedNullability) = (type, nullability); conversion = Conversion.Identity; } } else if (highestBoundExpr != null && highestBoundExpr != boundExpr && highestBoundExpr.HasExpressionType()) { (convertedType, convertedNullability) = getTypeAndNullability(highestBoundExpr); if (highestBoundExprKind != BoundKind.Conversion) { conversion = Conversion.Identity; } else if (((BoundConversion)highestBoundExpr).Operand.Kind != BoundKind.Conversion) { conversion = highestBoundExpr.GetConversion(); if (conversion.Kind == ConversionKind.AnonymousFunction) { // See comment above: anonymous functions do not have a type type = null; nullability = default; } } else { // There is a sequence of conversions; we use ClassifyConversionFromExpression to report the most pertinent. var binder = this.GetEnclosingBinder(boundExpr.Syntax.Span.Start); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; conversion = binder.Conversions.ClassifyConversionFromExpression(boundExpr, convertedType, ref discardedUseSiteInfo); } } else if (boundNodeForSyntacticParent?.Kind == BoundKind.DelegateCreationExpression) { // A delegate creation expression takes the place of a method group or anonymous function conversion. var delegateCreation = (BoundDelegateCreationExpression)boundNodeForSyntacticParent; (convertedType, convertedNullability) = getTypeAndNullability(delegateCreation); switch (boundExpr.Kind) { case BoundKind.MethodGroup: { conversion = new Conversion(ConversionKind.MethodGroup, delegateCreation.MethodOpt, delegateCreation.IsExtensionMethod); break; } case BoundKind.Lambda: { var lambda = (BoundLambda)boundExpr; conversion = new Conversion(ConversionKind.AnonymousFunction, lambda.Symbol, delegateCreation.IsExtensionMethod); break; } case BoundKind.UnboundLambda: { var lambda = ((UnboundLambda)boundExpr).BindForErrorRecovery(); conversion = new Conversion(ConversionKind.AnonymousFunction, lambda.Symbol, delegateCreation.IsExtensionMethod); break; } default: conversion = Conversion.Identity; break; } } else if (boundExpr is BoundConversion { ConversionKind: ConversionKind.MethodGroup, Conversion: var exprConversion, Type: { TypeKind: TypeKind.FunctionPointer }, SymbolOpt: var symbol }) { // Because the method group is a separate syntax node from the &, the lowest bound node here is the BoundConversion. However, // the conversion represents an implicit method group conversion from a typeless method group to a function pointer type, so // we should reflect that in the types and conversion we return. convertedType = type; convertedNullability = nullability; conversion = exprConversion; type = null; nullability = new NullabilityInfo(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableFlowState.NotNull); } else { convertedType = type; convertedNullability = nullability; conversion = Conversion.Identity; } return new CSharpTypeInfo(type, convertedType, nullability, convertedNullability, conversion); } return CSharpTypeInfo.None; static (TypeSymbol, NullabilityInfo) getTypeAndNullability(BoundExpression expr) => (expr.Type, expr.TopLevelNullability); } // Gets the method or property group from a specific bound node. // lowestBoundNode: The lowest node in the bound tree associated with node // highestBoundNode: The highest node in the bound tree associated with node // boundNodeForSyntacticParent: The lowest node in the bound tree associated with node.Parent. internal ImmutableArray<Symbol> GetMemberGroupForNode( SymbolInfoOptions options, BoundNode lowestBoundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt) { if (lowestBoundNode is BoundExpression boundExpr) { LookupResultKind resultKind; ImmutableArray<Symbol> memberGroup; bool isDynamic; GetSemanticSymbols(boundExpr, boundNodeForSyntacticParent, binderOpt, options, out isDynamic, out resultKind, out memberGroup); return memberGroup; } return ImmutableArray<Symbol>.Empty; } // Gets the indexer group from a specific bound node. // lowestBoundNode: The lowest node in the bound tree associated with node // highestBoundNode: The highest node in the bound tree associated with node // boundNodeForSyntacticParent: The lowest node in the bound tree associated with node.Parent. internal ImmutableArray<IPropertySymbol> GetIndexerGroupForNode( BoundNode lowestBoundNode, Binder binderOpt) { var boundExpr = lowestBoundNode as BoundExpression; if (boundExpr != null && boundExpr.Kind != BoundKind.TypeExpression) { return GetIndexerGroupSemanticSymbols(boundExpr, binderOpt); } return ImmutableArray<IPropertySymbol>.Empty; } // Gets symbol info for a type or namespace or alias reference. It is assumed that any error cases will come in // as a type whose OriginalDefinition is an error symbol from which the ResultKind can be retrieved. internal static SymbolInfo GetSymbolInfoForSymbol(Symbol symbol, SymbolInfoOptions options) { Debug.Assert((object)symbol != null); // Determine type. Dig through aliases if necessary. Symbol unwrapped = UnwrapAlias(symbol); TypeSymbol type = unwrapped as TypeSymbol; // Determine symbols and resultKind. var originalErrorSymbol = (object)type != null ? type.OriginalDefinition as ErrorTypeSymbol : null; if ((object)originalErrorSymbol != null) { // Error case. var symbols = ImmutableArray<Symbol>.Empty; LookupResultKind resultKind = originalErrorSymbol.ResultKind; if (resultKind != LookupResultKind.Empty) { symbols = originalErrorSymbol.CandidateSymbols; } if ((options & SymbolInfoOptions.ResolveAliases) != 0) { symbols = UnwrapAliases(symbols); } return SymbolInfoFactory.Create(symbols, resultKind, isDynamic: false); } else { // Non-error case. Use constructor that doesn't require creation of a Symbol array. var symbolToReturn = ((options & SymbolInfoOptions.ResolveAliases) != 0) ? unwrapped : symbol; return new SymbolInfo(symbolToReturn.GetPublicSymbol(), ImmutableArray<ISymbol>.Empty, CandidateReason.None); } } // Gets TypeInfo for a type or namespace or alias reference. internal static CSharpTypeInfo GetTypeInfoForSymbol(Symbol symbol) { Debug.Assert((object)symbol != null); // Determine type. Dig through aliases if necessary. TypeSymbol type = UnwrapAlias(symbol) as TypeSymbol; // https://github.com/dotnet/roslyn/issues/35033: Examine this and make sure that we're using the correct nullabilities return new CSharpTypeInfo(type, type, default, default, Conversion.Identity); } protected static Symbol UnwrapAlias(Symbol symbol) { return symbol is AliasSymbol aliasSym ? aliasSym.Target : symbol; } protected static ImmutableArray<Symbol> UnwrapAliases(ImmutableArray<Symbol> symbols) { bool anyAliases = false; foreach (Symbol symbol in symbols) { if (symbol.Kind == SymbolKind.Alias) anyAliases = true; } if (!anyAliases) return symbols; ArrayBuilder<Symbol> builder = ArrayBuilder<Symbol>.GetInstance(); foreach (Symbol symbol in symbols) { // Caas clients don't want ErrorTypeSymbol in the symbols, but the best guess // instead. If no best guess, then nothing is returned. AddUnwrappingErrorTypes(builder, UnwrapAlias(symbol)); } return builder.ToImmutableAndFree(); } // This is used by other binding APIs to invoke the right binder API internal virtual BoundNode Bind(Binder binder, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { switch (node) { case ExpressionSyntax expression: var parent = expression.Parent; return parent.IsKind(SyntaxKind.GotoStatement) ? binder.BindLabel(expression, diagnostics) : binder.BindNamespaceOrTypeOrExpression(expression, diagnostics); case StatementSyntax statement: return binder.BindStatement(statement, diagnostics); case GlobalStatementSyntax globalStatement: BoundStatement bound = binder.BindStatement(globalStatement.Statement, diagnostics); return new BoundGlobalStatementInitializer(node, bound); } return null; } /// <summary> /// Analyze control-flow within a part of a method body. /// </summary> /// <param name="firstStatement">The first statement to be included in the analysis.</param> /// <param name="lastStatement">The last statement to be included in the analysis.</param> /// <returns>An object that can be used to obtain the result of the control flow analysis.</returns> /// <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception> public virtual ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { // Only supported on a SyntaxTreeSemanticModel. throw new NotSupportedException(); } /// <summary> /// Analyze control-flow within a part of a method body. /// </summary> /// <param name="statement">The statement to be included in the analysis.</param> /// <returns>An object that can be used to obtain the result of the control flow analysis.</returns> public virtual ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax statement) { return AnalyzeControlFlow(statement, statement); } /// <summary> /// Analyze data-flow within an expression. /// </summary> /// <param name="expression">The expression within the associated SyntaxTree to analyze.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> public virtual DataFlowAnalysis AnalyzeDataFlow(ExpressionSyntax expression) { // Only supported on a SyntaxTreeSemanticModel. throw new NotSupportedException(); } /// <summary> /// Analyze data-flow within a part of a method body. /// </summary> /// <param name="firstStatement">The first statement to be included in the analysis.</param> /// <param name="lastStatement">The last statement to be included in the analysis.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> /// <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception> public virtual DataFlowAnalysis AnalyzeDataFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { // Only supported on a SyntaxTreeSemanticModel. throw new NotSupportedException(); } /// <summary> /// Analyze data-flow within a part of a method body. /// </summary> /// <param name="statement">The statement to be included in the analysis.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> public virtual DataFlowAnalysis AnalyzeDataFlow(StatementSyntax statement) { return AnalyzeDataFlow(statement, statement); } /// <summary> /// Get a SemanticModel object that is associated with a method body that did not appear in this source code. /// Given <paramref name="position"/> must lie within an existing method body of the Root syntax node for this SemanticModel. /// Locals and labels declared within this existing method body are not considered to be in scope of the speculated method body. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel and must be /// within the FullSpan of a Method body within the Root syntax node.</param> /// <param name="method">A syntax node that represents a parsed method declaration. This method should not be /// present in the syntax tree associated with this object, but must have identical signature to the method containing /// the given <paramref name="position"/> in this SemanticModel.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="method"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="method"/> node is contained any SyntaxTree in the current Compilation</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="method"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModelForMethodBody(int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(method); return TryGetSpeculativeSemanticModelForMethodBodyCore((SyntaxTreeSemanticModel)this, position, method, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a method body that did not appear in this source code. /// Given <paramref name="position"/> must lie within an existing method body of the Root syntax node for this SemanticModel. /// Locals and labels declared within this existing method body are not considered to be in scope of the speculated method body. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel and must be /// within the FullSpan of a Method body within the Root syntax node.</param> /// <param name="accessor">A syntax node that represents a parsed accessor declaration. This accessor should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="accessor"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="accessor"/> node is contained any SyntaxTree in the current Compilation</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="accessor"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModelForMethodBody(int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(accessor); return TryGetSpeculativeSemanticModelForMethodBodyCore((SyntaxTreeSemanticModel)this, position, accessor, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a type syntax node that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a type syntax that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// </param> /// <param name="type">A syntax node that represents a parsed expression. This expression should not be /// present in the syntax tree associated with this object.</param> /// <param name="bindingOption">Indicates whether to bind the expression as a full expression, /// or as a type or namespace.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="type"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="type"/> node is contained any SyntaxTree in the current Compilation</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="type"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, TypeSyntax type, out SemanticModel speculativeModel, SpeculativeBindingOption bindingOption = SpeculativeBindingOption.BindAsExpression) { CheckModelAndSyntaxNodeToSpeculate(type); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, type, bindingOption, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a statement that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a statement that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel.</param> /// <param name="statement">A syntax node that represents a parsed statement. This statement should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="statement"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="statement"/> node is contained any SyntaxTree in the current Compilation</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="statement"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, StatementSyntax statement, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(statement); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, statement, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with an initializer that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a field initializer or default parameter value that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// </param> /// <param name="initializer">A syntax node that represents a parsed initializer. This initializer should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="initializer"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="initializer"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="initializer"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(initializer); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, initializer, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with an expression body that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of an expression body that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// </param> /// <param name="expressionBody">A syntax node that represents a parsed expression body. This node should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="expressionBody"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="expressionBody"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="expressionBody"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(expressionBody); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, expressionBody, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a constructor initializer that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a constructor initializer that did not appear in source code. /// /// NOTE: This will only work in locations where there is already a constructor initializer. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// Furthermore, it must be within the span of an existing constructor initializer. /// </param> /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. /// This node should not be present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="constructorInitializer"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="constructorInitializer"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="constructorInitializer"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(constructorInitializer); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, constructorInitializer, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a constructor initializer that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a constructor initializer that did not appear in source code. /// /// NOTE: This will only work in locations where there is already a constructor initializer. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the span of an existing constructor initializer. /// </param> /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. /// This node should not be present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="constructorInitializer"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="constructorInitializer"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="constructorInitializer"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(constructorInitializer); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, constructorInitializer, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a cref that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a cref that did not appear in source code. /// /// NOTE: This will only work in locations where there is already a cref. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// Furthermore, it must be within the span of an existing cref. /// </param> /// <param name="crefSyntax">A syntax node that represents a parsed cref syntax. /// This node should not be present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="crefSyntax"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="crefSyntax"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="crefSyntax"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(crefSyntax); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, crefSyntax, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with an attribute that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of an attribute that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel.</param> /// <param name="attribute">A syntax node that represents a parsed attribute. This attribute should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="attribute"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="attribute"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="attribute"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, AttributeSyntax attribute, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(attribute); var binder = GetSpeculativeBinderForAttribute(position, attribute); if (binder == null) { speculativeModel = null; return false; } AliasSymbol aliasOpt; var attributeType = (NamedTypeSymbol)binder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type; speculativeModel = ((SyntaxTreeSemanticModel)this).CreateSpeculativeAttributeSemanticModel(position, attribute, binder, aliasOpt, attributeType); return true; } /// <summary> /// If this is a speculative semantic model, then returns its parent semantic model. /// Otherwise, returns null. /// </summary> public new abstract CSharpSemanticModel ParentModel { get; } /// <summary> /// The SyntaxTree that this object is associated with. /// </summary> public new abstract SyntaxTree SyntaxTree { get; } /// <summary> /// Determines what type of conversion, if any, would be used if a given expression was /// converted to a given type. If isExplicitInSource is true, the conversion produced is /// that which would be used if the conversion were done for a cast expression. /// </summary> /// <param name="expression">An expression which much occur within the syntax tree /// associated with this object.</param> /// <param name="destination">The type to attempt conversion to.</param> /// <param name="isExplicitInSource">True if the conversion should be determined as for a cast expression.</param> /// <returns>Returns a Conversion object that summarizes whether the conversion was /// possible, and if so, what kind of conversion it was. If no conversion was possible, a /// Conversion object with a false "Exists" property is returned.</returns> /// <remarks>To determine the conversion between two types (instead of an expression and a /// type), use Compilation.ClassifyConversion.</remarks> public abstract Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false); /// <summary> /// Determines what type of conversion, if any, would be used if a given expression was /// converted to a given type. If isExplicitInSource is true, the conversion produced is /// that which would be used if the conversion were done for a cast expression. /// </summary> /// <param name="position">The character position for determining the enclosing declaration /// scope and accessibility.</param> /// <param name="expression">The expression to classify. This expression does not need to be /// present in the syntax tree associated with this object.</param> /// <param name="destination">The type to attempt conversion to.</param> /// <param name="isExplicitInSource">True if the conversion should be determined as for a cast expression.</param> /// <returns>Returns a Conversion object that summarizes whether the conversion was /// possible, and if so, what kind of conversion it was. If no conversion was possible, a /// Conversion object with a false "Exists" property is returned.</returns> /// <remarks>To determine the conversion between two types (instead of an expression and a /// type), use Compilation.ClassifyConversion.</remarks> public Conversion ClassifyConversion(int position, ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) { if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } TypeSymbol cdestination = destination.EnsureCSharpSymbolOrNull(nameof(destination)); if (expression.Kind() == SyntaxKind.DeclarationExpression) { // Conversion from a declaration is unspecified. return Conversion.NoConversion; } if (isExplicitInSource) { return ClassifyConversionForCast(position, expression, cdestination); } // Note that it is possible for an expression to be convertible to a type // via both an implicit user-defined conversion and an explicit built-in conversion. // In that case, this method chooses the implicit conversion. position = CheckAndAdjustPosition(position); var binder = this.GetEnclosingBinder(position); if (binder != null) { var bnode = binder.BindExpression(expression, BindingDiagnosticBag.Discarded); if (bnode != null && !cdestination.IsErrorType()) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return binder.Conversions.ClassifyConversionFromExpression(bnode, cdestination, ref discardedUseSiteInfo); } } return Conversion.NoConversion; } /// <summary> /// Determines what type of conversion, if any, would be used if a given expression was /// converted to a given type using an explicit cast. /// </summary> /// <param name="expression">An expression which much occur within the syntax tree /// associated with this object.</param> /// <param name="destination">The type to attempt conversion to.</param> /// <returns>Returns a Conversion object that summarizes whether the conversion was /// possible, and if so, what kind of conversion it was. If no conversion was possible, a /// Conversion object with a false "Exists" property is returned.</returns> /// <remarks>To determine the conversion between two types (instead of an expression and a /// type), use Compilation.ClassifyConversion.</remarks> internal abstract Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination); /// <summary> /// Determines what type of conversion, if any, would be used if a given expression was /// converted to a given type using an explicit cast. /// </summary> /// <param name="position">The character position for determining the enclosing declaration /// scope and accessibility.</param> /// <param name="expression">The expression to classify. This expression does not need to be /// present in the syntax tree associated with this object.</param> /// <param name="destination">The type to attempt conversion to.</param> /// <returns>Returns a Conversion object that summarizes whether the conversion was /// possible, and if so, what kind of conversion it was. If no conversion was possible, a /// Conversion object with a false "Exists" property is returned.</returns> /// <remarks>To determine the conversion between two types (instead of an expression and a /// type), use Compilation.ClassifyConversion.</remarks> internal Conversion ClassifyConversionForCast(int position, ExpressionSyntax expression, TypeSymbol destination) { if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } position = CheckAndAdjustPosition(position); var binder = this.GetEnclosingBinder(position); if (binder != null) { var bnode = binder.BindExpression(expression, BindingDiagnosticBag.Discarded); if (bnode != null && !destination.IsErrorType()) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return binder.Conversions.ClassifyConversionFromExpression(bnode, destination, ref discardedUseSiteInfo, forCast: true); } } return Conversion.NoConversion; } #region "GetDeclaredSymbol overloads for MemberDeclarationSyntax and its subtypes" /// <summary> /// Given a member declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for following subtypes of MemberDeclarationSyntax: /// NOTE: (1) GlobalStatementSyntax as they don't declare any symbols. /// NOTE: (2) IncompleteMemberSyntax as there are no symbols for incomplete members. /// NOTE: (3) BaseFieldDeclarationSyntax or its subtypes as these declarations can contain multiple variable declarators. /// NOTE: GetDeclaredSymbol should be called on the variable declarators directly. /// </remarks> public abstract ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a local function declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a compilation unit syntax, get the corresponding Simple Program entry point symbol. /// </summary> /// <param name="declarationSyntax">The compilation unit that declares the entry point member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a namespace declaration syntax node, get the corresponding namespace symbol for /// the declaration assembly. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a namespace.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The namespace symbol that was declared by the namespace declaration.</returns> public abstract INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a namespace declaration syntax node, get the corresponding namespace symbol for /// the declaration assembly. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a namespace.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The namespace symbol that was declared by the namespace declaration.</returns> public abstract INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a type declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a type.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseTypeDeclarationSyntax as all of them return a NamedTypeSymbol. /// </remarks> public abstract INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a delegate declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a delegate.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> public abstract INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a enum member declaration, get the corresponding field symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an enum member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a base method declaration syntax, get the corresponding method symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a method.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseMethodDeclarationSyntax as all of them return a MethodSymbol. /// </remarks> public abstract IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); #region GetDeclaredSymbol overloads for BasePropertyDeclarationSyntax and its subtypes /// <summary> /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares a property, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares an indexer, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an indexer.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares a (custom) event, get the corresponding event symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); #endregion #endregion // Anonymous types and Tuple expressions are an interesting case here because they declare their own types // // In both cases there is no distinct syntax that creates the type and the syntax that describes the type is the literal itself. // Surely - if you need to modify the anonymous type or a type of a tuple literal, you would be modifying these expressions. // // As a result we support GetDeclaredSymbol on the whole AnonymousObjectCreationExpressionSyntax/TupleExpressionSyntax. // The implementation returns the type of the expression. // // In addition to that GetDeclaredSymbol works on the AnonymousObjectMemberDeclaratorSyntax/ArgumentSyntax // The implementation returns the property/field symbol that is declared by the corresponding syntax. // // Example: // GetDeclaredSymbol => Type: (int Alice, int Bob) // _____ |__________ // [ ] // var tuple = (Alice: 1, Bob: 2); // [ ] // \GetDeclaredSymbol => Field: (int Alice, int Bob).Bob // // A special note must be made about the locations of the corresponding symbols - they refer to the actual syntax // of the literal or the anonymous type creation expression // // This way IDEs can unambiguously implement such services as "Go to definition" // // I.E. GetSymbolInfo for "Bob" in "tuple.Bob" should point to the same field as returned by GetDeclaredSymbol when applied to // the ArgumentSyntax "Bob: 2", since that is where the field was declared, where renames should be applied and so on. // // // In comparison to anonymous types, tuples have one special behavior. // It is permitted for tuple literals to not have a natural type as long as there is a target type which determines the types of the fields. // As, such for the purpose of GetDeclaredSymbol, the type symbol that is returned for tuple literals has target-typed fields, // but yet with the original names. // // GetDeclaredSymbol => Type: (string Alice, short Bob) // ________ |__________ // [ ] // (string, short) tuple = (Alice: null, Bob: 2); // [ ] // \GetDeclaredSymbol => Field: (string Alice, short Bob).Alice // // In particular, the location of the field declaration is "Alice: null" and not the "string" // the location of the type is "(Alice: null, Bob: 2)" and not the "(string, short)" // // The reason for this behavior is that, even though there might not be other references to "Alice" field in the code, // the name "Alice" itself evidently refers to something named "Alice" and should still work with // all the related APIs and services such as "Find all References", "Go to definition", "symbolic rename" etc... // // GetSymbolInfo => Field: (string Alice, short Bob).Alice // __ |__ // [ ] // (string, short) tuple = (Alice: null, Bob: 2); // /// <summary> /// Given a syntax node of anonymous object creation initializer, get the anonymous object property symbol. /// </summary> /// <param name="declaratorSyntax">The syntax node that declares a property.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node of anonymous object creation expression, get the anonymous object type symbol. /// </summary> /// <param name="declaratorSyntax">The syntax node that declares an anonymous object.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node of a tuple expression, get the tuple type symbol. /// </summary> /// <param name="declaratorSyntax">The tuple expression node.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node of an argument expression, get the declared symbol. /// </summary> /// <param name="declaratorSyntax">The argument syntax node.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// Generally ArgumentSyntax nodes do not declare symbols, except when used as arguments of a tuple literal. /// Example: var x = (Alice: 1, Bob: 2); /// ArgumentSyntax "Alice: 1" declares a tuple element field "(int Alice, int Bob).Alice" /// </remarks> public abstract ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares a property or member accessor, get the corresponding /// symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an accessor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares an expression body, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an expression body.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a variable declarator syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a variable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a variable designation syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a variable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a labeled statement syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the labeled statement.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public abstract ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a switch label syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the switch label.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public abstract ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a using declaration get the corresponding symbol for the using alias that was /// introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared.</returns> /// <remarks> /// If the using directive is an error because it attempts to introduce an alias for which an existing alias was /// previously declared in the same scope, the result is a newly-constructed AliasSymbol (i.e. not one from the /// symbol table). /// </remarks> public abstract IAliasSymbol GetDeclaredSymbol(UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given an extern alias declaration get the corresponding symbol for the alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared, or null if a duplicate alias symbol was declared.</returns> public abstract IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a parameter declaration syntax node, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a parameter.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The parameter that was declared.</returns> public abstract IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a base field declaration syntax, get the corresponding symbols. /// </summary> /// <param name="declarationSyntax">The syntax node that declares one or more fields or events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbols that were declared.</returns> internal abstract ImmutableArray<ISymbol> GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); protected ParameterSymbol GetParameterSymbol( ImmutableArray<ParameterSymbol> parameters, ParameterSyntax parameter, CancellationToken cancellationToken = default(CancellationToken)) { foreach (var symbol in parameters) { cancellationToken.ThrowIfCancellationRequested(); foreach (var location in symbol.Locations) { cancellationToken.ThrowIfCancellationRequested(); if (location.SourceTree == this.SyntaxTree && parameter.Span.Contains(location.SourceSpan)) { return symbol; } } } return null; } /// <summary> /// Given a type parameter declaration (field or method), get the corresponding symbol /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="typeParameter"></param> public abstract ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)); internal BinderFlags GetSemanticModelBinderFlags() { return this.IgnoresAccessibility ? BinderFlags.SemanticModel | BinderFlags.IgnoreAccessibility : BinderFlags.SemanticModel; } /// <summary> /// Given a foreach statement, get the symbol for the iteration variable /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="forEachStatement"></param> public ILocalSymbol GetDeclaredSymbol(ForEachStatementSyntax forEachStatement, CancellationToken cancellationToken = default(CancellationToken)) { Binder enclosingBinder = this.GetEnclosingBinder(GetAdjustedNodePosition(forEachStatement)); if (enclosingBinder == null) { return null; } Binder foreachBinder = enclosingBinder.GetBinder(forEachStatement); // Binder.GetBinder can fail in presence of syntax errors. if (foreachBinder == null) { return null; } LocalSymbol local = foreachBinder.GetDeclaredLocalsForScope(forEachStatement).FirstOrDefault(); return (local is SourceLocalSymbol { DeclarationKind: LocalDeclarationKind.ForEachIterationVariable } sourceLocal ? GetAdjustedLocalSymbol(sourceLocal) : local).GetPublicSymbol(); } /// <summary> /// Given a local symbol, gets an updated version of that local symbol adjusted for nullability analysis /// if the analysis affects the local. /// </summary> /// <param name="originalSymbol">The original symbol from initial binding.</param> /// /// <returns>The nullability-adjusted local, or the original symbol if the nullability analysis made no adjustments or was not run.</returns> internal abstract LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol originalSymbol); /// <summary> /// Given a catch declaration, get the symbol for the exception variable /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="catchDeclaration"></param> public ILocalSymbol GetDeclaredSymbol(CatchDeclarationSyntax catchDeclaration, CancellationToken cancellationToken = default(CancellationToken)) { CSharpSyntaxNode catchClause = catchDeclaration.Parent; //Syntax->Binder map is keyed on clause, not decl Debug.Assert(catchClause.Kind() == SyntaxKind.CatchClause); Binder enclosingBinder = this.GetEnclosingBinder(GetAdjustedNodePosition(catchClause)); if (enclosingBinder == null) { return null; } Binder catchBinder = enclosingBinder.GetBinder(catchClause); // Binder.GetBinder can fail in presence of syntax errors. if (catchBinder == null) { return null; } catchBinder = enclosingBinder.GetBinder(catchClause); LocalSymbol local = catchBinder.GetDeclaredLocalsForScope(catchClause).FirstOrDefault(); return ((object)local != null && local.DeclarationKind == LocalDeclarationKind.CatchVariable) ? local.GetPublicSymbol() : null; } public abstract IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax queryClause, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the query range variable declared in a join into clause. /// </summary> public abstract IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the query range variable declared in a query continuation clause. /// </summary> public abstract IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)); // Get the symbols and possible method or property group associated with a bound node, as // they should be exposed through GetSemanticInfo. // NB: It is not safe to pass a null binderOpt during speculative binding. private ImmutableArray<Symbol> GetSemanticSymbols( BoundExpression boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, SymbolInfoOptions options, out bool isDynamic, out LookupResultKind resultKind, out ImmutableArray<Symbol> memberGroup) { memberGroup = ImmutableArray<Symbol>.Empty; ImmutableArray<Symbol> symbols = ImmutableArray<Symbol>.Empty; resultKind = LookupResultKind.Viable; isDynamic = false; switch (boundNode.Kind) { case BoundKind.MethodGroup: symbols = GetMethodGroupSemanticSymbols((BoundMethodGroup)boundNode, boundNodeForSyntacticParent, binderOpt, out resultKind, out isDynamic, out memberGroup); break; case BoundKind.PropertyGroup: symbols = GetPropertyGroupSemanticSymbols((BoundPropertyGroup)boundNode, boundNodeForSyntacticParent, binderOpt, out resultKind, out memberGroup); break; case BoundKind.BadExpression: { var expr = (BoundBadExpression)boundNode; resultKind = expr.ResultKind; if (expr.Syntax.Kind() is SyntaxKind.ObjectCreationExpression or SyntaxKind.ImplicitObjectCreationExpression) { if (resultKind == LookupResultKind.NotCreatable) { return expr.Symbols; } else if (expr.Type.IsDelegateType()) { resultKind = LookupResultKind.Empty; return symbols; } memberGroup = expr.Symbols; } return expr.Symbols; } case BoundKind.DelegateCreationExpression: break; case BoundKind.TypeExpression: { var boundType = (BoundTypeExpression)boundNode; // Watch out for not creatable types within object creation syntax if (boundNodeForSyntacticParent != null && boundNodeForSyntacticParent.Syntax.Kind() == SyntaxKind.ObjectCreationExpression && ((ObjectCreationExpressionSyntax)boundNodeForSyntacticParent.Syntax).Type == boundType.Syntax && boundNodeForSyntacticParent.Kind == BoundKind.BadExpression && ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind == LookupResultKind.NotCreatable) { resultKind = LookupResultKind.NotCreatable; } // could be a type or alias. var typeSymbol = boundType.AliasOpt ?? (Symbol)boundType.Type; var originalErrorType = typeSymbol.OriginalDefinition as ErrorTypeSymbol; if ((object)originalErrorType != null) { resultKind = originalErrorType.ResultKind; symbols = originalErrorType.CandidateSymbols; } else { symbols = ImmutableArray.Create<Symbol>(typeSymbol); } } break; case BoundKind.TypeOrValueExpression: { // If we're seeing a node of this kind, then we failed to resolve the member access // as either a type or a property/field/event/local/parameter. In such cases, // the second interpretation applies so just visit the node for that. BoundExpression valueExpression = ((BoundTypeOrValueExpression)boundNode).Data.ValueExpression; return GetSemanticSymbols(valueExpression, boundNodeForSyntacticParent, binderOpt, options, out isDynamic, out resultKind, out memberGroup); } case BoundKind.Call: { // Either overload resolution succeeded for this call or it did not. If it // did not succeed then we've stashed the original method symbols from the // method group, and we should use those as the symbols displayed for the // call. If it did succeed then we did not stash any symbols; just fall // through to the default case. var call = (BoundCall)boundNode; if (call.OriginalMethodsOpt.IsDefault) { if ((object)call.Method != null) { symbols = CreateReducedExtensionMethodIfPossible(call); resultKind = call.ResultKind; } } else { symbols = StaticCast<Symbol>.From(CreateReducedExtensionMethodsFromOriginalsIfNecessary(call, Compilation)); resultKind = call.ResultKind; } } break; case BoundKind.FunctionPointerInvocation: { var invocation = (BoundFunctionPointerInvocation)boundNode; symbols = ImmutableArray.Create<Symbol>(invocation.FunctionPointer); resultKind = invocation.ResultKind; break; } case BoundKind.UnconvertedAddressOfOperator: { // We try to match the results given for a similar piece of syntax here: bad invocations. // A BoundUnconvertedAddressOfOperator represents this syntax: &M // Similarly, a BoundCall for a bad invocation represents this syntax: M(args) // Calling GetSymbolInfo on the syntax will return an array of candidate symbols that were // looked up, but calling GetMemberGroup will return an empty array. So, we ignore the member // group result in the call below. symbols = GetMethodGroupSemanticSymbols( ((BoundUnconvertedAddressOfOperator)boundNode).Operand, boundNodeForSyntacticParent, binderOpt, out resultKind, out isDynamic, methodGroup: out _); break; } case BoundKind.IndexerAccess: { // As for BoundCall, pull out stashed candidates if overload resolution failed. BoundIndexerAccess indexerAccess = (BoundIndexerAccess)boundNode; Debug.Assert((object)indexerAccess.Indexer != null); resultKind = indexerAccess.ResultKind; ImmutableArray<PropertySymbol> originalIndexersOpt = indexerAccess.OriginalIndexersOpt; symbols = originalIndexersOpt.IsDefault ? ImmutableArray.Create<Symbol>(indexerAccess.Indexer) : StaticCast<Symbol>.From(originalIndexersOpt); } break; case BoundKind.IndexOrRangePatternIndexerAccess: { var indexerAccess = (BoundIndexOrRangePatternIndexerAccess)boundNode; resultKind = indexerAccess.ResultKind; // The only time a BoundIndexOrRangePatternIndexerAccess is created, overload resolution succeeded // and returned only 1 result Debug.Assert(indexerAccess.PatternSymbol is object); symbols = ImmutableArray.Create<Symbol>(indexerAccess.PatternSymbol); } break; case BoundKind.EventAssignmentOperator: var eventAssignment = (BoundEventAssignmentOperator)boundNode; isDynamic = eventAssignment.IsDynamic; var eventSymbol = eventAssignment.Event; var methodSymbol = eventAssignment.IsAddition ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; if ((object)methodSymbol == null) { symbols = ImmutableArray<Symbol>.Empty; resultKind = LookupResultKind.Empty; } else { symbols = ImmutableArray.Create<Symbol>(methodSymbol); resultKind = eventAssignment.ResultKind; } break; case BoundKind.EventAccess when boundNodeForSyntacticParent is BoundEventAssignmentOperator { ResultKind: LookupResultKind.Viable } parentOperator && boundNode.ExpressionSymbol is Symbol accessSymbol && boundNode != parentOperator.Argument && parentOperator.Event.Equals(accessSymbol, TypeCompareKind.AllNullableIgnoreOptions): // When we're looking at the left-hand side of an event assignment, we synthesize a BoundEventAccess node. This node does not have // nullability information, however, so if we're in that case then we need to grab the event symbol from the parent event assignment // which does have the nullability-reinferred symbol symbols = ImmutableArray.Create<Symbol>(parentOperator.Event); resultKind = parentOperator.ResultKind; break; case BoundKind.Conversion: var conversion = (BoundConversion)boundNode; isDynamic = conversion.ConversionKind.IsDynamic(); if (!isDynamic) { if ((conversion.ConversionKind == ConversionKind.MethodGroup) && conversion.IsExtensionMethod) { var symbol = conversion.SymbolOpt; Debug.Assert((object)symbol != null); symbols = ImmutableArray.Create<Symbol>(ReducedExtensionMethodSymbol.Create(symbol)); resultKind = conversion.ResultKind; } else if (conversion.ConversionKind.IsUserDefinedConversion()) { GetSymbolsAndResultKind(conversion, conversion.SymbolOpt, conversion.OriginalUserDefinedConversionsOpt, out symbols, out resultKind); } else { goto default; } } break; case BoundKind.BinaryOperator: GetSymbolsAndResultKind((BoundBinaryOperator)boundNode, out isDynamic, ref resultKind, ref symbols); break; case BoundKind.UnaryOperator: GetSymbolsAndResultKind((BoundUnaryOperator)boundNode, out isDynamic, ref resultKind, ref symbols); break; case BoundKind.UserDefinedConditionalLogicalOperator: var @operator = (BoundUserDefinedConditionalLogicalOperator)boundNode; isDynamic = false; GetSymbolsAndResultKind(@operator, @operator.LogicalOperator, @operator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); break; case BoundKind.CompoundAssignmentOperator: GetSymbolsAndResultKind((BoundCompoundAssignmentOperator)boundNode, out isDynamic, ref resultKind, ref symbols); break; case BoundKind.IncrementOperator: GetSymbolsAndResultKind((BoundIncrementOperator)boundNode, out isDynamic, ref resultKind, ref symbols); break; case BoundKind.AwaitExpression: var await = (BoundAwaitExpression)boundNode; isDynamic = await.AwaitableInfo.IsDynamic; goto default; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)boundNode; Debug.Assert(conditional.ExpressionSymbol is null); isDynamic = conditional.IsDynamic; goto default; case BoundKind.Attribute: { Debug.Assert(boundNodeForSyntacticParent == null); var attribute = (BoundAttribute)boundNode; resultKind = attribute.ResultKind; // If attribute name bound to a single named type or an error type // with a single named type candidate symbol, we will return constructors // of the named type in the semantic info. // Otherwise, we will return the error type candidate symbols. var namedType = (NamedTypeSymbol)attribute.Type; if (namedType.IsErrorType()) { Debug.Assert(resultKind != LookupResultKind.Viable); var errorType = (ErrorTypeSymbol)namedType; var candidateSymbols = errorType.CandidateSymbols; // If error type has a single named type candidate symbol, we want to // use that type for symbol info. if (candidateSymbols.Length == 1 && candidateSymbols[0] is NamedTypeSymbol) { namedType = (NamedTypeSymbol)candidateSymbols[0]; } else { symbols = candidateSymbols; break; } } AdjustSymbolsForObjectCreation(attribute, namedType, attribute.Constructor, binderOpt, ref resultKind, ref symbols, ref memberGroup); } break; case BoundKind.QueryClause: { var query = (BoundQueryClause)boundNode; var builder = ArrayBuilder<Symbol>.GetInstance(); if (query.Operation != null && (object)query.Operation.ExpressionSymbol != null) builder.Add(query.Operation.ExpressionSymbol); if ((object)query.DefinedSymbol != null) builder.Add(query.DefinedSymbol); if (query.Cast != null && (object)query.Cast.ExpressionSymbol != null) builder.Add(query.Cast.ExpressionSymbol); symbols = builder.ToImmutableAndFree(); } break; case BoundKind.DynamicInvocation: var dynamicInvocation = (BoundDynamicInvocation)boundNode; Debug.Assert(dynamicInvocation.ExpressionSymbol is null); symbols = memberGroup = dynamicInvocation.ApplicableMethods.Cast<MethodSymbol, Symbol>(); isDynamic = true; break; case BoundKind.DynamicCollectionElementInitializer: var collectionInit = (BoundDynamicCollectionElementInitializer)boundNode; Debug.Assert(collectionInit.ExpressionSymbol is null); symbols = memberGroup = collectionInit.ApplicableMethods.Cast<MethodSymbol, Symbol>(); isDynamic = true; break; case BoundKind.DynamicIndexerAccess: var dynamicIndexer = (BoundDynamicIndexerAccess)boundNode; Debug.Assert(dynamicIndexer.ExpressionSymbol is null); symbols = memberGroup = dynamicIndexer.ApplicableIndexers.Cast<PropertySymbol, Symbol>(); isDynamic = true; break; case BoundKind.DynamicMemberAccess: Debug.Assert((object)boundNode.ExpressionSymbol == null); isDynamic = true; break; case BoundKind.DynamicObjectCreationExpression: var objectCreation = (BoundDynamicObjectCreationExpression)boundNode; symbols = memberGroup = objectCreation.ApplicableMethods.Cast<MethodSymbol, Symbol>(); isDynamic = true; break; case BoundKind.ObjectCreationExpression: var boundObjectCreation = (BoundObjectCreationExpression)boundNode; if ((object)boundObjectCreation.Constructor != null) { Debug.Assert(boundObjectCreation.ConstructorsGroup.Contains(boundObjectCreation.Constructor)); symbols = ImmutableArray.Create<Symbol>(boundObjectCreation.Constructor); } else if (boundObjectCreation.ConstructorsGroup.Length > 0) { symbols = StaticCast<Symbol>.From(boundObjectCreation.ConstructorsGroup); resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); } memberGroup = boundObjectCreation.ConstructorsGroup.Cast<MethodSymbol, Symbol>(); break; case BoundKind.ThisReference: case BoundKind.BaseReference: { Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); NamedTypeSymbol containingType = binder.ContainingType; var containingMember = binder.ContainingMember(); var thisParam = GetThisParameter(boundNode.Type, containingType, containingMember, out resultKind); symbols = thisParam != null ? ImmutableArray.Create<Symbol>(thisParam) : ImmutableArray<Symbol>.Empty; } break; case BoundKind.FromEndIndexExpression: { var fromEndIndexExpression = (BoundFromEndIndexExpression)boundNode; if ((object)fromEndIndexExpression.MethodOpt != null) { symbols = ImmutableArray.Create<Symbol>(fromEndIndexExpression.MethodOpt); } break; } case BoundKind.RangeExpression: { var rangeExpression = (BoundRangeExpression)boundNode; if ((object)rangeExpression.MethodOpt != null) { symbols = ImmutableArray.Create<Symbol>(rangeExpression.MethodOpt); } break; } default: { if (boundNode.ExpressionSymbol is Symbol symbol) { symbols = ImmutableArray.Create(symbol); resultKind = boundNode.ResultKind; } } break; } if (boundNodeForSyntacticParent != null && (options & SymbolInfoOptions.PreferConstructorsToType) != 0) { // Adjust symbols to get the constructors if we're T in a "new T(...)". AdjustSymbolsForObjectCreation(boundNode, boundNodeForSyntacticParent, binderOpt, ref resultKind, ref symbols, ref memberGroup); } return symbols; } private static ParameterSymbol GetThisParameter(TypeSymbol typeOfThis, NamedTypeSymbol containingType, Symbol containingMember, out LookupResultKind resultKind) { if ((object)containingMember == null || (object)containingType == null) { // not in a member of a type (can happen when speculating) resultKind = LookupResultKind.NotReferencable; return new ThisParameterSymbol(containingMember as MethodSymbol, typeOfThis); } ParameterSymbol thisParam; switch (containingMember.Kind) { case SymbolKind.Method: case SymbolKind.Field: case SymbolKind.Property: if (containingMember.IsStatic) { // in a static member resultKind = LookupResultKind.StaticInstanceMismatch; thisParam = new ThisParameterSymbol(containingMember as MethodSymbol, containingType); } else { if ((object)typeOfThis == ErrorTypeSymbol.UnknownResultType) { // in an instance member, but binder considered this/base unreferenceable thisParam = new ThisParameterSymbol(containingMember as MethodSymbol, containingType); resultKind = LookupResultKind.NotReferencable; } else { switch (containingMember.Kind) { case SymbolKind.Method: resultKind = LookupResultKind.Viable; thisParam = containingMember.EnclosingThisSymbol(); break; // Fields and properties can't access 'this' since // initializers are run in the constructor case SymbolKind.Field: case SymbolKind.Property: resultKind = LookupResultKind.NotReferencable; thisParam = containingMember.EnclosingThisSymbol() ?? new ThisParameterSymbol(null, containingType); break; default: throw ExceptionUtilities.UnexpectedValue(containingMember.Kind); } } } break; default: thisParam = new ThisParameterSymbol(containingMember as MethodSymbol, typeOfThis); resultKind = LookupResultKind.NotReferencable; break; } return thisParam; } private static void GetSymbolsAndResultKind(BoundUnaryOperator unaryOperator, out bool isDynamic, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols) { UnaryOperatorKind operandType = unaryOperator.OperatorKind.OperandTypes(); isDynamic = unaryOperator.OperatorKind.IsDynamic(); if (operandType == 0 || operandType == UnaryOperatorKind.UserDefined || unaryOperator.ResultKind != LookupResultKind.Viable) { if (!isDynamic) { GetSymbolsAndResultKind(unaryOperator, unaryOperator.MethodOpt, unaryOperator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); } } else { Debug.Assert((object)unaryOperator.MethodOpt == null && unaryOperator.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); UnaryOperatorKind op = unaryOperator.OperatorKind.Operator(); symbols = ImmutableArray.Create<Symbol>(new SynthesizedIntrinsicOperatorSymbol(unaryOperator.Operand.Type.StrippedType(), OperatorFacts.UnaryOperatorNameFromOperatorKind(op), unaryOperator.Type.StrippedType(), unaryOperator.OperatorKind.IsChecked())); resultKind = unaryOperator.ResultKind; } } private static void GetSymbolsAndResultKind(BoundIncrementOperator increment, out bool isDynamic, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols) { UnaryOperatorKind operandType = increment.OperatorKind.OperandTypes(); isDynamic = increment.OperatorKind.IsDynamic(); if (operandType == 0 || operandType == UnaryOperatorKind.UserDefined || increment.ResultKind != LookupResultKind.Viable) { if (!isDynamic) { GetSymbolsAndResultKind(increment, increment.MethodOpt, increment.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); } } else { Debug.Assert((object)increment.MethodOpt == null && increment.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); UnaryOperatorKind op = increment.OperatorKind.Operator(); symbols = ImmutableArray.Create<Symbol>(new SynthesizedIntrinsicOperatorSymbol(increment.Operand.Type.StrippedType(), OperatorFacts.UnaryOperatorNameFromOperatorKind(op), increment.Type.StrippedType(), increment.OperatorKind.IsChecked())); resultKind = increment.ResultKind; } } private static void GetSymbolsAndResultKind(BoundBinaryOperator binaryOperator, out bool isDynamic, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols) { BinaryOperatorKind operandType = binaryOperator.OperatorKind.OperandTypes(); BinaryOperatorKind op = binaryOperator.OperatorKind.Operator(); isDynamic = binaryOperator.OperatorKind.IsDynamic(); if (operandType == 0 || operandType == BinaryOperatorKind.UserDefined || binaryOperator.ResultKind != LookupResultKind.Viable || binaryOperator.OperatorKind.IsLogical()) { if (!isDynamic) { GetSymbolsAndResultKind(binaryOperator, binaryOperator.Method, binaryOperator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); } } else { Debug.Assert((object)binaryOperator.Method == null && binaryOperator.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); if (!isDynamic && (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) && ((binaryOperator.Left.IsLiteralNull() && binaryOperator.Right.Type.IsNullableType()) || (binaryOperator.Right.IsLiteralNull() && binaryOperator.Left.Type.IsNullableType())) && binaryOperator.Type.SpecialType == SpecialType.System_Boolean) { // Comparison of a nullable type with null, return corresponding operator for Object. var objectType = binaryOperator.Type.ContainingAssembly.GetSpecialType(SpecialType.System_Object); symbols = ImmutableArray.Create<Symbol>(new SynthesizedIntrinsicOperatorSymbol(objectType, OperatorFacts.BinaryOperatorNameFromOperatorKind(op), objectType, binaryOperator.Type, binaryOperator.OperatorKind.IsChecked())); } else { symbols = ImmutableArray.Create(GetIntrinsicOperatorSymbol(op, isDynamic, binaryOperator.Left.Type, binaryOperator.Right.Type, binaryOperator.Type, binaryOperator.OperatorKind.IsChecked())); } resultKind = binaryOperator.ResultKind; } } private static Symbol GetIntrinsicOperatorSymbol(BinaryOperatorKind op, bool isDynamic, TypeSymbol leftType, TypeSymbol rightType, TypeSymbol returnType, bool isChecked) { if (!isDynamic) { leftType = leftType.StrippedType(); rightType = rightType.StrippedType(); returnType = returnType.StrippedType(); } else { Debug.Assert(returnType.IsDynamic()); if ((object)leftType == null) { Debug.Assert(rightType.IsDynamic()); leftType = rightType; } else if ((object)rightType == null) { Debug.Assert(leftType.IsDynamic()); rightType = leftType; } } return new SynthesizedIntrinsicOperatorSymbol(leftType, OperatorFacts.BinaryOperatorNameFromOperatorKind(op), rightType, returnType, isChecked); } private static void GetSymbolsAndResultKind(BoundCompoundAssignmentOperator compoundAssignment, out bool isDynamic, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols) { BinaryOperatorKind operandType = compoundAssignment.Operator.Kind.OperandTypes(); BinaryOperatorKind op = compoundAssignment.Operator.Kind.Operator(); isDynamic = compoundAssignment.Operator.Kind.IsDynamic(); if (operandType == 0 || operandType == BinaryOperatorKind.UserDefined || compoundAssignment.ResultKind != LookupResultKind.Viable) { if (!isDynamic) { GetSymbolsAndResultKind(compoundAssignment, compoundAssignment.Operator.Method, compoundAssignment.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); } } else { Debug.Assert((object)compoundAssignment.Operator.Method == null && compoundAssignment.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); symbols = ImmutableArray.Create(GetIntrinsicOperatorSymbol(op, isDynamic, compoundAssignment.Operator.LeftType, compoundAssignment.Operator.RightType, compoundAssignment.Operator.ReturnType, compoundAssignment.Operator.Kind.IsChecked())); resultKind = compoundAssignment.ResultKind; } } private static void GetSymbolsAndResultKind(BoundExpression node, Symbol symbolOpt, ImmutableArray<MethodSymbol> originalCandidates, out ImmutableArray<Symbol> symbols, out LookupResultKind resultKind) { if (!ReferenceEquals(symbolOpt, null)) { symbols = ImmutableArray.Create(symbolOpt); resultKind = node.ResultKind; } else if (!originalCandidates.IsDefault) { symbols = StaticCast<Symbol>.From(originalCandidates); resultKind = node.ResultKind; } else { symbols = ImmutableArray<Symbol>.Empty; resultKind = LookupResultKind.Empty; } } // In cases where we are binding C in "[C(...)]", the bound nodes return the symbol for the type. However, we've // decided that we want this case to return the constructor of the type instead. This affects attributes. // This method checks for this situation and adjusts the syntax and method or property group. private void AdjustSymbolsForObjectCreation( BoundExpression boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols, ref ImmutableArray<Symbol> memberGroup) { NamedTypeSymbol typeSymbol = null; MethodSymbol constructor = null; // Check if boundNode.Syntax is the type-name child of an Attribute. SyntaxNode parentSyntax = boundNodeForSyntacticParent.Syntax; if (parentSyntax != null && parentSyntax == boundNode.Syntax.Parent && parentSyntax.Kind() == SyntaxKind.Attribute && ((AttributeSyntax)parentSyntax).Name == boundNode.Syntax) { var unwrappedSymbols = UnwrapAliases(symbols); switch (boundNodeForSyntacticParent.Kind) { case BoundKind.Attribute: BoundAttribute boundAttribute = (BoundAttribute)boundNodeForSyntacticParent; if (unwrappedSymbols.Length == 1 && unwrappedSymbols[0].Kind == SymbolKind.NamedType) { Debug.Assert(resultKind != LookupResultKind.Viable || TypeSymbol.Equals((TypeSymbol)unwrappedSymbols[0], boundAttribute.Type.GetNonErrorGuess(), TypeCompareKind.ConsiderEverything2)); typeSymbol = (NamedTypeSymbol)unwrappedSymbols[0]; constructor = boundAttribute.Constructor; resultKind = resultKind.WorseResultKind(boundAttribute.ResultKind); } break; case BoundKind.BadExpression: BoundBadExpression boundBadExpression = (BoundBadExpression)boundNodeForSyntacticParent; if (unwrappedSymbols.Length == 1) { resultKind = resultKind.WorseResultKind(boundBadExpression.ResultKind); typeSymbol = unwrappedSymbols[0] as NamedTypeSymbol; } break; default: throw ExceptionUtilities.UnexpectedValue(boundNodeForSyntacticParent.Kind); } AdjustSymbolsForObjectCreation(boundNode, typeSymbol, constructor, binderOpt, ref resultKind, ref symbols, ref memberGroup); } } private void AdjustSymbolsForObjectCreation( BoundNode lowestBoundNode, NamedTypeSymbol typeSymbolOpt, MethodSymbol constructorOpt, Binder binderOpt, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols, ref ImmutableArray<Symbol> memberGroup) { Debug.Assert(lowestBoundNode != null); Debug.Assert(binderOpt != null || IsInTree(lowestBoundNode.Syntax)); if ((object)typeSymbolOpt != null) { Debug.Assert(lowestBoundNode.Syntax != null); // Filter typeSymbol's instance constructors by accessibility. // If all the instance constructors are inaccessible, we retain // all of them for correct semantic info. Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(lowestBoundNode.Syntax)); ImmutableArray<MethodSymbol> candidateConstructors; if (binder != null) { var instanceConstructors = typeSymbolOpt.IsInterfaceType() && (object)typeSymbolOpt.ComImportCoClass != null ? typeSymbolOpt.ComImportCoClass.InstanceConstructors : typeSymbolOpt.InstanceConstructors; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; candidateConstructors = binder.FilterInaccessibleConstructors(instanceConstructors, allowProtectedConstructorsOfBaseType: false, useSiteInfo: ref discardedUseSiteInfo); if ((object)constructorOpt == null ? !candidateConstructors.Any() : !candidateConstructors.Contains(constructorOpt)) { // All instance constructors are inaccessible or if the specified constructor // isn't a candidate, then we retain all of them for correct semantic info. Debug.Assert(resultKind != LookupResultKind.Viable); candidateConstructors = instanceConstructors; } } else { candidateConstructors = ImmutableArray<MethodSymbol>.Empty; } if ((object)constructorOpt != null) { Debug.Assert(candidateConstructors.Contains(constructorOpt)); symbols = ImmutableArray.Create<Symbol>(constructorOpt); } else if (candidateConstructors.Length > 0) { symbols = StaticCast<Symbol>.From(candidateConstructors); Debug.Assert(resultKind != LookupResultKind.Viable); resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); } memberGroup = candidateConstructors.Cast<MethodSymbol, Symbol>(); } } /// <summary> /// Returns a list of accessible, non-hidden indexers that could be invoked with the given expression /// as a receiver. /// </summary> /// <remarks> /// If the given expression is an indexer access, then this method will return the list of indexers /// that could be invoked on the result, not the list of indexers that were considered. /// </remarks> private ImmutableArray<IPropertySymbol> GetIndexerGroupSemanticSymbols(BoundExpression boundNode, Binder binderOpt) { Debug.Assert(binderOpt != null || IsInTree(boundNode.Syntax)); TypeSymbol type = boundNode.Type; if (ReferenceEquals(type, null) || type.IsStatic) { return ImmutableArray<IPropertySymbol>.Empty; } Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); var symbols = ArrayBuilder<ISymbol>.GetInstance(); AppendSymbolsWithNameAndArity(symbols, WellKnownMemberNames.Indexer, 0, binder, type, LookupOptions.MustBeInstance); if (symbols.Count == 0) { symbols.Free(); return ImmutableArray<IPropertySymbol>.Empty; } return FilterOverriddenOrHiddenIndexers(symbols.ToImmutableAndFree()); } private static ImmutableArray<IPropertySymbol> FilterOverriddenOrHiddenIndexers(ImmutableArray<ISymbol> symbols) { PooledHashSet<Symbol> hiddenSymbols = null; foreach (ISymbol iSymbol in symbols) { Symbol symbol = iSymbol.GetSymbol(); Debug.Assert(symbol.IsIndexer(), "Only indexers can have name " + WellKnownMemberNames.Indexer); PropertySymbol indexer = (PropertySymbol)symbol; OverriddenOrHiddenMembersResult overriddenOrHiddenMembers = indexer.OverriddenOrHiddenMembers; foreach (Symbol overridden in overriddenOrHiddenMembers.OverriddenMembers) { if (hiddenSymbols == null) { hiddenSymbols = PooledHashSet<Symbol>.GetInstance(); } hiddenSymbols.Add(overridden); } // Don't worry about RuntimeOverriddenMembers - this check is for the API, which // should reflect the C# semantics. foreach (Symbol hidden in overriddenOrHiddenMembers.HiddenMembers) { if (hiddenSymbols == null) { hiddenSymbols = PooledHashSet<Symbol>.GetInstance(); } hiddenSymbols.Add(hidden); } } var builder = ArrayBuilder<IPropertySymbol>.GetInstance(); foreach (IPropertySymbol indexer in symbols) { if (hiddenSymbols == null || !hiddenSymbols.Contains(indexer.GetSymbol())) { builder.Add(indexer); } } hiddenSymbols?.Free(); return builder.ToImmutableAndFree(); } /// <remarks> /// The method group can contain "duplicate" symbols that we do not want to display in the IDE analysis. /// /// For example, there could be an overriding virtual method and the method it overrides both in /// the method group. This, strictly speaking, is a violation of the C# specification because we are /// supposed to strip out overriding methods from the method group before overload resolution; overload /// resolution is supposed to treat overridden methods as being methods of the less derived type. However, /// in the IDE we want to display information about the overriding method, not the overridden method, and /// therefore we leave both in the method group. The overload resolution algorithm has been written /// to handle this departure from the specification. /// /// Similarly, we might have two methods in the method group where one is a "new" method that hides /// another. Again, in overload resolution this would be handled by the rule that says that methods /// declared on more derived types take priority over methods declared on less derived types. Both /// will be in the method group, but in the IDE we want to only display information about the /// hiding method, not the hidden method. /// /// We can also have "diamond" inheritance of interfaces leading to multiple copies of the same /// method ending up in the method group: /// /// interface IB { void M(); } /// interface IL : IB {} /// interface IR : IB {} /// interface ID : IL, IR {} /// ... /// id.M(); /// /// We only want to display one symbol in the IDE, even if the member lookup algorithm is unsophisticated /// and puts IB.M in the member group twice. (Again, this is a mild spec violation since a method group /// is supposed to be a set, without duplicates.) /// /// Finally, the interaction of multiple inheritance of interfaces and hiding can lead to some subtle /// situations. Suppose we make a slight modification to the scenario above: /// /// interface IL : IB { new void M(); } /// /// Again, we only want to display one symbol in the method group. The fact that there is a "path" /// to IB.M from ID via IR is irrelevant; if the symbol IB.M is hidden by IL.M then it is hidden /// in ID, period. /// </remarks> private static ImmutableArray<MethodSymbol> FilterOverriddenOrHiddenMethods(ImmutableArray<MethodSymbol> methods) { // Optimization, not required for correctness. if (methods.Length <= 1) { return methods; } HashSet<Symbol> hiddenSymbols = new HashSet<Symbol>(); foreach (MethodSymbol method in methods) { OverriddenOrHiddenMembersResult overriddenOrHiddenMembers = method.OverriddenOrHiddenMembers; foreach (Symbol overridden in overriddenOrHiddenMembers.OverriddenMembers) { hiddenSymbols.Add(overridden); } // Don't worry about RuntimeOverriddenMembers - this check is for the API, which // should reflect the C# semantics. foreach (Symbol hidden in overriddenOrHiddenMembers.HiddenMembers) { hiddenSymbols.Add(hidden); } } return methods.WhereAsArray((m, hiddenSymbols) => !hiddenSymbols.Contains(m), hiddenSymbols); } // Get the symbols and possible method group associated with a method group bound node, as // they should be exposed through GetSemanticInfo. // NB: It is not safe to pass a null binderOpt during speculative binding. // // If the parent node of the method group syntax node provides information (such as arguments) // that allows us to return more specific symbols (a specific overload or applicable candidates) // we return these. The complete set of symbols of the method group is then returned in methodGroup parameter. private ImmutableArray<Symbol> GetMethodGroupSemanticSymbols( BoundMethodGroup boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, out LookupResultKind resultKind, out bool isDynamic, out ImmutableArray<Symbol> methodGroup) { Debug.Assert(binderOpt != null || IsInTree(boundNode.Syntax)); ImmutableArray<Symbol> symbols = ImmutableArray<Symbol>.Empty; resultKind = boundNode.ResultKind; if (resultKind == LookupResultKind.Empty) { resultKind = LookupResultKind.Viable; } isDynamic = false; // The method group needs filtering. Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); methodGroup = GetReducedAndFilteredMethodGroupSymbols(binder, boundNode).Cast<MethodSymbol, Symbol>(); // We want to get the actual node chosen by overload resolution, if possible. if (boundNodeForSyntacticParent != null) { switch (boundNodeForSyntacticParent.Kind) { case BoundKind.Call: // If we are looking for info on M in M(args), we want the symbol that overload resolution // chose for M. var call = (BoundCall)boundNodeForSyntacticParent; InvocationExpressionSyntax invocation = call.Syntax as InvocationExpressionSyntax; if (invocation != null && invocation.Expression.SkipParens() == ((ExpressionSyntax)boundNode.Syntax).SkipParens() && (object)call.Method != null) { if (call.OriginalMethodsOpt.IsDefault) { // Overload resolution succeeded. symbols = CreateReducedExtensionMethodIfPossible(call); resultKind = LookupResultKind.Viable; } else { resultKind = call.ResultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); symbols = StaticCast<Symbol>.From(CreateReducedExtensionMethodsFromOriginalsIfNecessary(call, Compilation)); } } break; case BoundKind.DelegateCreationExpression: // If we are looking for info on "M" in "new Action(M)" // we want to get the symbol that overload resolution chose for M, not the whole method group M. var delegateCreation = (BoundDelegateCreationExpression)boundNodeForSyntacticParent; if (delegateCreation.Argument == boundNode && (object)delegateCreation.MethodOpt != null) { symbols = CreateReducedExtensionMethodIfPossible(delegateCreation, boundNode.ReceiverOpt); } break; case BoundKind.Conversion: // If we are looking for info on "M" in "(Action)M" // we want to get the symbol that overload resolution chose for M, not the whole method group M. var conversion = (BoundConversion)boundNodeForSyntacticParent; var method = conversion.SymbolOpt; if ((object)method != null) { Debug.Assert(conversion.ConversionKind == ConversionKind.MethodGroup); if (conversion.IsExtensionMethod) { method = ReducedExtensionMethodSymbol.Create(method); } symbols = ImmutableArray.Create((Symbol)method); resultKind = conversion.ResultKind; } else { goto default; } break; case BoundKind.DynamicInvocation: var dynamicInvocation = (BoundDynamicInvocation)boundNodeForSyntacticParent; symbols = dynamicInvocation.ApplicableMethods.Cast<MethodSymbol, Symbol>(); isDynamic = true; break; case BoundKind.BadExpression: // If the bad expression has symbol(s) from this method group, it better indicates any problems. ImmutableArray<Symbol> myMethodGroup = methodGroup; symbols = ((BoundBadExpression)boundNodeForSyntacticParent).Symbols.WhereAsArray((sym, myMethodGroup) => myMethodGroup.Contains(sym), myMethodGroup); if (symbols.Any()) { resultKind = ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind; } break; case BoundKind.NameOfOperator: symbols = methodGroup; resultKind = resultKind.WorseResultKind(LookupResultKind.MemberGroup); break; default: symbols = methodGroup; if (symbols.Length > 0) { resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); } break; } } else if (methodGroup.Length == 1 && !boundNode.HasAnyErrors) { // During speculative binding, there won't be a parent bound node. The parent bound // node may also be absent if the syntactic parent has errors or if one is simply // not specified (see SemanticModel.GetSymbolInfoForNode). However, if there's exactly // one candidate, then we should probably succeed. symbols = methodGroup; if (symbols.Length > 0) { resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); } } if (!symbols.Any()) { // If we didn't find a better set of symbols, then assume this is a method group that didn't // get resolved. Return all members of the method group, with a resultKind of OverloadResolutionFailure // (unless the method group already has a worse result kind). symbols = methodGroup; if (!isDynamic && resultKind > LookupResultKind.OverloadResolutionFailure) { resultKind = LookupResultKind.OverloadResolutionFailure; } } return symbols; } // NB: It is not safe to pass a null binderOpt during speculative binding. private ImmutableArray<Symbol> GetPropertyGroupSemanticSymbols( BoundPropertyGroup boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, out LookupResultKind resultKind, out ImmutableArray<Symbol> propertyGroup) { Debug.Assert(binderOpt != null || IsInTree(boundNode.Syntax)); ImmutableArray<Symbol> symbols = ImmutableArray<Symbol>.Empty; resultKind = boundNode.ResultKind; if (resultKind == LookupResultKind.Empty) { resultKind = LookupResultKind.Viable; } // The property group needs filtering. propertyGroup = boundNode.Properties.Cast<PropertySymbol, Symbol>(); // We want to get the actual node chosen by overload resolution, if possible. if (boundNodeForSyntacticParent != null) { switch (boundNodeForSyntacticParent.Kind) { case BoundKind.IndexerAccess: // If we are looking for info on P in P[args], we want the symbol that overload resolution // chose for P. var indexer = (BoundIndexerAccess)boundNodeForSyntacticParent; var elementAccess = indexer.Syntax as ElementAccessExpressionSyntax; if (elementAccess != null && elementAccess.Expression == boundNode.Syntax && (object)indexer.Indexer != null) { if (indexer.OriginalIndexersOpt.IsDefault) { // Overload resolution succeeded. symbols = ImmutableArray.Create<Symbol>(indexer.Indexer); resultKind = LookupResultKind.Viable; } else { resultKind = indexer.ResultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); symbols = StaticCast<Symbol>.From(indexer.OriginalIndexersOpt); } } break; case BoundKind.BadExpression: // If the bad expression has symbol(s) from this property group, it better indicates any problems. ImmutableArray<Symbol> myPropertyGroup = propertyGroup; symbols = ((BoundBadExpression)boundNodeForSyntacticParent).Symbols.WhereAsArray((sym, myPropertyGroup) => myPropertyGroup.Contains(sym), myPropertyGroup); if (symbols.Any()) { resultKind = ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind; } break; } } else if (propertyGroup.Length == 1 && !boundNode.HasAnyErrors) { // During speculative binding, there won't be a parent bound node. The parent bound // node may also be absent if the syntactic parent has errors or if one is simply // not specified (see SemanticModel.GetSymbolInfoForNode). However, if there's exactly // one candidate, then we should probably succeed. // If we're speculatively binding and there's exactly one candidate, then we should probably succeed. symbols = propertyGroup; } if (!symbols.Any()) { // If we didn't find a better set of symbols, then assume this is a property group that didn't // get resolved. Return all members of the property group, with a resultKind of OverloadResolutionFailure // (unless the property group already has a worse result kind). symbols = propertyGroup; if (resultKind > LookupResultKind.OverloadResolutionFailure) { resultKind = LookupResultKind.OverloadResolutionFailure; } } return symbols; } /// <summary> /// Get the semantic info of a named argument in an invocation-like expression (e.g. `x` in `M(x: 3)`) /// or the name in a Subpattern (e.g. either `Name` in `e is (Name: 3){Name: 3}`). /// </summary> private SymbolInfo GetNamedArgumentSymbolInfo(IdentifierNameSyntax identifierNameSyntax, CancellationToken cancellationToken) { Debug.Assert(SyntaxFacts.IsNamedArgumentName(identifierNameSyntax)); // Argument names do not have bound nodes associated with them, so we cannot use the usual // GetSymbolInfo mechanism. Instead, we just do the following: // 1. Find the containing invocation. // 2. Call GetSymbolInfo on that. // 3. For each method or indexer in the return semantic info, find the argument // with the given name (if any). // 4. Use the ResultKind in that semantic info and any symbols to create the semantic info // for the named argument. // 5. Type is always null, as is constant value. string argumentName = identifierNameSyntax.Identifier.ValueText; if (argumentName.Length == 0) return SymbolInfo.None; // missing name. // argument could be an argument of a tuple expression // var x = (Identifier: 1, AnotherIdentifier: 2); var parent3 = identifierNameSyntax.Parent.Parent.Parent; if (parent3.IsKind(SyntaxKind.TupleExpression)) { var tupleArgument = (ArgumentSyntax)identifierNameSyntax.Parent.Parent; var tupleElement = GetDeclaredSymbol(tupleArgument, cancellationToken); return (object)tupleElement == null ? SymbolInfo.None : new SymbolInfo(tupleElement, ImmutableArray<ISymbol>.Empty, CandidateReason.None); } if (parent3.IsKind(SyntaxKind.PropertyPatternClause) || parent3.IsKind(SyntaxKind.PositionalPatternClause)) { return GetSymbolInfoWorker(identifierNameSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken); } CSharpSyntaxNode containingInvocation = parent3.Parent; SymbolInfo containingInvocationInfo = GetSymbolInfoWorker(containingInvocation, SymbolInfoOptions.PreferConstructorsToType | SymbolInfoOptions.ResolveAliases, cancellationToken); if ((object)containingInvocationInfo.Symbol != null) { ParameterSymbol param = FindNamedParameter(containingInvocationInfo.Symbol.GetSymbol().GetParameters(), argumentName); return (object)param == null ? SymbolInfo.None : new SymbolInfo(param.GetPublicSymbol(), ImmutableArray<ISymbol>.Empty, CandidateReason.None); } else { var symbols = ArrayBuilder<ISymbol>.GetInstance(); foreach (ISymbol invocationSym in containingInvocationInfo.CandidateSymbols) { switch (invocationSym.Kind) { case SymbolKind.Method: case SymbolKind.Property: break; // Could have parameters. default: continue; // Definitely doesn't have parameters. } ParameterSymbol param = FindNamedParameter(invocationSym.GetSymbol().GetParameters(), argumentName); if ((object)param != null) { symbols.Add(param.GetPublicSymbol()); } } if (symbols.Count == 0) { symbols.Free(); return SymbolInfo.None; } else { return new SymbolInfo(null, symbols.ToImmutableAndFree(), containingInvocationInfo.CandidateReason); } } } /// <summary> /// Find the first parameter named "argumentName". /// </summary> private static ParameterSymbol FindNamedParameter(ImmutableArray<ParameterSymbol> parameters, string argumentName) { foreach (ParameterSymbol param in parameters) { if (param.Name == argumentName) return param; } return null; } internal static ImmutableArray<MethodSymbol> GetReducedAndFilteredMethodGroupSymbols(Binder binder, BoundMethodGroup node) { var methods = ArrayBuilder<MethodSymbol>.GetInstance(); var filteredMethods = ArrayBuilder<MethodSymbol>.GetInstance(); var resultKind = LookupResultKind.Empty; var typeArguments = node.TypeArgumentsOpt; // Non-extension methods. if (node.Methods.Any()) { // This is the only place we care about overridden/hidden methods. If there aren't methods // in the method group, there's only one fallback candidate and extension methods never override // or hide instance methods or other extension methods. ImmutableArray<MethodSymbol> nonHiddenMethods = FilterOverriddenOrHiddenMethods(node.Methods); Debug.Assert(nonHiddenMethods.Any()); // Something must be hiding, so can't all be hidden. foreach (var method in nonHiddenMethods) { MergeReducedAndFilteredMethodGroupSymbol( methods, filteredMethods, new SingleLookupResult(node.ResultKind, method, node.LookupError), typeArguments, null, ref resultKind, binder.Compilation); } } else { var otherSymbol = node.LookupSymbolOpt; if (((object)otherSymbol != null) && (otherSymbol.Kind == SymbolKind.Method)) { MergeReducedAndFilteredMethodGroupSymbol( methods, filteredMethods, new SingleLookupResult(node.ResultKind, otherSymbol, node.LookupError), typeArguments, null, ref resultKind, binder.Compilation); } } var receiver = node.ReceiverOpt; var name = node.Name; // Extension methods, all scopes. if (node.SearchExtensionMethods) { Debug.Assert(receiver != null); int arity; LookupOptions options; if (typeArguments.IsDefault) { arity = 0; options = LookupOptions.AllMethodsOnArityZero; } else { arity = typeArguments.Length; options = LookupOptions.Default; } binder = binder.WithAdditionalFlags(BinderFlags.SemanticModel); foreach (var scope in new ExtensionMethodScopes(binder)) { var extensionMethods = ArrayBuilder<MethodSymbol>.GetInstance(); var otherBinder = scope.Binder; otherBinder.GetCandidateExtensionMethods(extensionMethods, name, arity, options, originalBinder: binder); foreach (var method in extensionMethods) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; MergeReducedAndFilteredMethodGroupSymbol( methods, filteredMethods, binder.CheckViability(method, arity, options, accessThroughType: null, diagnose: false, useSiteInfo: ref discardedUseSiteInfo), typeArguments, receiver.Type, ref resultKind, binder.Compilation); } extensionMethods.Free(); } } methods.Free(); return filteredMethods.ToImmutableAndFree(); } // Reduce extension methods to their reduced form, and remove: // a) Extension methods are aren't applicable to receiverType // including constraint checking. // b) Duplicate methods // c) Methods that are hidden or overridden by another method in the group. private static bool AddReducedAndFilteredMethodGroupSymbol( ArrayBuilder<MethodSymbol> methods, ArrayBuilder<MethodSymbol> filteredMethods, MethodSymbol method, ImmutableArray<TypeWithAnnotations> typeArguments, TypeSymbol receiverType, CSharpCompilation compilation) { MethodSymbol constructedMethod; if (!typeArguments.IsDefaultOrEmpty && method.Arity == typeArguments.Length) { constructedMethod = method.Construct(typeArguments); Debug.Assert((object)constructedMethod != null); } else { constructedMethod = method; } if ((object)receiverType != null) { constructedMethod = constructedMethod.ReduceExtensionMethod(receiverType, compilation); if ((object)constructedMethod == null) { return false; } } // Don't add exact duplicates. if (filteredMethods.Contains(constructedMethod)) { return false; } methods.Add(method); filteredMethods.Add(constructedMethod); return true; } private static void MergeReducedAndFilteredMethodGroupSymbol( ArrayBuilder<MethodSymbol> methods, ArrayBuilder<MethodSymbol> filteredMethods, SingleLookupResult singleResult, ImmutableArray<TypeWithAnnotations> typeArguments, TypeSymbol receiverType, ref LookupResultKind resultKind, CSharpCompilation compilation) { Debug.Assert(singleResult.Kind != LookupResultKind.Empty); Debug.Assert((object)singleResult.Symbol != null); Debug.Assert(singleResult.Symbol.Kind == SymbolKind.Method); var singleKind = singleResult.Kind; if (resultKind > singleKind) { return; } else if (resultKind < singleKind) { methods.Clear(); filteredMethods.Clear(); resultKind = LookupResultKind.Empty; } var method = (MethodSymbol)singleResult.Symbol; if (AddReducedAndFilteredMethodGroupSymbol(methods, filteredMethods, method, typeArguments, receiverType, compilation)) { Debug.Assert(methods.Count > 0); if (resultKind < singleKind) { resultKind = singleKind; } } Debug.Assert((methods.Count == 0) == (resultKind == LookupResultKind.Empty)); Debug.Assert(methods.Count == filteredMethods.Count); } /// <summary> /// If the call represents an extension method invocation with an explicit receiver, return the original /// methods as ReducedExtensionMethodSymbols. Otherwise, return the original methods unchanged. /// </summary> private static ImmutableArray<MethodSymbol> CreateReducedExtensionMethodsFromOriginalsIfNecessary(BoundCall call, CSharpCompilation compilation) { var methods = call.OriginalMethodsOpt; TypeSymbol extensionThisType = null; Debug.Assert(!methods.IsDefault); if (call.InvokedAsExtensionMethod) { // If the call was invoked as an extension method, the receiver // should be non-null and all methods should be extension methods. if (call.ReceiverOpt != null) { extensionThisType = call.ReceiverOpt.Type; } else { extensionThisType = call.Arguments[0].Type; } Debug.Assert((object)extensionThisType != null); } var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); var filteredMethodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var method in FilterOverriddenOrHiddenMethods(methods)) { AddReducedAndFilteredMethodGroupSymbol(methodBuilder, filteredMethodBuilder, method, default(ImmutableArray<TypeWithAnnotations>), extensionThisType, compilation); } methodBuilder.Free(); return filteredMethodBuilder.ToImmutableAndFree(); } /// <summary> /// If the call represents an extension method with an explicit receiver, return a /// ReducedExtensionMethodSymbol if it can be constructed. Otherwise, return the /// original call method. /// </summary> private ImmutableArray<Symbol> CreateReducedExtensionMethodIfPossible(BoundCall call) { var method = call.Method; Debug.Assert((object)method != null); if (call.InvokedAsExtensionMethod && method.IsExtensionMethod && method.MethodKind != MethodKind.ReducedExtension) { Debug.Assert(call.Arguments.Length > 0); BoundExpression receiver = call.Arguments[0]; MethodSymbol reduced = method.ReduceExtensionMethod(receiver.Type, Compilation); // If the extension method can't be applied to the receiver of the given // type, we should also return the original call method. method = reduced ?? method; } return ImmutableArray.Create<Symbol>(method); } private ImmutableArray<Symbol> CreateReducedExtensionMethodIfPossible(BoundDelegateCreationExpression delegateCreation, BoundExpression receiverOpt) { var method = delegateCreation.MethodOpt; Debug.Assert((object)method != null); if (delegateCreation.IsExtensionMethod && method.IsExtensionMethod && (receiverOpt != null)) { MethodSymbol reduced = method.ReduceExtensionMethod(receiverOpt.Type, Compilation); method = reduced ?? method; } return ImmutableArray.Create<Symbol>(method); } /// <summary> /// Gets for each statement info. /// </summary> /// <param name="node">The node.</param> public abstract ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node); /// <summary> /// Gets for each statement info. /// </summary> /// <param name="node">The node.</param> public abstract ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node); /// <summary> /// Gets deconstruction assignment info. /// </summary> /// <param name="node">The node.</param> public abstract DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node); /// <summary> /// Gets deconstruction foreach info. /// </summary> /// <param name="node">The node.</param> public abstract DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node); /// <summary> /// Gets await expression info. /// </summary> /// <param name="node">The node.</param> public abstract AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node); /// <summary> /// If the given node is within a preprocessing directive, gets the preprocessing symbol info for it. /// </summary> /// <param name="node">Preprocessing symbol identifier node.</param> public PreprocessingSymbolInfo GetPreprocessingSymbolInfo(IdentifierNameSyntax node) { CheckSyntaxNode(node); if (node.Ancestors().Any(n => SyntaxFacts.IsPreprocessorDirective(n.Kind()))) { bool isDefined = this.SyntaxTree.IsPreprocessorSymbolDefined(node.Identifier.ValueText, node.Identifier.SpanStart); return new PreprocessingSymbolInfo(new Symbols.PublicModel.PreprocessingSymbol(node.Identifier.ValueText), isDefined); } return PreprocessingSymbolInfo.None; } /// <summary> /// Options to control the internal working of GetSymbolInfoWorker. Not currently exposed /// to public clients, but could be if desired. /// </summary> [Flags] internal enum SymbolInfoOptions { /// <summary> /// When binding "C" new C(...), return the type C and do not return information about /// which constructor was bound to. Bind "new C(...)" to get information about which constructor /// was chosen. /// </summary> PreferTypeToConstructors = 0x1, /// <summary> /// When binding "C" new C(...), return the constructor of C that was bound to, if C unambiguously /// binds to a single type with at least one constructor. /// </summary> PreferConstructorsToType = 0x2, /// <summary> /// When binding a name X that was declared with a "using X=OtherTypeOrNamespace", return OtherTypeOrNamespace. /// </summary> ResolveAliases = 0x4, /// <summary> /// When binding a name X that was declared with a "using X=OtherTypeOrNamespace", return the alias symbol X. /// </summary> PreserveAliases = 0x8, // Default Options. DefaultOptions = PreferConstructorsToType | ResolveAliases } internal static void ValidateSymbolInfoOptions(SymbolInfoOptions options) { Debug.Assert(((options & SymbolInfoOptions.PreferConstructorsToType) != 0) != ((options & SymbolInfoOptions.PreferTypeToConstructors) != 0), "Options are mutually exclusive"); Debug.Assert(((options & SymbolInfoOptions.ResolveAliases) != 0) != ((options & SymbolInfoOptions.PreserveAliases) != 0), "Options are mutually exclusive"); } /// <summary> /// Given a position in the SyntaxTree for this SemanticModel returns the innermost /// NamedType that the position is considered inside of. /// </summary> public new ISymbol GetEnclosingSymbol( int position, CancellationToken cancellationToken = default(CancellationToken)) { position = CheckAndAdjustPosition(position); var binder = GetEnclosingBinder(position); return binder == null ? null : binder.ContainingMemberOrLambda.GetPublicSymbol(); } #region SemanticModel Members public sealed override string Language { get { return LanguageNames.CSharp; } } protected sealed override Compilation CompilationCore { get { return this.Compilation; } } protected sealed override SemanticModel ParentModelCore { get { return this.ParentModel; } } protected sealed override SyntaxTree SyntaxTreeCore { get { return this.SyntaxTree; } } protected sealed override SyntaxNode RootCore => this.Root; private SymbolInfo GetSymbolInfoFromNode(SyntaxNode node, CancellationToken cancellationToken) { switch (node) { case null: throw new ArgumentNullException(nameof(node)); case ExpressionSyntax expression: return this.GetSymbolInfo(expression, cancellationToken); case ConstructorInitializerSyntax initializer: return this.GetSymbolInfo(initializer, cancellationToken); case PrimaryConstructorBaseTypeSyntax initializer: return this.GetSymbolInfo(initializer, cancellationToken); case AttributeSyntax attribute: return this.GetSymbolInfo(attribute, cancellationToken); case CrefSyntax cref: return this.GetSymbolInfo(cref, cancellationToken); case SelectOrGroupClauseSyntax selectOrGroupClause: return this.GetSymbolInfo(selectOrGroupClause, cancellationToken); case OrderingSyntax orderingSyntax: return this.GetSymbolInfo(orderingSyntax, cancellationToken); case PositionalPatternClauseSyntax ppcSyntax: return this.GetSymbolInfo(ppcSyntax, cancellationToken); } return SymbolInfo.None; } private TypeInfo GetTypeInfoFromNode(SyntaxNode node, CancellationToken cancellationToken) { switch (node) { case null: throw new ArgumentNullException(nameof(node)); case ExpressionSyntax expression: return this.GetTypeInfo(expression, cancellationToken); case ConstructorInitializerSyntax initializer: return this.GetTypeInfo(initializer, cancellationToken); case AttributeSyntax attribute: return this.GetTypeInfo(attribute, cancellationToken); case SelectOrGroupClauseSyntax selectOrGroupClause: return this.GetTypeInfo(selectOrGroupClause, cancellationToken); case PatternSyntax pattern: return this.GetTypeInfo(pattern, cancellationToken); } return CSharpTypeInfo.None; } private ImmutableArray<ISymbol> GetMemberGroupFromNode(SyntaxNode node, CancellationToken cancellationToken) { switch (node) { case null: throw new ArgumentNullException(nameof(node)); case ExpressionSyntax expression: return this.GetMemberGroup(expression, cancellationToken); case ConstructorInitializerSyntax initializer: return this.GetMemberGroup(initializer, cancellationToken); case AttributeSyntax attribute: return this.GetMemberGroup(attribute, cancellationToken); } return ImmutableArray<ISymbol>.Empty; } protected sealed override ImmutableArray<ISymbol> GetMemberGroupCore(SyntaxNode node, CancellationToken cancellationToken) { var methodGroup = this.GetMemberGroupFromNode(node, cancellationToken); return StaticCast<ISymbol>.From(methodGroup); } protected sealed override SymbolInfo GetSpeculativeSymbolInfoCore(int position, SyntaxNode node, SpeculativeBindingOption bindingOption) { switch (node) { case ExpressionSyntax expression: return GetSpeculativeSymbolInfo(position, expression, bindingOption); case ConstructorInitializerSyntax initializer: return GetSpeculativeSymbolInfo(position, initializer); case PrimaryConstructorBaseTypeSyntax initializer: return GetSpeculativeSymbolInfo(position, initializer); case AttributeSyntax attribute: return GetSpeculativeSymbolInfo(position, attribute); case CrefSyntax cref: return GetSpeculativeSymbolInfo(position, cref); } return SymbolInfo.None; } protected sealed override TypeInfo GetSpeculativeTypeInfoCore(int position, SyntaxNode node, SpeculativeBindingOption bindingOption) { return node is ExpressionSyntax expression ? GetSpeculativeTypeInfo(position, expression, bindingOption) : CSharpTypeInfo.None; } protected sealed override IAliasSymbol GetSpeculativeAliasInfoCore(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption) { return nameSyntax is IdentifierNameSyntax identifier ? GetSpeculativeAliasInfo(position, identifier, bindingOption) : null; } protected sealed override SymbolInfo GetSymbolInfoCore(SyntaxNode node, CancellationToken cancellationToken) { return this.GetSymbolInfoFromNode(node, cancellationToken); } protected sealed override TypeInfo GetTypeInfoCore(SyntaxNode node, CancellationToken cancellationToken) { return this.GetTypeInfoFromNode(node, cancellationToken); } protected sealed override IAliasSymbol GetAliasInfoCore(SyntaxNode node, CancellationToken cancellationToken) { return node is IdentifierNameSyntax nameSyntax ? GetAliasInfo(nameSyntax, cancellationToken) : null; } protected sealed override PreprocessingSymbolInfo GetPreprocessingSymbolInfoCore(SyntaxNode node) { return node is IdentifierNameSyntax nameSyntax ? GetPreprocessingSymbolInfo(nameSyntax) : PreprocessingSymbolInfo.None; } protected sealed override ISymbol GetDeclaredSymbolCore(SyntaxNode node, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); switch (node) { case AccessorDeclarationSyntax accessor: return this.GetDeclaredSymbol(accessor, cancellationToken); case BaseTypeDeclarationSyntax type: return this.GetDeclaredSymbol(type, cancellationToken); case QueryClauseSyntax clause: return this.GetDeclaredSymbol(clause, cancellationToken); case MemberDeclarationSyntax member: return this.GetDeclaredSymbol(member, cancellationToken); } switch (node.Kind()) { case SyntaxKind.LocalFunctionStatement: return this.GetDeclaredSymbol((LocalFunctionStatementSyntax)node, cancellationToken); case SyntaxKind.LabeledStatement: return this.GetDeclaredSymbol((LabeledStatementSyntax)node, cancellationToken); case SyntaxKind.CaseSwitchLabel: case SyntaxKind.DefaultSwitchLabel: return this.GetDeclaredSymbol((SwitchLabelSyntax)node, cancellationToken); case SyntaxKind.AnonymousObjectCreationExpression: return this.GetDeclaredSymbol((AnonymousObjectCreationExpressionSyntax)node, cancellationToken); case SyntaxKind.AnonymousObjectMemberDeclarator: return this.GetDeclaredSymbol((AnonymousObjectMemberDeclaratorSyntax)node, cancellationToken); case SyntaxKind.TupleExpression: return this.GetDeclaredSymbol((TupleExpressionSyntax)node, cancellationToken); case SyntaxKind.Argument: return this.GetDeclaredSymbol((ArgumentSyntax)node, cancellationToken); case SyntaxKind.VariableDeclarator: return this.GetDeclaredSymbol((VariableDeclaratorSyntax)node, cancellationToken); case SyntaxKind.SingleVariableDesignation: return this.GetDeclaredSymbol((SingleVariableDesignationSyntax)node, cancellationToken); case SyntaxKind.TupleElement: return this.GetDeclaredSymbol((TupleElementSyntax)node, cancellationToken); case SyntaxKind.NamespaceDeclaration: return this.GetDeclaredSymbol((NamespaceDeclarationSyntax)node, cancellationToken); case SyntaxKind.FileScopedNamespaceDeclaration: return this.GetDeclaredSymbol((FileScopedNamespaceDeclarationSyntax)node, cancellationToken); case SyntaxKind.Parameter: return this.GetDeclaredSymbol((ParameterSyntax)node, cancellationToken); case SyntaxKind.TypeParameter: return this.GetDeclaredSymbol((TypeParameterSyntax)node, cancellationToken); case SyntaxKind.UsingDirective: var usingDirective = (UsingDirectiveSyntax)node; if (usingDirective.Alias == null) { break; } return this.GetDeclaredSymbol(usingDirective, cancellationToken); case SyntaxKind.ForEachStatement: return this.GetDeclaredSymbol((ForEachStatementSyntax)node, cancellationToken); case SyntaxKind.CatchDeclaration: return this.GetDeclaredSymbol((CatchDeclarationSyntax)node, cancellationToken); case SyntaxKind.JoinIntoClause: return this.GetDeclaredSymbol((JoinIntoClauseSyntax)node, cancellationToken); case SyntaxKind.QueryContinuation: return this.GetDeclaredSymbol((QueryContinuationSyntax)node, cancellationToken); case SyntaxKind.CompilationUnit: return this.GetDeclaredSymbol((CompilationUnitSyntax)node, cancellationToken); } return null; } /// <summary> /// Given a tuple element syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a tuple element.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public ISymbol GetDeclaredSymbol(TupleElementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Parent is TupleTypeSyntax tupleTypeSyntax) { return (GetSymbolInfo(tupleTypeSyntax, cancellationToken).Symbol.GetSymbol() as NamedTypeSymbol)?.TupleElements.ElementAtOrDefault(tupleTypeSyntax.Elements.IndexOf(declarationSyntax)).GetPublicSymbol(); } return null; } protected sealed override ImmutableArray<ISymbol> GetDeclaredSymbolsCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (declaration is BaseFieldDeclarationSyntax field) { return this.GetDeclaredSymbols(field, cancellationToken); } var symbol = GetDeclaredSymbolCore(declaration, cancellationToken); if (symbol != null) { return ImmutableArray.Create(symbol); } return ImmutableArray.Create<ISymbol>(); } internal override void ComputeDeclarationsInSpan(TextSpan span, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken) { CSharpDeclarationComputer.ComputeDeclarationsInSpan(this, span, getSymbol, builder, cancellationToken); } internal override void ComputeDeclarationsInNode(SyntaxNode node, ISymbol associatedSymbol, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken, int? levelsToCompute = null) { CSharpDeclarationComputer.ComputeDeclarationsInNode(this, associatedSymbol, node, getSymbol, builder, cancellationToken, levelsToCompute); } internal abstract override Func<SyntaxNode, bool> GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol); protected internal override SyntaxNode GetTopmostNodeForDiagnosticAnalysis(ISymbol symbol, SyntaxNode declaringSyntax) { switch (symbol.Kind) { case SymbolKind.Event: // for field-like events case SymbolKind.Field: var fieldDecl = declaringSyntax.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); if (fieldDecl != null) { return fieldDecl; } break; } return declaringSyntax; } protected sealed override ImmutableArray<ISymbol> LookupSymbolsCore(int position, INamespaceOrTypeSymbol container, string name, bool includeReducedExtensionMethods) { return LookupSymbols(position, container.EnsureCSharpSymbolOrNull(nameof(container)), name, includeReducedExtensionMethods); } protected sealed override ImmutableArray<ISymbol> LookupBaseMembersCore(int position, string name) { return LookupBaseMembers(position, name); } protected sealed override ImmutableArray<ISymbol> LookupStaticMembersCore(int position, INamespaceOrTypeSymbol container, string name) { return LookupStaticMembers(position, container.EnsureCSharpSymbolOrNull(nameof(container)), name); } protected sealed override ImmutableArray<ISymbol> LookupNamespacesAndTypesCore(int position, INamespaceOrTypeSymbol container, string name) { return LookupNamespacesAndTypes(position, container.EnsureCSharpSymbolOrNull(nameof(container)), name); } protected sealed override ImmutableArray<ISymbol> LookupLabelsCore(int position, string name) { return LookupLabels(position, name); } protected sealed override ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement) { if (firstStatement == null) { throw new ArgumentNullException(nameof(firstStatement)); } if (lastStatement == null) { throw new ArgumentNullException(nameof(lastStatement)); } if (!(firstStatement is StatementSyntax firstStatementSyntax)) { throw new ArgumentException("firstStatement is not a StatementSyntax."); } if (!(lastStatement is StatementSyntax lastStatementSyntax)) { throw new ArgumentException("firstStatement is a StatementSyntax but lastStatement isn't."); } return this.AnalyzeControlFlow(firstStatementSyntax, lastStatementSyntax); } protected sealed override ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode statement) { if (statement == null) { throw new ArgumentNullException(nameof(statement)); } if (!(statement is StatementSyntax statementSyntax)) { throw new ArgumentException("statement is not a StatementSyntax."); } return this.AnalyzeControlFlow(statementSyntax); } protected sealed override DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement) { if (firstStatement == null) { throw new ArgumentNullException(nameof(firstStatement)); } if (lastStatement == null) { throw new ArgumentNullException(nameof(lastStatement)); } if (!(firstStatement is StatementSyntax firstStatementSyntax)) { throw new ArgumentException("firstStatement is not a StatementSyntax."); } if (!(lastStatement is StatementSyntax lastStatementSyntax)) { throw new ArgumentException("lastStatement is not a StatementSyntax."); } return this.AnalyzeDataFlow(firstStatementSyntax, lastStatementSyntax); } protected sealed override DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode statementOrExpression) { switch (statementOrExpression) { case null: throw new ArgumentNullException(nameof(statementOrExpression)); case StatementSyntax statementSyntax: return this.AnalyzeDataFlow(statementSyntax); case ExpressionSyntax expressionSyntax: return this.AnalyzeDataFlow(expressionSyntax); default: throw new ArgumentException("statementOrExpression is not a StatementSyntax or an ExpressionSyntax."); } } protected sealed override Optional<object> GetConstantValueCore(SyntaxNode node, CancellationToken cancellationToken) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return node is ExpressionSyntax expression ? GetConstantValue(expression, cancellationToken) : default(Optional<object>); } protected sealed override ISymbol GetEnclosingSymbolCore(int position, CancellationToken cancellationToken) { return this.GetEnclosingSymbol(position, cancellationToken); } protected sealed override bool IsAccessibleCore(int position, ISymbol symbol) { return this.IsAccessible(position, symbol.EnsureCSharpSymbolOrNull(nameof(symbol))); } protected sealed override bool IsEventUsableAsFieldCore(int position, IEventSymbol symbol) { return this.IsEventUsableAsField(position, symbol.EnsureCSharpSymbolOrNull(nameof(symbol))); } public sealed override NullableContext GetNullableContext(int position) { var syntaxTree = (CSharpSyntaxTree)Root.SyntaxTree; NullableContextState contextState = syntaxTree.GetNullableContextState(position); var defaultState = syntaxTree.IsGeneratedCode(Compilation.Options.SyntaxTreeOptionsProvider, CancellationToken.None) ? NullableContextOptions.Disable : Compilation.Options.NullableContextOptions; NullableContext context = getFlag(contextState.AnnotationsState, defaultState.AnnotationsEnabled(), NullableContext.AnnotationsContextInherited, NullableContext.AnnotationsEnabled); context |= getFlag(contextState.WarningsState, defaultState.WarningsEnabled(), NullableContext.WarningsContextInherited, NullableContext.WarningsEnabled); return context; static NullableContext getFlag(NullableContextState.State contextState, bool defaultEnableState, NullableContext inheritedFlag, NullableContext enableFlag) => contextState switch { NullableContextState.State.Enabled => enableFlag, NullableContextState.State.Disabled => NullableContext.Disabled, _ when defaultEnableState => (inheritedFlag | enableFlag), _ => inheritedFlag, }; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Allows asking semantic questions about a tree of syntax nodes in a Compilation. Typically, /// an instance is obtained by a call to <see cref="Compilation"/>.<see /// cref="Compilation.GetSemanticModel(SyntaxTree, bool)"/>. /// </summary> /// <remarks> /// <para>An instance of <see cref="CSharpSemanticModel"/> caches local symbols and semantic /// information. Thus, it is much more efficient to use a single instance of <see /// cref="CSharpSemanticModel"/> when asking multiple questions about a syntax tree, because /// information from the first question may be reused. This also means that holding onto an /// instance of SemanticModel for a long time may keep a significant amount of memory from being /// garbage collected. /// </para> /// <para> /// When an answer is a named symbol that is reachable by traversing from the root of the symbol /// table, (that is, from an <see cref="AssemblySymbol"/> of the <see cref="Compilation"/>), /// that symbol will be returned (i.e. the returned value will be reference-equal to one /// reachable from the root of the symbol table). Symbols representing entities without names /// (e.g. array-of-int) may or may not exhibit reference equality. However, some named symbols /// (such as local variables) are not reachable from the root. These symbols are visible as /// answers to semantic questions. When the same SemanticModel object is used, the answers /// exhibit reference-equality. /// </para> /// </remarks> internal abstract class CSharpSemanticModel : SemanticModel { /// <summary> /// The compilation this object was obtained from. /// </summary> public new abstract CSharpCompilation Compilation { get; } /// <summary> /// The root node of the syntax tree that this binding is based on. /// </summary> internal new abstract CSharpSyntaxNode Root { get; } // Is this node one that could be successfully interrogated by GetSymbolInfo/GetTypeInfo/GetMemberGroup/GetConstantValue? // WARN: If isSpeculative is true, then don't look at .Parent - there might not be one. internal static bool CanGetSemanticInfo(CSharpSyntaxNode node, bool allowNamedArgumentName = false, bool isSpeculative = false) { Debug.Assert(node != null); if (!isSpeculative && IsInStructuredTriviaOtherThanCrefOrNameAttribute(node)) { return false; } switch (node.Kind()) { case SyntaxKind.CollectionInitializerExpression: case SyntaxKind.ObjectInitializerExpression: // new CollectionClass() { 1, 2, 3 } // ~~~~~~~~~~~ // OR // // new ObjectClass() { field = 1, prop = 2 } // ~~~~~~~~~~~~~~~~~~~~~~~ // CollectionInitializerExpression and ObjectInitializerExpression are not really expressions in the language sense. // We do not allow getting the semantic info for these syntax nodes. However, we do allow getting semantic info // for each of the individual initializer elements or member assignments. return false; case SyntaxKind.ComplexElementInitializerExpression: // new Collection { 1, {2, 3} } // ~~~~~~ // ComplexElementInitializerExpression are also not true expressions in the language sense, so we disallow getting the // semantic info for it. However, we may be interested in getting the semantic info for the compiler generated Add // method invoked with initializer expressions as arguments. Roslyn bug 11987 tracks this work item. return false; case SyntaxKind.IdentifierName: // The alias of a using directive is a declaration, so there is no semantic info - use GetDeclaredSymbol instead. if (!isSpeculative && node.Parent != null && node.Parent.Kind() == SyntaxKind.NameEquals && node.Parent.Parent.Kind() == SyntaxKind.UsingDirective) { return false; } goto default; case SyntaxKind.OmittedTypeArgument: case SyntaxKind.RefExpression: case SyntaxKind.RefType: // These are just placeholders and are not separately meaningful. return false; default: // If we are being asked for binding info on a "missing" syntax node // then there's no point in doing any work at all. For example, the user might // have something like "class C { [] void M() {} }". The caller might obtain // the attribute declaration syntax and then attempt to ask for type information // about the contents of the attribute. But the parser has recovered from the // missing attribute type and filled in a "missing" node in its place. There's // nothing we can do with that, so let's not allow it. if (node.IsMissing) { return false; } return (node is ExpressionSyntax && (isSpeculative || allowNamedArgumentName || !SyntaxFacts.IsNamedArgumentName(node))) || (node is ConstructorInitializerSyntax) || (node is PrimaryConstructorBaseTypeSyntax) || (node is AttributeSyntax) || (node is CrefSyntax); } } #region Abstract worker methods /// <summary> /// Gets symbol information about a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="options">Options to control behavior.</param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets symbol information about the 'Add' method corresponding to an expression syntax <paramref name="node"/> within collection initializer. /// This is the worker function that is overridden in various derived kinds of Semantic Models. It can assume that /// CheckSyntaxNode has already been called and the <paramref name="node"/> is in the right place in the syntax tree. /// </summary> internal abstract SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets type information about a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Binds the provided expression in the given context. /// </summary> /// <param name="position">The position to bind at.</param> /// <param name="expression">The expression to bind</param> /// <param name="bindingOption">How to speculatively bind the given expression. If this is <see cref="SpeculativeBindingOption.BindAsTypeOrNamespace"/> /// then the provided expression should be a <see cref="TypeSyntax"/>.</param> /// <param name="binder">The binder that was used to bind the given syntax.</param> /// <param name="crefSymbols">The symbols used in a cref. If this is not default, then the return is null.</param> /// <returns>The expression that was bound. If <paramref name="crefSymbols"/> is not default, this is null.</returns> internal abstract BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols); /// <summary> /// Gets a list of method or indexed property symbols for a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="options"></param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of indexer symbols for a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="options"></param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the constant value for a syntax node. This is overridden by various specializations of SemanticModel. /// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named /// argument nodes have been handled. /// </summary> /// <param name="node">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> internal abstract Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); #endregion Abstract worker methods #region Helpers for speculative binding internal Binder GetSpeculativeBinder(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { Debug.Assert(expression != null); position = CheckAndAdjustPosition(position); if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace) { if (!(expression is TypeSyntax)) { return null; } } Binder binder = this.GetEnclosingBinder(position); if (binder == null) { return null; } if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace && IsInTypeofExpression(position)) { // If position is within a typeof expression, GetEnclosingBinder may return a // TypeofBinder. However, this TypeofBinder will have been constructed with the // actual syntax of the typeof argument and we want to use the given syntax. // Wrap the binder in another TypeofBinder to overrule its description of where // unbound generic types are allowed. //Debug.Assert(binder is TypeofBinder); // Expectation, not requirement. binder = new TypeofBinder(expression, binder); } binder = new WithNullableContextBinder(SyntaxTree, position, binder); return new ExecutableCodeBinder(expression, binder.ContainingMemberOrLambda, binder).GetBinder(expression); } private Binder GetSpeculativeBinderForAttribute(int position, AttributeSyntax attribute) { position = CheckAndAdjustPositionForSpeculativeAttribute(position); var binder = this.GetEnclosingBinder(position); if (binder == null) { return null; } return new ExecutableCodeBinder(attribute, binder.ContainingMemberOrLambda, binder).GetBinder(attribute); } private static BoundExpression GetSpeculativelyBoundExpressionHelper(Binder binder, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { Debug.Assert(binder != null); Debug.Assert(binder.IsSemanticModelBinder); Debug.Assert(expression != null); Debug.Assert(bindingOption != SpeculativeBindingOption.BindAsTypeOrNamespace || expression is TypeSyntax); BoundExpression boundNode; if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace || binder.Flags.Includes(BinderFlags.CrefParameterOrReturnType)) { boundNode = binder.BindNamespaceOrType(expression, BindingDiagnosticBag.Discarded); } else { Debug.Assert(bindingOption == SpeculativeBindingOption.BindAsExpression); boundNode = binder.BindExpression(expression, BindingDiagnosticBag.Discarded); } return boundNode; } /// <summary> /// Bind the given expression speculatively at the given position, and return back /// the resulting bound node. May return null in some error cases. /// </summary> /// <remarks> /// Keep in sync with Binder.BindCrefParameterOrReturnType. /// </remarks> protected BoundExpression GetSpeculativelyBoundExpressionWithoutNullability(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } crefSymbols = default(ImmutableArray<Symbol>); expression = SyntaxFactory.GetStandaloneExpression(expression); binder = this.GetSpeculativeBinder(position, expression, bindingOption); if (binder == null) { return null; } if (binder.Flags.Includes(BinderFlags.CrefParameterOrReturnType)) { crefSymbols = ImmutableArray.Create<Symbol>(binder.BindType(expression, BindingDiagnosticBag.Discarded).Type); return null; } else if (binder.InCref) { if (expression.IsKind(SyntaxKind.QualifiedName)) { var qualified = (QualifiedNameSyntax)expression; var crefWrapper = SyntaxFactory.QualifiedCref(qualified.Left, SyntaxFactory.NameMemberCref(qualified.Right)); crefSymbols = BindCref(crefWrapper, binder); } else if (expression is TypeSyntax typeSyntax) { var crefWrapper = typeSyntax is PredefinedTypeSyntax ? (CrefSyntax)SyntaxFactory.TypeCref(typeSyntax) : SyntaxFactory.NameMemberCref(typeSyntax); crefSymbols = BindCref(crefWrapper, binder); } return null; } var boundNode = GetSpeculativelyBoundExpressionHelper(binder, expression, bindingOption); return boundNode; } internal static ImmutableArray<Symbol> BindCref(CrefSyntax crefSyntax, Binder binder) { Symbol unusedAmbiguityWinner; var symbols = binder.BindCref(crefSyntax, out unusedAmbiguityWinner, BindingDiagnosticBag.Discarded); return symbols; } internal SymbolInfo GetCrefSymbolInfo(int position, CrefSyntax crefSyntax, SymbolInfoOptions options, bool hasParameterList) { var binder = this.GetEnclosingBinder(position); if (binder?.InCref == true) { ImmutableArray<Symbol> symbols = BindCref(crefSyntax, binder); return GetCrefSymbolInfo(symbols, options, hasParameterList); } return SymbolInfo.None; } internal static bool HasParameterList(CrefSyntax crefSyntax) { while (crefSyntax.Kind() == SyntaxKind.QualifiedCref) { crefSyntax = ((QualifiedCrefSyntax)crefSyntax).Member; } switch (crefSyntax.Kind()) { case SyntaxKind.NameMemberCref: return ((NameMemberCrefSyntax)crefSyntax).Parameters != null; case SyntaxKind.IndexerMemberCref: return ((IndexerMemberCrefSyntax)crefSyntax).Parameters != null; case SyntaxKind.OperatorMemberCref: return ((OperatorMemberCrefSyntax)crefSyntax).Parameters != null; case SyntaxKind.ConversionOperatorMemberCref: return ((ConversionOperatorMemberCrefSyntax)crefSyntax).Parameters != null; } return false; } private static SymbolInfo GetCrefSymbolInfo(ImmutableArray<Symbol> symbols, SymbolInfoOptions options, bool hasParameterList) { switch (symbols.Length) { case 0: return SymbolInfo.None; case 1: // Might have to expand an ExtendedErrorTypeSymbol into multiple candidates. return GetSymbolInfoForSymbol(symbols[0], options); default: if ((options & SymbolInfoOptions.ResolveAliases) == SymbolInfoOptions.ResolveAliases) { symbols = UnwrapAliases(symbols); } LookupResultKind resultKind = LookupResultKind.Ambiguous; // The boundary between Ambiguous and OverloadResolutionFailure is let clear-cut for crefs. // We'll say that overload resolution failed if the syntax has a parameter list and if // all of the candidates have the same kind. SymbolKind firstCandidateKind = symbols[0].Kind; if (hasParameterList && symbols.All(s => s.Kind == firstCandidateKind)) { resultKind = LookupResultKind.OverloadResolutionFailure; } return SymbolInfoFactory.Create(symbols, resultKind, isDynamic: false); } } /// <summary> /// Bind the given attribute speculatively at the given position, and return back /// the resulting bound node. May return null in some error cases. /// </summary> private BoundAttribute GetSpeculativelyBoundAttribute(int position, AttributeSyntax attribute, out Binder binder) { if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } binder = this.GetSpeculativeBinderForAttribute(position, attribute); if (binder == null) { return null; } AliasSymbol aliasOpt; // not needed. NamedTypeSymbol attributeType = (NamedTypeSymbol)binder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type; var boundNode = new ExecutableCodeBinder(attribute, binder.ContainingMemberOrLambda, binder).BindAttribute(attribute, attributeType, BindingDiagnosticBag.Discarded); return boundNode; } // When speculatively binding an attribute, we have to use the name lookup rules for an attribute, // even if the position isn't within an attribute. For example: // class C { // class DAttribute: Attribute {} // } // // If we speculatively bind the attribute "D" with position at the beginning of "class C", it should // bind to DAttribute. // // But GetBinderForPosition won't do that; it only handles the case where position is inside an attribute. // This function adds a special case: if the position (after first adjustment) is at the exact beginning // of a type or method, the position is adjusted so the right binder is chosen to get the right things // in scope. private int CheckAndAdjustPositionForSpeculativeAttribute(int position) { position = CheckAndAdjustPosition(position); SyntaxToken token = Root.FindToken(position); if (position == 0 && position != token.SpanStart) return position; CSharpSyntaxNode node = (CSharpSyntaxNode)token.Parent; if (position == node.SpanStart) { // There are two cases where the binder chosen for a position at the beginning of a symbol // is incorrect for binding an attribute: // // For a type, the binder should be the one that is used for the interior of the type, where // the types members (and type parameters) are in scope. We adjust the position to the "{" to get // that binder. // // For a generic method, the binder should not include the type parameters. We adjust the position to // the method name to get that binder. if (node is BaseTypeDeclarationSyntax typeDecl) { // We're at the beginning of a type declaration. We want the members to be in scope for attributes, // so use the open brace token. position = typeDecl.OpenBraceToken.SpanStart; } var methodDecl = node.FirstAncestorOrSelf<MethodDeclarationSyntax>(); if (methodDecl?.SpanStart == position) { // We're at the beginning of a method declaration. We want the type parameters to NOT be in scope. position = methodDecl.Identifier.SpanStart; } } return position; } #endregion Helpers for speculative binding protected override IOperation GetOperationCore(SyntaxNode node, CancellationToken cancellationToken) { var csnode = (CSharpSyntaxNode)node; CheckSyntaxNode(csnode); return this.GetOperationWorker(csnode, cancellationToken); } internal virtual IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { return null; } #region GetSymbolInfo /// <summary> /// Gets the semantic information for an ordering clause in an orderby query clause. /// </summary> public abstract SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the semantic information associated with a select or group clause. /// </summary> public abstract SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the SymbolInfo for the Deconstruct method used for a deconstruction pattern clause, if any. /// </summary> public SymbolInfo GetSymbolInfo(PositionalPatternClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); return this.GetSymbolInfoWorker(node, SymbolInfoOptions.DefaultOptions, cancellationToken); } /// <summary> /// Returns what symbol(s), if any, the given expression syntax bound to in the program. /// /// An AliasSymbol will never be returned by this method. What the alias refers to will be /// returned instead. To get information about aliases, call GetAliasInfo. /// /// If binding the type name C in the expression "new C(...)" the actual constructor bound to /// will be returned (or all constructor if overload resolution failed). This occurs as long as C /// unambiguously binds to a single type that has a constructor. If C ambiguously binds to multiple /// types, or C binds to a static class, then type(s) are returned. /// </summary> public SymbolInfo GetSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); if (!CanGetSemanticInfo(expression, allowNamedArgumentName: true)) { return SymbolInfo.None; } else if (SyntaxFacts.IsNamedArgumentName(expression)) { // Named arguments handled in special way. return this.GetNamedArgumentSymbolInfo((IdentifierNameSyntax)expression, cancellationToken); } else if (SyntaxFacts.IsDeclarationExpressionType(expression, out DeclarationExpressionSyntax parent)) { switch (parent.Designation.Kind()) { case SyntaxKind.SingleVariableDesignation: return GetSymbolInfoFromSymbolOrNone(TypeFromVariable((SingleVariableDesignationSyntax)parent.Designation, cancellationToken).Type); case SyntaxKind.DiscardDesignation: return GetSymbolInfoFromSymbolOrNone(GetTypeInfoWorker(parent, cancellationToken).Type.GetPublicSymbol()); case SyntaxKind.ParenthesizedVariableDesignation: if (((TypeSyntax)expression).IsVar) { return SymbolInfo.None; } break; } } else if (expression is DeclarationExpressionSyntax declaration) { if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { return SymbolInfo.None; } var symbol = GetDeclaredSymbol((SingleVariableDesignationSyntax)declaration.Designation, cancellationToken); if ((object)symbol == null) { return SymbolInfo.None; } return new SymbolInfo(symbol); } return this.GetSymbolInfoWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken); } private static SymbolInfo GetSymbolInfoFromSymbolOrNone(ITypeSymbol type) { if (type?.Kind != SymbolKind.ErrorType) { return new SymbolInfo(type); } return SymbolInfo.None; } /// <summary> /// Given a variable designation (typically in the left-hand-side of a deconstruction declaration statement), /// figure out its type by looking at the declared symbol of the corresponding variable. /// </summary> private (ITypeSymbol Type, CodeAnalysis.NullableAnnotation Annotation) TypeFromVariable(SingleVariableDesignationSyntax variableDesignation, CancellationToken cancellationToken) { var variable = GetDeclaredSymbol(variableDesignation, cancellationToken); switch (variable) { case ILocalSymbol local: return (local.Type, local.NullableAnnotation); case IFieldSymbol field: return (field.Type, field.NullableAnnotation); } return default; } /// <summary> /// Returns what 'Add' method symbol(s), if any, corresponds to the given expression syntax /// within <see cref="BaseObjectCreationExpressionSyntax.Initializer"/>. /// </summary> public SymbolInfo GetCollectionInitializerSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); if (expression.Parent != null && expression.Parent.Kind() == SyntaxKind.CollectionInitializerExpression) { // Find containing object creation expression InitializerExpressionSyntax initializer = (InitializerExpressionSyntax)expression.Parent; // Skip containing object initializers while (initializer.Parent != null && initializer.Parent.Kind() == SyntaxKind.SimpleAssignmentExpression && ((AssignmentExpressionSyntax)initializer.Parent).Right == initializer && initializer.Parent.Parent != null && initializer.Parent.Parent.Kind() == SyntaxKind.ObjectInitializerExpression) { initializer = (InitializerExpressionSyntax)initializer.Parent.Parent; } if (initializer.Parent is BaseObjectCreationExpressionSyntax objectCreation && objectCreation.Initializer == initializer && CanGetSemanticInfo(objectCreation, allowNamedArgumentName: false)) { return GetCollectionInitializerSymbolInfoWorker((InitializerExpressionSyntax)expression.Parent, expression, cancellationToken); } } return SymbolInfo.None; } /// <summary> /// Returns what symbol(s), if any, the given constructor initializer syntax bound to in the program. /// </summary> /// <param name="constructorInitializer">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public SymbolInfo GetSymbolInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(constructorInitializer); return CanGetSemanticInfo(constructorInitializer) ? GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken) : SymbolInfo.None; } /// <summary> /// Returns what symbol(s), if any, the given constructor initializer syntax bound to in the program. /// </summary> /// <param name="constructorInitializer">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public SymbolInfo GetSymbolInfo(PrimaryConstructorBaseTypeSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(constructorInitializer); return CanGetSemanticInfo(constructorInitializer) ? GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken) : SymbolInfo.None; } /// <summary> /// Returns what symbol(s), if any, the given attribute syntax bound to in the program. /// </summary> /// <param name="attributeSyntax">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public SymbolInfo GetSymbolInfo(AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(attributeSyntax); return CanGetSemanticInfo(attributeSyntax) ? GetSymbolInfoWorker(attributeSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken) : SymbolInfo.None; } /// <summary> /// Gets the semantic information associated with a documentation comment cref. /// </summary> public SymbolInfo GetSymbolInfo(CrefSyntax crefSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(crefSyntax); return CanGetSemanticInfo(crefSyntax) ? GetSymbolInfoWorker(crefSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken) : SymbolInfo.None; } /// <summary> /// Binds the expression in the context of the specified location and gets symbol information. /// This method is used to get symbol information about an expression that did not actually /// appear in the source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and /// accessibility. This character position must be within the FullSpan of the Root syntax /// node in this SemanticModel. /// </param> /// <param name="expression">A syntax node that represents a parsed expression. This syntax /// node need not and typically does not appear in the source code referred to by the /// SemanticModel instance.</param> /// <param name="bindingOption">Indicates whether to binding the expression as a full expressions, /// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then /// expression should derive from TypeSyntax.</param> /// <returns>The symbol information for the topmost node of the expression.</returns> /// <remarks> /// The passed in expression is interpreted as a stand-alone expression, as if it /// appeared by itself somewhere within the scope that encloses "position". /// /// <paramref name="bindingOption"/> is ignored if <paramref name="position"/> is within a documentation /// comment cref attribute value. /// </remarks> public SymbolInfo GetSpeculativeSymbolInfo(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { if (!CanGetSemanticInfo(expression, isSpeculative: true)) return SymbolInfo.None; Binder binder; ImmutableArray<Symbol> crefSymbols; BoundNode boundNode = GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); //calls CheckAndAdjustPosition Debug.Assert(boundNode == null || crefSymbols.IsDefault); if (boundNode == null) { return crefSymbols.IsDefault ? SymbolInfo.None : GetCrefSymbolInfo(crefSymbols, SymbolInfoOptions.DefaultOptions, hasParameterList: false); } var symbolInfo = this.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundNode, boundNode, boundNodeForSyntacticParent: null, binderOpt: binder); return symbolInfo; } /// <summary> /// Bind the attribute in the context of the specified location and get semantic information /// such as type, symbols and diagnostics. This method is used to get semantic information about an attribute /// that did not actually appear in the source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. In order to obtain /// the correct scoping rules for the attribute, position should be the Start position of the Span of the symbol that /// the attribute is being applied to. /// </param> /// <param name="attribute">A syntax node that represents a parsed attribute. This syntax node /// need not and typically does not appear in the source code referred to SemanticModel instance.</param> /// <returns>The semantic information for the topmost node of the attribute.</returns> public SymbolInfo GetSpeculativeSymbolInfo(int position, AttributeSyntax attribute) { Debug.Assert(CanGetSemanticInfo(attribute, isSpeculative: true)); Binder binder; BoundNode boundNode = GetSpeculativelyBoundAttribute(position, attribute, out binder); //calls CheckAndAdjustPosition if (boundNode == null) return SymbolInfo.None; var symbolInfo = this.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundNode, boundNode, boundNodeForSyntacticParent: null, binderOpt: binder); return symbolInfo; } /// <summary> /// Bind the constructor initializer in the context of the specified location and get semantic information /// such as type, symbols and diagnostics. This method is used to get semantic information about a constructor /// initializer that did not actually appear in the source code. /// /// NOTE: This will only work in locations where there is already a constructor initializer. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// Furthermore, it must be within the span of an existing constructor initializer. /// </param> /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. This syntax node /// need not and typically does not appear in the source code referred to SemanticModel instance.</param> /// <returns>The semantic information for the topmost node of the constructor initializer.</returns> public SymbolInfo GetSpeculativeSymbolInfo(int position, ConstructorInitializerSyntax constructorInitializer) { Debug.Assert(CanGetSemanticInfo(constructorInitializer, isSpeculative: true)); position = CheckAndAdjustPosition(position); if (constructorInitializer == null) { throw new ArgumentNullException(nameof(constructorInitializer)); } // NOTE: since we're going to be depending on a MemberModel to do the binding for us, // we need to find a constructor initializer in the tree of this semantic model. // NOTE: This approach will not allow speculative binding of a constructor initializer // on a constructor that didn't formerly have one. // TODO: Should we support positions that are not in existing constructor initializers? // If so, we will need to build up the context that would otherwise be built up by // InitializerMemberModel. var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<ConstructorInitializerSyntax>().FirstOrDefault(); if (existingConstructorInitializer == null) { return SymbolInfo.None; } MemberSemanticModel memberModel = GetMemberModel(existingConstructorInitializer); if (memberModel == null) { return SymbolInfo.None; } var binder = memberModel.GetEnclosingBinder(position); if (binder != null) { binder = new ExecutableCodeBinder(constructorInitializer, binder.ContainingMemberOrLambda, binder); BoundExpressionStatement bnode = binder.BindConstructorInitializer(constructorInitializer, BindingDiagnosticBag.Discarded); var binfo = GetSymbolInfoFromBoundConstructorInitializer(memberModel, binder, bnode); return binfo; } else { return SymbolInfo.None; } } private static SymbolInfo GetSymbolInfoFromBoundConstructorInitializer(MemberSemanticModel memberModel, Binder binder, BoundExpressionStatement bnode) { BoundExpression expression = bnode.Expression; while (expression is BoundSequence sequence) { expression = sequence.Value; } return memberModel.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, expression, expression, boundNodeForSyntacticParent: null, binderOpt: binder); } /// <summary> /// Bind the constructor initializer in the context of the specified location and get semantic information /// about symbols. This method is used to get semantic information about a constructor /// initializer that did not actually appear in the source code. /// /// NOTE: This will only work in locations where there is already a constructor initializer. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the span of an existing constructor initializer. /// </param> /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. This syntax node /// need not and typically does not appear in the source code referred to SemanticModel instance.</param> /// <returns>The semantic information for the topmost node of the constructor initializer.</returns> public SymbolInfo GetSpeculativeSymbolInfo(int position, PrimaryConstructorBaseTypeSyntax constructorInitializer) { Debug.Assert(CanGetSemanticInfo(constructorInitializer, isSpeculative: true)); position = CheckAndAdjustPosition(position); if (constructorInitializer == null) { throw new ArgumentNullException(nameof(constructorInitializer)); } // NOTE: since we're going to be depending on a MemberModel to do the binding for us, // we need to find a constructor initializer in the tree of this semantic model. // NOTE: This approach will not allow speculative binding of a constructor initializer // on a constructor that didn't formerly have one. // TODO: Should we support positions that are not in existing constructor initializers? // If so, we will need to build up the context that would otherwise be built up by // InitializerMemberModel. var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<PrimaryConstructorBaseTypeSyntax>().FirstOrDefault(); if (existingConstructorInitializer == null) { return SymbolInfo.None; } MemberSemanticModel memberModel = GetMemberModel(existingConstructorInitializer); if (memberModel == null) { return SymbolInfo.None; } var argumentList = existingConstructorInitializer.ArgumentList; var binder = memberModel.GetEnclosingBinder(LookupPosition.IsBetweenTokens(position, argumentList.OpenParenToken, argumentList.CloseParenToken) ? position : argumentList.OpenParenToken.SpanStart); if (binder != null) { binder = new ExecutableCodeBinder(constructorInitializer, binder.ContainingMemberOrLambda, binder); BoundExpressionStatement bnode = binder.BindConstructorInitializer(constructorInitializer, BindingDiagnosticBag.Discarded); SymbolInfo binfo = GetSymbolInfoFromBoundConstructorInitializer(memberModel, binder, bnode); return binfo; } else { return SymbolInfo.None; } } /// <summary> /// Bind the cref in the context of the specified location and get semantic information /// such as type, symbols and diagnostics. This method is used to get semantic information about a cref /// that did not actually appear in the source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. In order to obtain /// the correct scoping rules for the cref, position should be the Start position of the Span of the original cref. /// </param> /// <param name="cref">A syntax node that represents a parsed cref. This syntax node /// need not and typically does not appear in the source code referred to SemanticModel instance.</param> /// <param name="options">SymbolInfo options.</param> /// <returns>The semantic information for the topmost node of the cref.</returns> public SymbolInfo GetSpeculativeSymbolInfo(int position, CrefSyntax cref, SymbolInfoOptions options = SymbolInfoOptions.DefaultOptions) { Debug.Assert(CanGetSemanticInfo(cref, isSpeculative: true)); position = CheckAndAdjustPosition(position); return this.GetCrefSymbolInfo(position, cref, options, HasParameterList(cref)); } #endregion GetSymbolInfo #region GetTypeInfo /// <summary> /// Gets type information about a constructor initializer. /// </summary> /// <param name="constructorInitializer">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public TypeInfo GetTypeInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(constructorInitializer); return CanGetSemanticInfo(constructorInitializer) ? GetTypeInfoWorker(constructorInitializer, cancellationToken) : CSharpTypeInfo.None; } public abstract TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); public TypeInfo GetTypeInfo(PatternSyntax pattern, CancellationToken cancellationToken = default(CancellationToken)) { while (pattern is ParenthesizedPatternSyntax pp) pattern = pp.Pattern; CheckSyntaxNode(pattern); return GetTypeInfoWorker(pattern, cancellationToken); } /// <summary> /// Gets type information about an expression. /// </summary> /// <param name="expression">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public TypeInfo GetTypeInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); if (!CanGetSemanticInfo(expression)) { return CSharpTypeInfo.None; } else if (SyntaxFacts.IsDeclarationExpressionType(expression, out DeclarationExpressionSyntax parent)) { switch (parent.Designation.Kind()) { case SyntaxKind.SingleVariableDesignation: var (declarationType, annotation) = ((ITypeSymbol, CodeAnalysis.NullableAnnotation))TypeFromVariable((SingleVariableDesignationSyntax)parent.Designation, cancellationToken); var declarationTypeSymbol = declarationType.GetSymbol(); var nullabilityInfo = annotation.ToNullabilityInfo(declarationTypeSymbol); return new CSharpTypeInfo(declarationTypeSymbol, declarationTypeSymbol, nullabilityInfo, nullabilityInfo, Conversion.Identity); case SyntaxKind.DiscardDesignation: var declarationInfo = GetTypeInfoWorker(parent, cancellationToken); return new CSharpTypeInfo(declarationInfo.Type, declarationInfo.Type, declarationInfo.Nullability, declarationInfo.Nullability, Conversion.Identity); case SyntaxKind.ParenthesizedVariableDesignation: if (((TypeSyntax)expression).IsVar) { return CSharpTypeInfo.None; } break; } } return GetTypeInfoWorker(expression, cancellationToken); } /// <summary> /// Gets type information about an attribute. /// </summary> /// <param name="attributeSyntax">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public TypeInfo GetTypeInfo(AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(attributeSyntax); return CanGetSemanticInfo(attributeSyntax) ? GetTypeInfoWorker(attributeSyntax, cancellationToken) : CSharpTypeInfo.None; } /// <summary> /// Gets the conversion that occurred between the expression's type and type implied by the expression's context. /// </summary> public Conversion GetConversion(SyntaxNode expression, CancellationToken cancellationToken = default(CancellationToken)) { var csnode = (CSharpSyntaxNode)expression; CheckSyntaxNode(csnode); var info = CanGetSemanticInfo(csnode) ? GetTypeInfoWorker(csnode, cancellationToken) : CSharpTypeInfo.None; return info.ImplicitConversion; } /// <summary> /// Binds the expression in the context of the specified location and gets type information. /// This method is used to get type information about an expression that did not actually /// appear in the source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and /// accessibility. This character position must be within the FullSpan of the Root syntax /// node in this SemanticModel. /// </param> /// <param name="expression">A syntax node that represents a parsed expression. This syntax /// node need not and typically does not appear in the source code referred to by the /// SemanticModel instance.</param> /// <param name="bindingOption">Indicates whether to binding the expression as a full expressions, /// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then /// expression should derive from TypeSyntax.</param> /// <returns>The type information for the topmost node of the expression.</returns> /// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it /// appeared by itself somewhere within the scope that encloses "position".</remarks> public TypeInfo GetSpeculativeTypeInfo(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { return GetSpeculativeTypeInfoWorker(position, expression, bindingOption); } internal CSharpTypeInfo GetSpeculativeTypeInfoWorker(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { if (!CanGetSemanticInfo(expression, isSpeculative: true)) { return CSharpTypeInfo.None; } ImmutableArray<Symbol> crefSymbols; BoundNode boundNode = GetSpeculativelyBoundExpression(position, expression, bindingOption, out _, out crefSymbols); //calls CheckAndAdjustPosition Debug.Assert(boundNode == null || crefSymbols.IsDefault); if (boundNode == null) { return !crefSymbols.IsDefault && crefSymbols.Length == 1 ? GetTypeInfoForSymbol(crefSymbols[0]) : CSharpTypeInfo.None; } var typeInfo = GetTypeInfoForNode(boundNode, boundNode, boundNodeForSyntacticParent: null); return typeInfo; } /// <summary> /// Gets the conversion that occurred between the expression's type and type implied by the expression's context. /// </summary> public Conversion GetSpeculativeConversion(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) { var info = this.GetSpeculativeTypeInfoWorker(position, expression, bindingOption); return info.ImplicitConversion; } #endregion GetTypeInfo #region GetMemberGroup /// <summary> /// Gets a list of method or indexed property symbols for a syntax node. /// </summary> /// <param name="expression">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public ImmutableArray<ISymbol> GetMemberGroup(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); return CanGetSemanticInfo(expression) ? this.GetMemberGroupWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols() : ImmutableArray<ISymbol>.Empty; } /// <summary> /// Gets a list of method or indexed property symbols for a syntax node. /// </summary> /// <param name="attribute">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public ImmutableArray<ISymbol> GetMemberGroup(AttributeSyntax attribute, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(attribute); return CanGetSemanticInfo(attribute) ? this.GetMemberGroupWorker(attribute, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols() : ImmutableArray<ISymbol>.Empty; } /// <summary> /// Gets a list of method symbols for a syntax node. /// </summary> /// <param name="initializer">The syntax node to get semantic information for.</param> /// <param name="cancellationToken">The cancellation token.</param> public ImmutableArray<ISymbol> GetMemberGroup(ConstructorInitializerSyntax initializer, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(initializer); return CanGetSemanticInfo(initializer) ? this.GetMemberGroupWorker(initializer, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols() : ImmutableArray<ISymbol>.Empty; } #endregion GetMemberGroup #region GetIndexerGroup /// <summary> /// Returns the list of accessible, non-hidden indexers that could be invoked with the given expression as receiver. /// </summary> /// <param name="expression">Potential indexer receiver.</param> /// <param name="cancellationToken">To cancel the computation.</param> /// <returns>Accessible, non-hidden indexers.</returns> /// <remarks> /// If the receiver is an indexer expression, the list will contain the indexers that could be applied to the result /// of accessing the indexer, not the set of candidates that were considered during construction of the indexer expression. /// </remarks> public ImmutableArray<IPropertySymbol> GetIndexerGroup(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); return CanGetSemanticInfo(expression) ? this.GetIndexerGroupWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken) : ImmutableArray<IPropertySymbol>.Empty; } #endregion GetIndexerGroup #region GetConstantValue public Optional<object> GetConstantValue(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(expression); return CanGetSemanticInfo(expression) ? this.GetConstantValueWorker(expression, cancellationToken) : default(Optional<object>); } #endregion GetConstantValue /// <summary> /// Gets the semantic information associated with a query clause. /// </summary> public abstract QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// If <paramref name="nameSyntax"/> resolves to an alias name, return the AliasSymbol corresponding /// to A. Otherwise return null. /// </summary> public IAliasSymbol GetAliasInfo(IdentifierNameSyntax nameSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(nameSyntax); if (!CanGetSemanticInfo(nameSyntax)) return null; SymbolInfo info = GetSymbolInfoWorker(nameSyntax, SymbolInfoOptions.PreferTypeToConstructors | SymbolInfoOptions.PreserveAliases, cancellationToken); return info.Symbol as IAliasSymbol; } /// <summary> /// Binds the name in the context of the specified location and sees if it resolves to an /// alias name. If it does, return the AliasSymbol corresponding to it. Otherwise, return null. /// </summary> /// <param name="position">A character position used to identify a declaration scope and /// accessibility. This character position must be within the FullSpan of the Root syntax /// node in this SemanticModel. /// </param> /// <param name="nameSyntax">A syntax node that represents a name. This syntax /// node need not and typically does not appear in the source code referred to by the /// SemanticModel instance.</param> /// <param name="bindingOption">Indicates whether to binding the name as a full expression, /// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then /// expression should derive from TypeSyntax.</param> /// <remarks>The passed in name is interpreted as a stand-alone name, as if it /// appeared by itself somewhere within the scope that encloses "position".</remarks> public IAliasSymbol GetSpeculativeAliasInfo(int position, IdentifierNameSyntax nameSyntax, SpeculativeBindingOption bindingOption) { Binder binder; ImmutableArray<Symbol> crefSymbols; BoundNode boundNode = GetSpeculativelyBoundExpression(position, nameSyntax, bindingOption, out binder, out crefSymbols); //calls CheckAndAdjustPosition Debug.Assert(boundNode == null || crefSymbols.IsDefault); if (boundNode == null) { return !crefSymbols.IsDefault && crefSymbols.Length == 1 ? (crefSymbols[0] as AliasSymbol).GetPublicSymbol() : null; } var symbolInfo = this.GetSymbolInfoForNode(SymbolInfoOptions.PreferTypeToConstructors | SymbolInfoOptions.PreserveAliases, boundNode, boundNode, boundNodeForSyntacticParent: null, binderOpt: binder); return symbolInfo.Symbol as IAliasSymbol; } /// <summary> /// Gets the binder that encloses the position. /// </summary> internal Binder GetEnclosingBinder(int position) { Binder result = GetEnclosingBinderInternal(position); Debug.Assert(result == null || result.IsSemanticModelBinder); return result; } internal abstract Binder GetEnclosingBinderInternal(int position); /// <summary> /// Gets the MemberSemanticModel that contains the node. /// </summary> internal abstract MemberSemanticModel GetMemberModel(SyntaxNode node); internal bool IsInTree(SyntaxNode node) { return node.SyntaxTree == this.SyntaxTree; } private static bool IsInStructuredTriviaOtherThanCrefOrNameAttribute(CSharpSyntaxNode node) { while (node != null) { if (node.Kind() == SyntaxKind.XmlCrefAttribute || node.Kind() == SyntaxKind.XmlNameAttribute) { return false; } else if (node.IsStructuredTrivia) { return true; } else { node = node.ParentOrStructuredTriviaParent; } } return false; } /// <summary> /// Given a position, locates the containing token. If the position is actually within the /// leading trivia of the containing token or if that token is EOF, moves one token to the /// left. Returns the start position of the resulting token. /// /// This has the effect of moving the position left until it hits the beginning of a non-EOF /// token. /// /// Throws an ArgumentOutOfRangeException if position is not within the root of this model. /// </summary> protected int CheckAndAdjustPosition(int position) { SyntaxToken unused; return CheckAndAdjustPosition(position, out unused); } protected int CheckAndAdjustPosition(int position, out SyntaxToken token) { int fullStart = this.Root.Position; int fullEnd = this.Root.FullSpan.End; bool atEOF = position == fullEnd && position == this.SyntaxTree.GetRoot().FullSpan.End; if ((fullStart <= position && position < fullEnd) || atEOF) // allow for EOF { token = (atEOF ? (CSharpSyntaxNode)this.SyntaxTree.GetRoot() : Root).FindTokenIncludingCrefAndNameAttributes(position); if (position < token.SpanStart) // NB: Span, not FullSpan { // If this is already the first token, then the result will be default(SyntaxToken) token = token.GetPreviousToken(); } // If the first token in the root is missing, it's possible to step backwards // past the start of the root. All sorts of bad things will happen in that case, // so just use the start of the root span. // CONSIDER: this should only happen when we step past the first token found, so // the start of that token would be another possible return value. return Math.Max(token.SpanStart, fullStart); } else if (fullStart == fullEnd && position == fullEnd) { // The root is an empty span and isn't the full compilation unit. No other choice here. token = default(SyntaxToken); return fullStart; } throw new ArgumentOutOfRangeException(nameof(position), position, string.Format(CSharpResources.PositionIsNotWithinSyntax, Root.FullSpan)); } /// <summary> /// A convenience method that determines a position from a node. If the node is missing, /// then its position will be adjusted using CheckAndAdjustPosition. /// </summary> protected int GetAdjustedNodePosition(SyntaxNode node) { Debug.Assert(IsInTree(node)); var fullSpan = this.Root.FullSpan; var position = node.SpanStart; // skip zero-width tokens to get the position, but never get past the end of the node SyntaxToken firstToken = node.GetFirstToken(includeZeroWidth: false); if (firstToken.Node is object) { int betterPosition = firstToken.SpanStart; if (betterPosition < node.Span.End) { position = betterPosition; } } if (fullSpan.IsEmpty) { Debug.Assert(position == fullSpan.Start); // At end of zero-width full span. No need to call // CheckAndAdjustPosition since that will simply // return the original position. return position; } else if (position == fullSpan.End) { Debug.Assert(node.Width == 0); // For zero-width node at the end of the full span, // check and adjust the preceding position. return CheckAndAdjustPosition(position - 1); } else if (node.IsMissing || node.HasErrors || node.Width == 0 || node.IsPartOfStructuredTrivia()) { return CheckAndAdjustPosition(position); } else { // No need to adjust position. return position; } } [Conditional("DEBUG")] protected void AssertPositionAdjusted(int position) { Debug.Assert(position == CheckAndAdjustPosition(position), "Expected adjusted position"); } protected void CheckSyntaxNode(CSharpSyntaxNode syntax) { if (syntax == null) { throw new ArgumentNullException(nameof(syntax)); } if (!IsInTree(syntax)) { throw new ArgumentException(CSharpResources.SyntaxNodeIsNotWithinSynt); } } // This method ensures that the given syntax node to speculate is non-null and doesn't belong to a SyntaxTree of any model in the chain. private void CheckModelAndSyntaxNodeToSpeculate(CSharpSyntaxNode syntax) { if (syntax == null) { throw new ArgumentNullException(nameof(syntax)); } if (this.IsSpeculativeSemanticModel) { throw new InvalidOperationException(CSharpResources.ChainingSpeculativeModelIsNotSupported); } if (this.Compilation.ContainsSyntaxTree(syntax.SyntaxTree)) { throw new ArgumentException(CSharpResources.SpeculatedSyntaxNodeCannotBelongToCurrentCompilation); } } /// <summary> /// Gets the available named symbols in the context of the specified location and optional container. Only /// symbols that are accessible and visible from the given location are returned. /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="container">The container to search for symbols within. If null then the enclosing declaration /// scope around position is used.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <param name="includeReducedExtensionMethods">Consider (reduced) extension methods.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if "container" is /// specified, the "position" location is significant for determining which members of "containing" are /// accessible. /// /// Labels are not considered (see <see cref="LookupLabels"/>). /// /// Non-reduced extension methods are considered regardless of the value of <paramref name="includeReducedExtensionMethods"/>. /// </remarks> public ImmutableArray<ISymbol> LookupSymbols( int position, NamespaceOrTypeSymbol container = null, string name = null, bool includeReducedExtensionMethods = false) { var options = includeReducedExtensionMethods ? LookupOptions.IncludeExtensionMethods : LookupOptions.Default; return LookupSymbolsInternal(position, container, name, options, useBaseReferenceAccessibility: false); } /// <summary> /// Gets the available base type members in the context of the specified location. Akin to /// calling <see cref="LookupSymbols"/> with the container set to the immediate base type of /// the type in which <paramref name="position"/> occurs. However, the accessibility rules /// are different: protected members of the base type will be visible. /// /// Consider the following example: /// /// public class Base /// { /// protected void M() { } /// } /// /// public class Derived : Base /// { /// void Test(Base b) /// { /// b.M(); // Error - cannot access protected member. /// base.M(); /// } /// } /// /// Protected members of an instance of another type are only accessible if the instance is known /// to be "this" instance (as indicated by the "base" keyword). /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. /// /// Non-reduced extension methods are considered, but reduced extension methods are not. /// </remarks> public new ImmutableArray<ISymbol> LookupBaseMembers( int position, string name = null) { return LookupSymbolsInternal(position, container: null, name: name, options: LookupOptions.Default, useBaseReferenceAccessibility: true); } /// <summary> /// Gets the available named static member symbols in the context of the specified location and optional container. /// Only members that are accessible and visible from the given location are returned. /// /// Non-reduced extension methods are considered, since they are static methods. /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="container">The container to search for symbols within. If null then the enclosing declaration /// scope around position is used.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if "container" is /// specified, the "position" location is significant for determining which members of "containing" are /// accessible. /// </remarks> public ImmutableArray<ISymbol> LookupStaticMembers( int position, NamespaceOrTypeSymbol container = null, string name = null) { return LookupSymbolsInternal(position, container, name, LookupOptions.MustNotBeInstance, useBaseReferenceAccessibility: false); } /// <summary> /// Gets the available named namespace and type symbols in the context of the specified location and optional container. /// Only members that are accessible and visible from the given location are returned. /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="container">The container to search for symbols within. If null then the enclosing declaration /// scope around position is used.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if "container" is /// specified, the "position" location is significant for determining which members of "containing" are /// accessible. /// /// Does not return NamespaceOrTypeSymbol, because there could be aliases. /// </remarks> public ImmutableArray<ISymbol> LookupNamespacesAndTypes( int position, NamespaceOrTypeSymbol container = null, string name = null) { return LookupSymbolsInternal(position, container, name, LookupOptions.NamespacesOrTypesOnly, useBaseReferenceAccessibility: false); } /// <summary> /// Gets the available named label symbols in the context of the specified location and optional container. /// Only members that are accessible and visible from the given location are returned. /// </summary> /// <param name="position">The character position for determining the enclosing declaration scope and /// accessibility.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if "container" is /// specified, the "position" location is significant for determining which members of "containing" are /// accessible. /// </remarks> public new ImmutableArray<ISymbol> LookupLabels( int position, string name = null) { return LookupSymbolsInternal(position, container: null, name: name, options: LookupOptions.LabelsOnly, useBaseReferenceAccessibility: false); } /// <summary> /// Gets the available named symbols in the context of the specified location and optional /// container. Only symbols that are accessible and visible from the given location are /// returned. /// </summary> /// <param name="position">The character position for determining the enclosing declaration /// scope and accessibility.</param> /// <param name="container">The container to search for symbols within. If null then the /// enclosing declaration scope around position is used.</param> /// <param name="name">The name of the symbol to find. If null is specified then symbols /// with any names are returned.</param> /// <param name="options">Additional options that affect the lookup process.</param> /// <param name="useBaseReferenceAccessibility">Ignore 'throughType' in accessibility checking. /// Used in checking accessibility of symbols accessed via 'MyBase' or 'base'.</param> /// <remarks> /// The "position" is used to determine what variables are visible and accessible. Even if /// "container" is specified, the "position" location is significant for determining which /// members of "containing" are accessible. /// </remarks> /// <exception cref="ArgumentException">Throws an argument exception if the passed lookup options are invalid.</exception> private ImmutableArray<ISymbol> LookupSymbolsInternal( int position, NamespaceOrTypeSymbol container, string name, LookupOptions options, bool useBaseReferenceAccessibility) { Debug.Assert((options & LookupOptions.UseBaseReferenceAccessibility) == 0, "Use the useBaseReferenceAccessibility parameter."); if (useBaseReferenceAccessibility) { options |= LookupOptions.UseBaseReferenceAccessibility; } Debug.Assert(!options.IsAttributeTypeLookup()); // Not exposed publicly. options.ThrowIfInvalid(); SyntaxToken token; position = CheckAndAdjustPosition(position, out token); if ((object)container == null || container.Kind == SymbolKind.Namespace) { options &= ~LookupOptions.IncludeExtensionMethods; } var binder = GetEnclosingBinder(position); if (binder == null) { return ImmutableArray<ISymbol>.Empty; } if (useBaseReferenceAccessibility) { Debug.Assert((object)container == null); TypeSymbol containingType = binder.ContainingType; TypeSymbol baseType = null; // For a script class or a submission class base should have no members. if ((object)containingType != null && containingType.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)containingType).IsScriptClass) { return ImmutableArray<ISymbol>.Empty; } if ((object)containingType == null || (object)(baseType = containingType.BaseTypeNoUseSiteDiagnostics) == null) { throw new ArgumentException( "Not a valid position for a call to LookupBaseMembers (must be in a type with a base type)", nameof(position)); } container = baseType; } if (!binder.IsInMethodBody && (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0) { // Method type parameters are not in scope outside a method // body unless the position is either: // a) in a type-only context inside an expression, or // b) inside of an XML name attribute in an XML doc comment. var parentExpr = token.Parent as ExpressionSyntax; if (parentExpr != null && !(parentExpr.Parent is XmlNameAttributeSyntax) && !SyntaxFacts.IsInTypeOnlyContext(parentExpr)) { options |= LookupOptions.MustNotBeMethodTypeParameter; } } var info = LookupSymbolsInfo.GetInstance(); info.FilterName = name; if ((object)container == null) { binder.AddLookupSymbolsInfo(info, options); } else { binder.AddMemberLookupSymbolsInfo(info, container, options, binder); } var results = ArrayBuilder<ISymbol>.GetInstance(info.Count); if (name == null) { // If they didn't provide a name, then look up all names and associated arities // and find all the corresponding symbols. foreach (string foundName in info.Names) { AppendSymbolsWithName(results, foundName, binder, container, options, info); } } else { // They provided a name. Find all the arities for that name, and then look all of those up. AppendSymbolsWithName(results, name, binder, container, options, info); } info.Free(); if ((options & LookupOptions.IncludeExtensionMethods) != 0) { var lookupResult = LookupResult.GetInstance(); options |= LookupOptions.AllMethodsOnArityZero; options &= ~LookupOptions.MustBeInstance; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; binder.LookupExtensionMethods(lookupResult, name, 0, options, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { TypeSymbol containingType = (TypeSymbol)container; foreach (MethodSymbol extensionMethod in lookupResult.Symbols) { var reduced = extensionMethod.ReduceExtensionMethod(containingType, Compilation); if ((object)reduced != null) { results.Add(reduced.GetPublicSymbol()); } } } lookupResult.Free(); } ImmutableArray<ISymbol> sealedResults = results.ToImmutableAndFree(); return name == null ? FilterNotReferencable(sealedResults) : sealedResults; } private void AppendSymbolsWithName(ArrayBuilder<ISymbol> results, string name, Binder binder, NamespaceOrTypeSymbol container, LookupOptions options, LookupSymbolsInfo info) { LookupSymbolsInfo.IArityEnumerable arities; Symbol uniqueSymbol; if (info.TryGetAritiesAndUniqueSymbol(name, out arities, out uniqueSymbol)) { if ((object)uniqueSymbol != null) { // This name mapped to something unique. We don't need to proceed // with a costly lookup. Just add it straight to the results. results.Add(RemapSymbolIfNecessary(uniqueSymbol).GetPublicSymbol()); } else { // The name maps to multiple symbols. Actually do a real lookup so // that we will properly figure out hiding and whatnot. if (arities != null) { foreach (var arity in arities) { this.AppendSymbolsWithNameAndArity(results, name, arity, binder, container, options); } } else { //non-unique symbol with non-zero arity doesn't seem possible. this.AppendSymbolsWithNameAndArity(results, name, 0, binder, container, options); } } } } private void AppendSymbolsWithNameAndArity( ArrayBuilder<ISymbol> results, string name, int arity, Binder binder, NamespaceOrTypeSymbol container, LookupOptions options) { Debug.Assert(results != null); // Don't need to de-dup since AllMethodsOnArityZero can't be set at this point (not exposed in CommonLookupOptions). Debug.Assert((options & LookupOptions.AllMethodsOnArityZero) == 0); var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; binder.LookupSymbolsSimpleName( lookupResult, container, name, arity, basesBeingResolved: null, options: options & ~LookupOptions.IncludeExtensionMethods, diagnose: false, useSiteInfo: ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { if (lookupResult.Symbols.Any(t => t.Kind == SymbolKind.NamedType || t.Kind == SymbolKind.Namespace || t.Kind == SymbolKind.ErrorType)) { // binder.ResultSymbol is defined only for type/namespace lookups bool wasError; Symbol singleSymbol = binder.ResultSymbol(lookupResult, name, arity, this.Root, BindingDiagnosticBag.Discarded, true, out wasError, container, options); if (!wasError) { results.Add(RemapSymbolIfNecessary(singleSymbol).GetPublicSymbol()); } else { foreach (var symbol in lookupResult.Symbols) { results.Add(RemapSymbolIfNecessary(symbol).GetPublicSymbol()); } } } else { foreach (var symbol in lookupResult.Symbols) { results.Add(RemapSymbolIfNecessary(symbol).GetPublicSymbol()); } } } lookupResult.Free(); } private Symbol RemapSymbolIfNecessary(Symbol symbol) { switch (symbol) { case LocalSymbol _: case ParameterSymbol _: case MethodSymbol { MethodKind: MethodKind.LambdaMethod }: return RemapSymbolIfNecessaryCore(symbol); default: return symbol; } } /// <summary> /// Remaps a local, parameter, localfunction, or lambda symbol, if that symbol or its containing /// symbols were reinferred. This should only be called when nullable semantic analysis is enabled. /// </summary> internal abstract Symbol RemapSymbolIfNecessaryCore(Symbol symbol); private static ImmutableArray<ISymbol> FilterNotReferencable(ImmutableArray<ISymbol> sealedResults) { ArrayBuilder<ISymbol> builder = null; int pos = 0; foreach (var result in sealedResults) { if (result.CanBeReferencedByName) { builder?.Add(result); } else if (builder == null) { builder = ArrayBuilder<ISymbol>.GetInstance(); builder.AddRange(sealedResults, pos); } pos++; } return builder?.ToImmutableAndFree() ?? sealedResults; } /// <summary> /// Determines if the symbol is accessible from the specified location. /// </summary> /// <param name="position">A character position used to identify a declaration scope and /// accessibility. This character position must be within the FullSpan of the Root syntax /// node in this SemanticModel. /// </param> /// <param name="symbol">The symbol that we are checking to see if it accessible.</param> /// <returns> /// True if "symbol is accessible, false otherwise.</returns> /// <remarks> /// This method only checks accessibility from the point of view of the accessibility /// modifiers on symbol and its containing types. Even if true is returned, the given symbol /// may not be able to be referenced for other reasons, such as name hiding. /// </remarks> public bool IsAccessible(int position, Symbol symbol) { position = CheckAndAdjustPosition(position); if ((object)symbol == null) { throw new ArgumentNullException(nameof(symbol)); } var binder = this.GetEnclosingBinder(position); if (binder != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return binder.IsAccessible(symbol, ref discardedUseSiteInfo, null); } return false; } /// <summary> /// Field-like events can be used as fields in types that can access private /// members of the declaring type of the event. /// </summary> public bool IsEventUsableAsField(int position, EventSymbol symbol) { return symbol is object && symbol.HasAssociatedField && this.IsAccessible(position, symbol.AssociatedField); //calls CheckAndAdjustPosition } private bool IsInTypeofExpression(int position) { var token = this.Root.FindToken(position); var curr = token.Parent; while (curr != this.Root) { if (curr.IsKind(SyntaxKind.TypeOfExpression)) { return true; } curr = curr.ParentOrStructuredTriviaParent; } return false; } // Gets the semantic info from a specific bound node and a set of diagnostics // lowestBoundNode: The lowest node in the bound tree associated with node // highestBoundNode: The highest node in the bound tree associated with node // boundNodeForSyntacticParent: The lowest node in the bound tree associated with node.Parent. // binderOpt: If this is null, then the one enclosing the bound node's syntax will be used (unsafe during speculative binding). [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Provide " + nameof(ArrayBuilder<Symbol>) + " capacity to reduce number of allocations.")] internal SymbolInfo GetSymbolInfoForNode( SymbolInfoOptions options, BoundNode lowestBoundNode, BoundNode highestBoundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt) { BoundExpression boundExpr; switch (highestBoundNode) { case BoundRecursivePattern pat: return GetSymbolInfoForDeconstruction(pat); } switch (lowestBoundNode) { case BoundPositionalSubpattern subpattern: return GetSymbolInfoForSubpattern(subpattern.Symbol); case BoundPropertySubpattern subpattern: return GetSymbolInfoForSubpattern(subpattern.Member?.Symbol); case BoundPropertySubpatternMember subpatternMember: return GetSymbolInfoForSubpattern(subpatternMember.Symbol); case BoundExpression boundExpr2: boundExpr = boundExpr2; break; default: return SymbolInfo.None; } // TODO: Should parenthesized expression really not have symbols? At least for C#, I'm not sure that // is right. For example, C# allows the assignment statement: // (i) = 9; // So we don't think this code should special case parenthesized expressions. // Get symbols and result kind from the lowest and highest nodes associated with the // syntax node. ImmutableArray<Symbol> symbols = GetSemanticSymbols( boundExpr, boundNodeForSyntacticParent, binderOpt, options, out bool isDynamic, out LookupResultKind resultKind, out ImmutableArray<Symbol> unusedMemberGroup); if (highestBoundNode is BoundExpression highestBoundExpr) { LookupResultKind highestResultKind; bool highestIsDynamic; ImmutableArray<Symbol> unusedHighestMemberGroup; ImmutableArray<Symbol> highestSymbols = GetSemanticSymbols( highestBoundExpr, boundNodeForSyntacticParent, binderOpt, options, out highestIsDynamic, out highestResultKind, out unusedHighestMemberGroup); if ((symbols.Length != 1 || resultKind == LookupResultKind.OverloadResolutionFailure) && highestSymbols.Length > 0) { symbols = highestSymbols; resultKind = highestResultKind; isDynamic = highestIsDynamic; } else if (highestResultKind != LookupResultKind.Empty && highestResultKind < resultKind) { resultKind = highestResultKind; isDynamic = highestIsDynamic; } else if (highestBoundExpr.Kind == BoundKind.TypeOrValueExpression) { symbols = highestSymbols; resultKind = highestResultKind; isDynamic = highestIsDynamic; } else if (highestBoundExpr.Kind == BoundKind.UnaryOperator) { if (IsUserDefinedTrueOrFalse((BoundUnaryOperator)highestBoundExpr)) { symbols = highestSymbols; resultKind = highestResultKind; isDynamic = highestIsDynamic; } else { Debug.Assert(ReferenceEquals(lowestBoundNode, highestBoundNode), "How is it that this operator has the same syntax node as its operand?"); } } } if (resultKind == LookupResultKind.Empty) { // Empty typically indicates an error symbol that was created because no real // symbol actually existed. return SymbolInfoFactory.Create(ImmutableArray<Symbol>.Empty, LookupResultKind.Empty, isDynamic); } else { // Caas clients don't want ErrorTypeSymbol in the symbols, but the best guess // instead. If no best guess, then nothing is returned. var builder = ArrayBuilder<Symbol>.GetInstance(symbols.Length); foreach (Symbol symbol in symbols) { AddUnwrappingErrorTypes(builder, symbol); } symbols = builder.ToImmutableAndFree(); } if ((options & SymbolInfoOptions.ResolveAliases) != 0) { symbols = UnwrapAliases(symbols); } if (resultKind == LookupResultKind.Viable && symbols.Length > 1) { resultKind = LookupResultKind.OverloadResolutionFailure; } return SymbolInfoFactory.Create(symbols, resultKind, isDynamic); } private static SymbolInfo GetSymbolInfoForSubpattern(Symbol subpatternSymbol) { if (subpatternSymbol?.OriginalDefinition is ErrorTypeSymbol originalErrorType) { return new SymbolInfo(symbol: null, originalErrorType.CandidateSymbols.GetPublicSymbols(), originalErrorType.ResultKind.ToCandidateReason()); } return new SymbolInfo(subpatternSymbol.GetPublicSymbol(), CandidateReason.None); } private SymbolInfo GetSymbolInfoForDeconstruction(BoundRecursivePattern pat) { return new SymbolInfo(pat.DeconstructMethod.GetPublicSymbol(), CandidateReason.None); } private static void AddUnwrappingErrorTypes(ArrayBuilder<Symbol> builder, Symbol s) { var originalErrorSymbol = s.OriginalDefinition as ErrorTypeSymbol; if ((object)originalErrorSymbol != null) { builder.AddRange(originalErrorSymbol.CandidateSymbols); } else { builder.Add(s); } } private static bool IsUserDefinedTrueOrFalse(BoundUnaryOperator @operator) { UnaryOperatorKind operatorKind = @operator.OperatorKind; return operatorKind == UnaryOperatorKind.UserDefinedTrue || operatorKind == UnaryOperatorKind.UserDefinedFalse; } // Gets the semantic info from a specific bound node and a set of diagnostics // lowestBoundNode: The lowest node in the bound tree associated with node // highestBoundNode: The highest node in the bound tree associated with node // boundNodeForSyntacticParent: The lowest node in the bound tree associated with node.Parent. internal CSharpTypeInfo GetTypeInfoForNode( BoundNode lowestBoundNode, BoundNode highestBoundNode, BoundNode boundNodeForSyntacticParent) { BoundPattern pattern = lowestBoundNode as BoundPattern ?? highestBoundNode as BoundPattern ?? (highestBoundNode is BoundSubpattern sp ? sp.Pattern : null); if (pattern != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // https://github.com/dotnet/roslyn/issues/35032: support patterns return new CSharpTypeInfo( pattern.InputType, pattern.NarrowedType, nullability: default, convertedNullability: default, Compilation.Conversions.ClassifyBuiltInConversion(pattern.InputType, pattern.NarrowedType, ref discardedUseSiteInfo)); } if (lowestBoundNode is BoundPropertySubpatternMember member) { return new CSharpTypeInfo(member.Type, member.Type, nullability: default, convertedNullability: default, Conversion.Identity); } var boundExpr = lowestBoundNode as BoundExpression; var highestBoundExpr = highestBoundNode as BoundExpression; if (boundExpr != null && !(boundNodeForSyntacticParent != null && boundNodeForSyntacticParent.Syntax.Kind() == SyntaxKind.ObjectCreationExpression && ((ObjectCreationExpressionSyntax)boundNodeForSyntacticParent.Syntax).Type == boundExpr.Syntax)) // Do not return any type information for a ObjectCreationExpressionSyntax.Type node. { // TODO: Should parenthesized expression really not have symbols? At least for C#, I'm not sure that // is right. For example, C# allows the assignment statement: // (i) = 9; // So I don't assume this code should special case parenthesized expressions. TypeSymbol type = null; NullabilityInfo nullability = boundExpr.TopLevelNullability; if (boundExpr.HasExpressionType()) { type = boundExpr.Type; switch (boundExpr) { case BoundLocal local: { // Use of local before declaration requires some additional fixup. // Due to complications around implicit locals and type inference, we do not // try to obtain a type of a local when it is used before declaration, we use // a special error type symbol. However, semantic model should return the same // type information for usage of a local before and after its declaration. // We will detect the use before declaration cases and replace the error type // symbol with the one obtained from the local. It should be safe to get the type // from the local at this point. if (type is ExtendedErrorTypeSymbol extended && extended.VariableUsedBeforeDeclaration) { type = local.LocalSymbol.Type; nullability = local.LocalSymbol.TypeWithAnnotations.NullableAnnotation.ToNullabilityInfo(type); } break; } case BoundConvertedTupleLiteral { SourceTuple: BoundTupleLiteral original }: { // The bound tree fully binds tuple literals. From the language point of // view, however, converted tuple literals represent tuple conversions // from tuple literal expressions which may or may not have types type = original.Type; break; } } } // we match highestBoundExpr.Kind to various kind frequently, so cache it here. // use NoOp kind for the case when highestBoundExpr == null - NoOp will not match anything below. var highestBoundExprKind = highestBoundExpr?.Kind ?? BoundKind.NoOpStatement; TypeSymbol convertedType; NullabilityInfo convertedNullability; Conversion conversion; if (highestBoundExprKind == BoundKind.Lambda) // the enclosing conversion is explicit { var lambda = (BoundLambda)highestBoundExpr; convertedType = lambda.Type; // The bound tree always fully binds lambda and anonymous functions. From the language point of // view, however, anonymous functions converted to a real delegate type should only have a // ConvertedType, not a Type. So set Type to null here. Otherwise you get the edge case where both // Type and ConvertedType are the same, but the conversion isn't Identity. type = null; nullability = default; convertedNullability = new NullabilityInfo(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableFlowState.NotNull); conversion = new Conversion(ConversionKind.AnonymousFunction, lambda.Symbol, false); } else if ((highestBoundExpr as BoundConversion)?.Conversion.IsTupleLiteralConversion == true) { var tupleLiteralConversion = (BoundConversion)highestBoundExpr; if (tupleLiteralConversion.Operand.Kind == BoundKind.ConvertedTupleLiteral) { var convertedTuple = (BoundConvertedTupleLiteral)tupleLiteralConversion.Operand; type = convertedTuple.SourceTuple.Type; nullability = convertedTuple.TopLevelNullability; } else { (type, nullability) = getTypeAndNullability(tupleLiteralConversion.Operand); } (convertedType, convertedNullability) = getTypeAndNullability(tupleLiteralConversion); conversion = tupleLiteralConversion.Conversion; } else if (highestBoundExprKind == BoundKind.FixedLocalCollectionInitializer) { var initializer = (BoundFixedLocalCollectionInitializer)highestBoundExpr; (convertedType, convertedNullability) = getTypeAndNullability(initializer); (type, nullability) = getTypeAndNullability(initializer.Expression); // the most pertinent conversion is the pointer conversion conversion = BoundNode.GetConversion(initializer.ElementPointerConversion, initializer.ElementPointerPlaceholder); } else if (boundExpr is BoundConvertedSwitchExpression { WasTargetTyped: true } convertedSwitch) { if (highestBoundExpr is BoundConversion { ConversionKind: ConversionKind.SwitchExpression, Conversion: var convertedSwitchConversion }) { // There was an implicit cast. type = convertedSwitch.NaturalTypeOpt; convertedType = convertedSwitch.Type; convertedNullability = convertedSwitch.TopLevelNullability; conversion = convertedSwitchConversion.IsValid ? convertedSwitchConversion : Conversion.NoConversion; } else { // There was an explicit cast on top of this type = convertedSwitch.NaturalTypeOpt; (convertedType, convertedNullability) = (type, nullability); conversion = Conversion.Identity; } } else if (boundExpr is BoundConditionalOperator { WasTargetTyped: true } cond) { if (highestBoundExpr is BoundConversion { ConversionKind: ConversionKind.ConditionalExpression }) { // There was an implicit cast. type = cond.NaturalTypeOpt; convertedType = cond.Type; convertedNullability = nullability; conversion = Conversion.MakeConditionalExpression(ImmutableArray<Conversion>.Empty); } else { // There was an explicit cast on top of this. type = cond.NaturalTypeOpt; (convertedType, convertedNullability) = (type, nullability); conversion = Conversion.Identity; } } else if (highestBoundExpr != null && highestBoundExpr != boundExpr && highestBoundExpr.HasExpressionType()) { (convertedType, convertedNullability) = getTypeAndNullability(highestBoundExpr); if (highestBoundExprKind != BoundKind.Conversion) { conversion = Conversion.Identity; } else if (((BoundConversion)highestBoundExpr).Operand.Kind != BoundKind.Conversion) { conversion = highestBoundExpr.GetConversion(); if (conversion.Kind == ConversionKind.AnonymousFunction) { // See comment above: anonymous functions do not have a type type = null; nullability = default; } } else { // There is a sequence of conversions; we use ClassifyConversionFromExpression to report the most pertinent. var binder = this.GetEnclosingBinder(boundExpr.Syntax.Span.Start); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; conversion = binder.Conversions.ClassifyConversionFromExpression(boundExpr, convertedType, ref discardedUseSiteInfo); } } else if (boundNodeForSyntacticParent?.Kind == BoundKind.DelegateCreationExpression) { // A delegate creation expression takes the place of a method group or anonymous function conversion. var delegateCreation = (BoundDelegateCreationExpression)boundNodeForSyntacticParent; (convertedType, convertedNullability) = getTypeAndNullability(delegateCreation); switch (boundExpr.Kind) { case BoundKind.MethodGroup: { conversion = new Conversion(ConversionKind.MethodGroup, delegateCreation.MethodOpt, delegateCreation.IsExtensionMethod); break; } case BoundKind.Lambda: { var lambda = (BoundLambda)boundExpr; conversion = new Conversion(ConversionKind.AnonymousFunction, lambda.Symbol, delegateCreation.IsExtensionMethod); break; } case BoundKind.UnboundLambda: { var lambda = ((UnboundLambda)boundExpr).BindForErrorRecovery(); conversion = new Conversion(ConversionKind.AnonymousFunction, lambda.Symbol, delegateCreation.IsExtensionMethod); break; } default: conversion = Conversion.Identity; break; } } else if (boundExpr is BoundConversion { ConversionKind: ConversionKind.MethodGroup, Conversion: var exprConversion, Type: { TypeKind: TypeKind.FunctionPointer }, SymbolOpt: var symbol }) { // Because the method group is a separate syntax node from the &, the lowest bound node here is the BoundConversion. However, // the conversion represents an implicit method group conversion from a typeless method group to a function pointer type, so // we should reflect that in the types and conversion we return. convertedType = type; convertedNullability = nullability; conversion = exprConversion; type = null; nullability = new NullabilityInfo(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableFlowState.NotNull); } else { convertedType = type; convertedNullability = nullability; conversion = Conversion.Identity; } return new CSharpTypeInfo(type, convertedType, nullability, convertedNullability, conversion); } return CSharpTypeInfo.None; static (TypeSymbol, NullabilityInfo) getTypeAndNullability(BoundExpression expr) => (expr.Type, expr.TopLevelNullability); } // Gets the method or property group from a specific bound node. // lowestBoundNode: The lowest node in the bound tree associated with node // highestBoundNode: The highest node in the bound tree associated with node // boundNodeForSyntacticParent: The lowest node in the bound tree associated with node.Parent. internal ImmutableArray<Symbol> GetMemberGroupForNode( SymbolInfoOptions options, BoundNode lowestBoundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt) { if (lowestBoundNode is BoundExpression boundExpr) { LookupResultKind resultKind; ImmutableArray<Symbol> memberGroup; bool isDynamic; GetSemanticSymbols(boundExpr, boundNodeForSyntacticParent, binderOpt, options, out isDynamic, out resultKind, out memberGroup); return memberGroup; } return ImmutableArray<Symbol>.Empty; } // Gets the indexer group from a specific bound node. // lowestBoundNode: The lowest node in the bound tree associated with node // highestBoundNode: The highest node in the bound tree associated with node // boundNodeForSyntacticParent: The lowest node in the bound tree associated with node.Parent. internal ImmutableArray<IPropertySymbol> GetIndexerGroupForNode( BoundNode lowestBoundNode, Binder binderOpt) { var boundExpr = lowestBoundNode as BoundExpression; if (boundExpr != null && boundExpr.Kind != BoundKind.TypeExpression) { return GetIndexerGroupSemanticSymbols(boundExpr, binderOpt); } return ImmutableArray<IPropertySymbol>.Empty; } // Gets symbol info for a type or namespace or alias reference. It is assumed that any error cases will come in // as a type whose OriginalDefinition is an error symbol from which the ResultKind can be retrieved. internal static SymbolInfo GetSymbolInfoForSymbol(Symbol symbol, SymbolInfoOptions options) { Debug.Assert((object)symbol != null); // Determine type. Dig through aliases if necessary. Symbol unwrapped = UnwrapAlias(symbol); TypeSymbol type = unwrapped as TypeSymbol; // Determine symbols and resultKind. var originalErrorSymbol = (object)type != null ? type.OriginalDefinition as ErrorTypeSymbol : null; if ((object)originalErrorSymbol != null) { // Error case. var symbols = ImmutableArray<Symbol>.Empty; LookupResultKind resultKind = originalErrorSymbol.ResultKind; if (resultKind != LookupResultKind.Empty) { symbols = originalErrorSymbol.CandidateSymbols; } if ((options & SymbolInfoOptions.ResolveAliases) != 0) { symbols = UnwrapAliases(symbols); } return SymbolInfoFactory.Create(symbols, resultKind, isDynamic: false); } else { // Non-error case. Use constructor that doesn't require creation of a Symbol array. var symbolToReturn = ((options & SymbolInfoOptions.ResolveAliases) != 0) ? unwrapped : symbol; return new SymbolInfo(symbolToReturn.GetPublicSymbol(), ImmutableArray<ISymbol>.Empty, CandidateReason.None); } } // Gets TypeInfo for a type or namespace or alias reference. internal static CSharpTypeInfo GetTypeInfoForSymbol(Symbol symbol) { Debug.Assert((object)symbol != null); // Determine type. Dig through aliases if necessary. TypeSymbol type = UnwrapAlias(symbol) as TypeSymbol; // https://github.com/dotnet/roslyn/issues/35033: Examine this and make sure that we're using the correct nullabilities return new CSharpTypeInfo(type, type, default, default, Conversion.Identity); } protected static Symbol UnwrapAlias(Symbol symbol) { return symbol is AliasSymbol aliasSym ? aliasSym.Target : symbol; } protected static ImmutableArray<Symbol> UnwrapAliases(ImmutableArray<Symbol> symbols) { bool anyAliases = false; foreach (Symbol symbol in symbols) { if (symbol.Kind == SymbolKind.Alias) anyAliases = true; } if (!anyAliases) return symbols; ArrayBuilder<Symbol> builder = ArrayBuilder<Symbol>.GetInstance(); foreach (Symbol symbol in symbols) { // Caas clients don't want ErrorTypeSymbol in the symbols, but the best guess // instead. If no best guess, then nothing is returned. AddUnwrappingErrorTypes(builder, UnwrapAlias(symbol)); } return builder.ToImmutableAndFree(); } // This is used by other binding APIs to invoke the right binder API internal virtual BoundNode Bind(Binder binder, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { switch (node) { case ExpressionSyntax expression: var parent = expression.Parent; return parent.IsKind(SyntaxKind.GotoStatement) ? binder.BindLabel(expression, diagnostics) : binder.BindNamespaceOrTypeOrExpression(expression, diagnostics); case StatementSyntax statement: return binder.BindStatement(statement, diagnostics); case GlobalStatementSyntax globalStatement: BoundStatement bound = binder.BindStatement(globalStatement.Statement, diagnostics); return new BoundGlobalStatementInitializer(node, bound); } return null; } /// <summary> /// Analyze control-flow within a part of a method body. /// </summary> /// <param name="firstStatement">The first statement to be included in the analysis.</param> /// <param name="lastStatement">The last statement to be included in the analysis.</param> /// <returns>An object that can be used to obtain the result of the control flow analysis.</returns> /// <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception> public virtual ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { // Only supported on a SyntaxTreeSemanticModel. throw new NotSupportedException(); } /// <summary> /// Analyze control-flow within a part of a method body. /// </summary> /// <param name="statement">The statement to be included in the analysis.</param> /// <returns>An object that can be used to obtain the result of the control flow analysis.</returns> public virtual ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax statement) { return AnalyzeControlFlow(statement, statement); } /// <summary> /// Analyze data-flow within an expression. /// </summary> /// <param name="expression">The expression within the associated SyntaxTree to analyze.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> public virtual DataFlowAnalysis AnalyzeDataFlow(ExpressionSyntax expression) { // Only supported on a SyntaxTreeSemanticModel. throw new NotSupportedException(); } /// <summary> /// Analyze data-flow within a part of a method body. /// </summary> /// <param name="firstStatement">The first statement to be included in the analysis.</param> /// <param name="lastStatement">The last statement to be included in the analysis.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> /// <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception> public virtual DataFlowAnalysis AnalyzeDataFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { // Only supported on a SyntaxTreeSemanticModel. throw new NotSupportedException(); } /// <summary> /// Analyze data-flow within a part of a method body. /// </summary> /// <param name="statement">The statement to be included in the analysis.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> public virtual DataFlowAnalysis AnalyzeDataFlow(StatementSyntax statement) { return AnalyzeDataFlow(statement, statement); } /// <summary> /// Get a SemanticModel object that is associated with a method body that did not appear in this source code. /// Given <paramref name="position"/> must lie within an existing method body of the Root syntax node for this SemanticModel. /// Locals and labels declared within this existing method body are not considered to be in scope of the speculated method body. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel and must be /// within the FullSpan of a Method body within the Root syntax node.</param> /// <param name="method">A syntax node that represents a parsed method declaration. This method should not be /// present in the syntax tree associated with this object, but must have identical signature to the method containing /// the given <paramref name="position"/> in this SemanticModel.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="method"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="method"/> node is contained any SyntaxTree in the current Compilation</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="method"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModelForMethodBody(int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(method); return TryGetSpeculativeSemanticModelForMethodBodyCore((SyntaxTreeSemanticModel)this, position, method, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a method body that did not appear in this source code. /// Given <paramref name="position"/> must lie within an existing method body of the Root syntax node for this SemanticModel. /// Locals and labels declared within this existing method body are not considered to be in scope of the speculated method body. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel and must be /// within the FullSpan of a Method body within the Root syntax node.</param> /// <param name="accessor">A syntax node that represents a parsed accessor declaration. This accessor should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="accessor"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="accessor"/> node is contained any SyntaxTree in the current Compilation</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="accessor"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModelForMethodBody(int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(accessor); return TryGetSpeculativeSemanticModelForMethodBodyCore((SyntaxTreeSemanticModel)this, position, accessor, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a type syntax node that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a type syntax that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// </param> /// <param name="type">A syntax node that represents a parsed expression. This expression should not be /// present in the syntax tree associated with this object.</param> /// <param name="bindingOption">Indicates whether to bind the expression as a full expression, /// or as a type or namespace.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="type"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="type"/> node is contained any SyntaxTree in the current Compilation</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="type"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, TypeSyntax type, out SemanticModel speculativeModel, SpeculativeBindingOption bindingOption = SpeculativeBindingOption.BindAsExpression) { CheckModelAndSyntaxNodeToSpeculate(type); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, type, bindingOption, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a statement that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a statement that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel.</param> /// <param name="statement">A syntax node that represents a parsed statement. This statement should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="statement"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="statement"/> node is contained any SyntaxTree in the current Compilation</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="statement"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, StatementSyntax statement, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(statement); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, statement, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with an initializer that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a field initializer or default parameter value that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// </param> /// <param name="initializer">A syntax node that represents a parsed initializer. This initializer should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="initializer"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="initializer"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="initializer"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(initializer); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, initializer, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with an expression body that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of an expression body that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// </param> /// <param name="expressionBody">A syntax node that represents a parsed expression body. This node should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="expressionBody"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="expressionBody"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="expressionBody"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(expressionBody); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, expressionBody, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a constructor initializer that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a constructor initializer that did not appear in source code. /// /// NOTE: This will only work in locations where there is already a constructor initializer. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// Furthermore, it must be within the span of an existing constructor initializer. /// </param> /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. /// This node should not be present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="constructorInitializer"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="constructorInitializer"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="constructorInitializer"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(constructorInitializer); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, constructorInitializer, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a constructor initializer that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a constructor initializer that did not appear in source code. /// /// NOTE: This will only work in locations where there is already a constructor initializer. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the span of an existing constructor initializer. /// </param> /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. /// This node should not be present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="constructorInitializer"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="constructorInitializer"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="constructorInitializer"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(constructorInitializer); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, constructorInitializer, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with a cref that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of a cref that did not appear in source code. /// /// NOTE: This will only work in locations where there is already a cref. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel. /// Furthermore, it must be within the span of an existing cref. /// </param> /// <param name="crefSyntax">A syntax node that represents a parsed cref syntax. /// This node should not be present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="crefSyntax"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="crefSyntax"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="crefSyntax"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(crefSyntax); return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, crefSyntax, out speculativeModel); } internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel); /// <summary> /// Get a SemanticModel object that is associated with an attribute that did not appear in /// this source code. This can be used to get detailed semantic information about sub-parts /// of an attribute that did not appear in source code. /// </summary> /// <param name="position">A character position used to identify a declaration scope and accessibility. This /// character position must be within the FullSpan of the Root syntax node in this SemanticModel.</param> /// <param name="attribute">A syntax node that represents a parsed attribute. This attribute should not be /// present in the syntax tree associated with this object.</param> /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic /// information associated with syntax nodes within <paramref name="attribute"/>.</param> /// <returns>Flag indicating whether a speculative semantic model was created.</returns> /// <exception cref="ArgumentException">Throws this exception if the <paramref name="attribute"/> node is contained any SyntaxTree in the current Compilation.</exception> /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="attribute"/> is null.</exception> /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true. /// Chaining of speculative semantic model is not supported.</exception> public bool TryGetSpeculativeSemanticModel(int position, AttributeSyntax attribute, out SemanticModel speculativeModel) { CheckModelAndSyntaxNodeToSpeculate(attribute); var binder = GetSpeculativeBinderForAttribute(position, attribute); if (binder == null) { speculativeModel = null; return false; } AliasSymbol aliasOpt; var attributeType = (NamedTypeSymbol)binder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type; speculativeModel = ((SyntaxTreeSemanticModel)this).CreateSpeculativeAttributeSemanticModel(position, attribute, binder, aliasOpt, attributeType); return true; } /// <summary> /// If this is a speculative semantic model, then returns its parent semantic model. /// Otherwise, returns null. /// </summary> public new abstract CSharpSemanticModel ParentModel { get; } /// <summary> /// The SyntaxTree that this object is associated with. /// </summary> public new abstract SyntaxTree SyntaxTree { get; } /// <summary> /// Determines what type of conversion, if any, would be used if a given expression was /// converted to a given type. If isExplicitInSource is true, the conversion produced is /// that which would be used if the conversion were done for a cast expression. /// </summary> /// <param name="expression">An expression which much occur within the syntax tree /// associated with this object.</param> /// <param name="destination">The type to attempt conversion to.</param> /// <param name="isExplicitInSource">True if the conversion should be determined as for a cast expression.</param> /// <returns>Returns a Conversion object that summarizes whether the conversion was /// possible, and if so, what kind of conversion it was. If no conversion was possible, a /// Conversion object with a false "Exists" property is returned.</returns> /// <remarks>To determine the conversion between two types (instead of an expression and a /// type), use Compilation.ClassifyConversion.</remarks> public abstract Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false); /// <summary> /// Determines what type of conversion, if any, would be used if a given expression was /// converted to a given type. If isExplicitInSource is true, the conversion produced is /// that which would be used if the conversion were done for a cast expression. /// </summary> /// <param name="position">The character position for determining the enclosing declaration /// scope and accessibility.</param> /// <param name="expression">The expression to classify. This expression does not need to be /// present in the syntax tree associated with this object.</param> /// <param name="destination">The type to attempt conversion to.</param> /// <param name="isExplicitInSource">True if the conversion should be determined as for a cast expression.</param> /// <returns>Returns a Conversion object that summarizes whether the conversion was /// possible, and if so, what kind of conversion it was. If no conversion was possible, a /// Conversion object with a false "Exists" property is returned.</returns> /// <remarks>To determine the conversion between two types (instead of an expression and a /// type), use Compilation.ClassifyConversion.</remarks> public Conversion ClassifyConversion(int position, ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) { if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } TypeSymbol cdestination = destination.EnsureCSharpSymbolOrNull(nameof(destination)); if (expression.Kind() == SyntaxKind.DeclarationExpression) { // Conversion from a declaration is unspecified. return Conversion.NoConversion; } if (isExplicitInSource) { return ClassifyConversionForCast(position, expression, cdestination); } // Note that it is possible for an expression to be convertible to a type // via both an implicit user-defined conversion and an explicit built-in conversion. // In that case, this method chooses the implicit conversion. position = CheckAndAdjustPosition(position); var binder = this.GetEnclosingBinder(position); if (binder != null) { var bnode = binder.BindExpression(expression, BindingDiagnosticBag.Discarded); if (bnode != null && !cdestination.IsErrorType()) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return binder.Conversions.ClassifyConversionFromExpression(bnode, cdestination, ref discardedUseSiteInfo); } } return Conversion.NoConversion; } /// <summary> /// Determines what type of conversion, if any, would be used if a given expression was /// converted to a given type using an explicit cast. /// </summary> /// <param name="expression">An expression which much occur within the syntax tree /// associated with this object.</param> /// <param name="destination">The type to attempt conversion to.</param> /// <returns>Returns a Conversion object that summarizes whether the conversion was /// possible, and if so, what kind of conversion it was. If no conversion was possible, a /// Conversion object with a false "Exists" property is returned.</returns> /// <remarks>To determine the conversion between two types (instead of an expression and a /// type), use Compilation.ClassifyConversion.</remarks> internal abstract Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination); /// <summary> /// Determines what type of conversion, if any, would be used if a given expression was /// converted to a given type using an explicit cast. /// </summary> /// <param name="position">The character position for determining the enclosing declaration /// scope and accessibility.</param> /// <param name="expression">The expression to classify. This expression does not need to be /// present in the syntax tree associated with this object.</param> /// <param name="destination">The type to attempt conversion to.</param> /// <returns>Returns a Conversion object that summarizes whether the conversion was /// possible, and if so, what kind of conversion it was. If no conversion was possible, a /// Conversion object with a false "Exists" property is returned.</returns> /// <remarks>To determine the conversion between two types (instead of an expression and a /// type), use Compilation.ClassifyConversion.</remarks> internal Conversion ClassifyConversionForCast(int position, ExpressionSyntax expression, TypeSymbol destination) { if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } position = CheckAndAdjustPosition(position); var binder = this.GetEnclosingBinder(position); if (binder != null) { var bnode = binder.BindExpression(expression, BindingDiagnosticBag.Discarded); if (bnode != null && !destination.IsErrorType()) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return binder.Conversions.ClassifyConversionFromExpression(bnode, destination, ref discardedUseSiteInfo, forCast: true); } } return Conversion.NoConversion; } #region "GetDeclaredSymbol overloads for MemberDeclarationSyntax and its subtypes" /// <summary> /// Given a member declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for following subtypes of MemberDeclarationSyntax: /// NOTE: (1) GlobalStatementSyntax as they don't declare any symbols. /// NOTE: (2) IncompleteMemberSyntax as there are no symbols for incomplete members. /// NOTE: (3) BaseFieldDeclarationSyntax or its subtypes as these declarations can contain multiple variable declarators. /// NOTE: GetDeclaredSymbol should be called on the variable declarators directly. /// </remarks> public abstract ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a local function declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a compilation unit syntax, get the corresponding Simple Program entry point symbol. /// </summary> /// <param name="declarationSyntax">The compilation unit that declares the entry point member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a namespace declaration syntax node, get the corresponding namespace symbol for /// the declaration assembly. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a namespace.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The namespace symbol that was declared by the namespace declaration.</returns> public abstract INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a namespace declaration syntax node, get the corresponding namespace symbol for /// the declaration assembly. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a namespace.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The namespace symbol that was declared by the namespace declaration.</returns> public abstract INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a type declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a type.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseTypeDeclarationSyntax as all of them return a NamedTypeSymbol. /// </remarks> public abstract INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a delegate declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a delegate.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> public abstract INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a enum member declaration, get the corresponding field symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an enum member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a base method declaration syntax, get the corresponding method symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a method.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseMethodDeclarationSyntax as all of them return a MethodSymbol. /// </remarks> public abstract IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); #region GetDeclaredSymbol overloads for BasePropertyDeclarationSyntax and its subtypes /// <summary> /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares a property, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares an indexer, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an indexer.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares a (custom) event, get the corresponding event symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); #endregion #endregion // Anonymous types and Tuple expressions are an interesting case here because they declare their own types // // In both cases there is no distinct syntax that creates the type and the syntax that describes the type is the literal itself. // Surely - if you need to modify the anonymous type or a type of a tuple literal, you would be modifying these expressions. // // As a result we support GetDeclaredSymbol on the whole AnonymousObjectCreationExpressionSyntax/TupleExpressionSyntax. // The implementation returns the type of the expression. // // In addition to that GetDeclaredSymbol works on the AnonymousObjectMemberDeclaratorSyntax/ArgumentSyntax // The implementation returns the property/field symbol that is declared by the corresponding syntax. // // Example: // GetDeclaredSymbol => Type: (int Alice, int Bob) // _____ |__________ // [ ] // var tuple = (Alice: 1, Bob: 2); // [ ] // \GetDeclaredSymbol => Field: (int Alice, int Bob).Bob // // A special note must be made about the locations of the corresponding symbols - they refer to the actual syntax // of the literal or the anonymous type creation expression // // This way IDEs can unambiguously implement such services as "Go to definition" // // I.E. GetSymbolInfo for "Bob" in "tuple.Bob" should point to the same field as returned by GetDeclaredSymbol when applied to // the ArgumentSyntax "Bob: 2", since that is where the field was declared, where renames should be applied and so on. // // // In comparison to anonymous types, tuples have one special behavior. // It is permitted for tuple literals to not have a natural type as long as there is a target type which determines the types of the fields. // As, such for the purpose of GetDeclaredSymbol, the type symbol that is returned for tuple literals has target-typed fields, // but yet with the original names. // // GetDeclaredSymbol => Type: (string Alice, short Bob) // ________ |__________ // [ ] // (string, short) tuple = (Alice: null, Bob: 2); // [ ] // \GetDeclaredSymbol => Field: (string Alice, short Bob).Alice // // In particular, the location of the field declaration is "Alice: null" and not the "string" // the location of the type is "(Alice: null, Bob: 2)" and not the "(string, short)" // // The reason for this behavior is that, even though there might not be other references to "Alice" field in the code, // the name "Alice" itself evidently refers to something named "Alice" and should still work with // all the related APIs and services such as "Find all References", "Go to definition", "symbolic rename" etc... // // GetSymbolInfo => Field: (string Alice, short Bob).Alice // __ |__ // [ ] // (string, short) tuple = (Alice: null, Bob: 2); // /// <summary> /// Given a syntax node of anonymous object creation initializer, get the anonymous object property symbol. /// </summary> /// <param name="declaratorSyntax">The syntax node that declares a property.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node of anonymous object creation expression, get the anonymous object type symbol. /// </summary> /// <param name="declaratorSyntax">The syntax node that declares an anonymous object.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node of a tuple expression, get the tuple type symbol. /// </summary> /// <param name="declaratorSyntax">The tuple expression node.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node of an argument expression, get the declared symbol. /// </summary> /// <param name="declaratorSyntax">The argument syntax node.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// Generally ArgumentSyntax nodes do not declare symbols, except when used as arguments of a tuple literal. /// Example: var x = (Alice: 1, Bob: 2); /// ArgumentSyntax "Alice: 1" declares a tuple element field "(int Alice, int Bob).Alice" /// </remarks> public abstract ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares a property or member accessor, get the corresponding /// symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an accessor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a syntax node that declares an expression body, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an expression body.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a variable declarator syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a variable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a variable designation syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a variable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public abstract ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a labeled statement syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the labeled statement.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public abstract ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a switch label syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the switch label.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public abstract ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a using declaration get the corresponding symbol for the using alias that was /// introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared.</returns> /// <remarks> /// If the using directive is an error because it attempts to introduce an alias for which an existing alias was /// previously declared in the same scope, the result is a newly-constructed AliasSymbol (i.e. not one from the /// symbol table). /// </remarks> public abstract IAliasSymbol GetDeclaredSymbol(UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given an extern alias declaration get the corresponding symbol for the alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared, or null if a duplicate alias symbol was declared.</returns> public abstract IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a parameter declaration syntax node, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a parameter.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The parameter that was declared.</returns> public abstract IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Given a base field declaration syntax, get the corresponding symbols. /// </summary> /// <param name="declarationSyntax">The syntax node that declares one or more fields or events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbols that were declared.</returns> internal abstract ImmutableArray<ISymbol> GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); protected ParameterSymbol GetParameterSymbol( ImmutableArray<ParameterSymbol> parameters, ParameterSyntax parameter, CancellationToken cancellationToken = default(CancellationToken)) { foreach (var symbol in parameters) { cancellationToken.ThrowIfCancellationRequested(); foreach (var location in symbol.Locations) { cancellationToken.ThrowIfCancellationRequested(); if (location.SourceTree == this.SyntaxTree && parameter.Span.Contains(location.SourceSpan)) { return symbol; } } } return null; } /// <summary> /// Given a type parameter declaration (field or method), get the corresponding symbol /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="typeParameter"></param> public abstract ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)); internal BinderFlags GetSemanticModelBinderFlags() { return this.IgnoresAccessibility ? BinderFlags.SemanticModel | BinderFlags.IgnoreAccessibility : BinderFlags.SemanticModel; } /// <summary> /// Given a foreach statement, get the symbol for the iteration variable /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="forEachStatement"></param> public ILocalSymbol GetDeclaredSymbol(ForEachStatementSyntax forEachStatement, CancellationToken cancellationToken = default(CancellationToken)) { Binder enclosingBinder = this.GetEnclosingBinder(GetAdjustedNodePosition(forEachStatement)); if (enclosingBinder == null) { return null; } Binder foreachBinder = enclosingBinder.GetBinder(forEachStatement); // Binder.GetBinder can fail in presence of syntax errors. if (foreachBinder == null) { return null; } LocalSymbol local = foreachBinder.GetDeclaredLocalsForScope(forEachStatement).FirstOrDefault(); return (local is SourceLocalSymbol { DeclarationKind: LocalDeclarationKind.ForEachIterationVariable } sourceLocal ? GetAdjustedLocalSymbol(sourceLocal) : local).GetPublicSymbol(); } /// <summary> /// Given a local symbol, gets an updated version of that local symbol adjusted for nullability analysis /// if the analysis affects the local. /// </summary> /// <param name="originalSymbol">The original symbol from initial binding.</param> /// /// <returns>The nullability-adjusted local, or the original symbol if the nullability analysis made no adjustments or was not run.</returns> internal abstract LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol originalSymbol); /// <summary> /// Given a catch declaration, get the symbol for the exception variable /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="catchDeclaration"></param> public ILocalSymbol GetDeclaredSymbol(CatchDeclarationSyntax catchDeclaration, CancellationToken cancellationToken = default(CancellationToken)) { CSharpSyntaxNode catchClause = catchDeclaration.Parent; //Syntax->Binder map is keyed on clause, not decl Debug.Assert(catchClause.Kind() == SyntaxKind.CatchClause); Binder enclosingBinder = this.GetEnclosingBinder(GetAdjustedNodePosition(catchClause)); if (enclosingBinder == null) { return null; } Binder catchBinder = enclosingBinder.GetBinder(catchClause); // Binder.GetBinder can fail in presence of syntax errors. if (catchBinder == null) { return null; } catchBinder = enclosingBinder.GetBinder(catchClause); LocalSymbol local = catchBinder.GetDeclaredLocalsForScope(catchClause).FirstOrDefault(); return ((object)local != null && local.DeclarationKind == LocalDeclarationKind.CatchVariable) ? local.GetPublicSymbol() : null; } public abstract IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax queryClause, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the query range variable declared in a join into clause. /// </summary> public abstract IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the query range variable declared in a query continuation clause. /// </summary> public abstract IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)); // Get the symbols and possible method or property group associated with a bound node, as // they should be exposed through GetSemanticInfo. // NB: It is not safe to pass a null binderOpt during speculative binding. private ImmutableArray<Symbol> GetSemanticSymbols( BoundExpression boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, SymbolInfoOptions options, out bool isDynamic, out LookupResultKind resultKind, out ImmutableArray<Symbol> memberGroup) { memberGroup = ImmutableArray<Symbol>.Empty; ImmutableArray<Symbol> symbols = ImmutableArray<Symbol>.Empty; resultKind = LookupResultKind.Viable; isDynamic = false; switch (boundNode.Kind) { case BoundKind.MethodGroup: symbols = GetMethodGroupSemanticSymbols((BoundMethodGroup)boundNode, boundNodeForSyntacticParent, binderOpt, out resultKind, out isDynamic, out memberGroup); break; case BoundKind.PropertyGroup: symbols = GetPropertyGroupSemanticSymbols((BoundPropertyGroup)boundNode, boundNodeForSyntacticParent, binderOpt, out resultKind, out memberGroup); break; case BoundKind.BadExpression: { var expr = (BoundBadExpression)boundNode; resultKind = expr.ResultKind; if (expr.Syntax.Kind() is SyntaxKind.ObjectCreationExpression or SyntaxKind.ImplicitObjectCreationExpression) { if (resultKind == LookupResultKind.NotCreatable) { return expr.Symbols; } else if (expr.Type.IsDelegateType()) { resultKind = LookupResultKind.Empty; return symbols; } memberGroup = expr.Symbols; } return expr.Symbols; } case BoundKind.DelegateCreationExpression: break; case BoundKind.TypeExpression: { var boundType = (BoundTypeExpression)boundNode; // Watch out for not creatable types within object creation syntax if (boundNodeForSyntacticParent != null && boundNodeForSyntacticParent.Syntax.Kind() == SyntaxKind.ObjectCreationExpression && ((ObjectCreationExpressionSyntax)boundNodeForSyntacticParent.Syntax).Type == boundType.Syntax && boundNodeForSyntacticParent.Kind == BoundKind.BadExpression && ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind == LookupResultKind.NotCreatable) { resultKind = LookupResultKind.NotCreatable; } // could be a type or alias. var typeSymbol = boundType.AliasOpt ?? (Symbol)boundType.Type; var originalErrorType = typeSymbol.OriginalDefinition as ErrorTypeSymbol; if ((object)originalErrorType != null) { resultKind = originalErrorType.ResultKind; symbols = originalErrorType.CandidateSymbols; } else { symbols = ImmutableArray.Create<Symbol>(typeSymbol); } } break; case BoundKind.TypeOrValueExpression: { // If we're seeing a node of this kind, then we failed to resolve the member access // as either a type or a property/field/event/local/parameter. In such cases, // the second interpretation applies so just visit the node for that. BoundExpression valueExpression = ((BoundTypeOrValueExpression)boundNode).Data.ValueExpression; return GetSemanticSymbols(valueExpression, boundNodeForSyntacticParent, binderOpt, options, out isDynamic, out resultKind, out memberGroup); } case BoundKind.Call: { // Either overload resolution succeeded for this call or it did not. If it // did not succeed then we've stashed the original method symbols from the // method group, and we should use those as the symbols displayed for the // call. If it did succeed then we did not stash any symbols; just fall // through to the default case. var call = (BoundCall)boundNode; if (call.OriginalMethodsOpt.IsDefault) { if ((object)call.Method != null) { symbols = CreateReducedExtensionMethodIfPossible(call); resultKind = call.ResultKind; } } else { symbols = StaticCast<Symbol>.From(CreateReducedExtensionMethodsFromOriginalsIfNecessary(call, Compilation)); resultKind = call.ResultKind; } } break; case BoundKind.FunctionPointerInvocation: { var invocation = (BoundFunctionPointerInvocation)boundNode; symbols = ImmutableArray.Create<Symbol>(invocation.FunctionPointer); resultKind = invocation.ResultKind; break; } case BoundKind.UnconvertedAddressOfOperator: { // We try to match the results given for a similar piece of syntax here: bad invocations. // A BoundUnconvertedAddressOfOperator represents this syntax: &M // Similarly, a BoundCall for a bad invocation represents this syntax: M(args) // Calling GetSymbolInfo on the syntax will return an array of candidate symbols that were // looked up, but calling GetMemberGroup will return an empty array. So, we ignore the member // group result in the call below. symbols = GetMethodGroupSemanticSymbols( ((BoundUnconvertedAddressOfOperator)boundNode).Operand, boundNodeForSyntacticParent, binderOpt, out resultKind, out isDynamic, methodGroup: out _); break; } case BoundKind.IndexerAccess: { // As for BoundCall, pull out stashed candidates if overload resolution failed. BoundIndexerAccess indexerAccess = (BoundIndexerAccess)boundNode; Debug.Assert((object)indexerAccess.Indexer != null); resultKind = indexerAccess.ResultKind; ImmutableArray<PropertySymbol> originalIndexersOpt = indexerAccess.OriginalIndexersOpt; symbols = originalIndexersOpt.IsDefault ? ImmutableArray.Create<Symbol>(indexerAccess.Indexer) : StaticCast<Symbol>.From(originalIndexersOpt); } break; case BoundKind.IndexOrRangePatternIndexerAccess: { var indexerAccess = (BoundIndexOrRangePatternIndexerAccess)boundNode; resultKind = indexerAccess.ResultKind; // The only time a BoundIndexOrRangePatternIndexerAccess is created, overload resolution succeeded // and returned only 1 result Debug.Assert(indexerAccess.PatternSymbol is object); symbols = ImmutableArray.Create<Symbol>(indexerAccess.PatternSymbol); } break; case BoundKind.EventAssignmentOperator: var eventAssignment = (BoundEventAssignmentOperator)boundNode; isDynamic = eventAssignment.IsDynamic; var eventSymbol = eventAssignment.Event; var methodSymbol = eventAssignment.IsAddition ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; if ((object)methodSymbol == null) { symbols = ImmutableArray<Symbol>.Empty; resultKind = LookupResultKind.Empty; } else { symbols = ImmutableArray.Create<Symbol>(methodSymbol); resultKind = eventAssignment.ResultKind; } break; case BoundKind.EventAccess when boundNodeForSyntacticParent is BoundEventAssignmentOperator { ResultKind: LookupResultKind.Viable } parentOperator && boundNode.ExpressionSymbol is Symbol accessSymbol && boundNode != parentOperator.Argument && parentOperator.Event.Equals(accessSymbol, TypeCompareKind.AllNullableIgnoreOptions): // When we're looking at the left-hand side of an event assignment, we synthesize a BoundEventAccess node. This node does not have // nullability information, however, so if we're in that case then we need to grab the event symbol from the parent event assignment // which does have the nullability-reinferred symbol symbols = ImmutableArray.Create<Symbol>(parentOperator.Event); resultKind = parentOperator.ResultKind; break; case BoundKind.Conversion: var conversion = (BoundConversion)boundNode; isDynamic = conversion.ConversionKind.IsDynamic(); if (!isDynamic) { if ((conversion.ConversionKind == ConversionKind.MethodGroup) && conversion.IsExtensionMethod) { var symbol = conversion.SymbolOpt; Debug.Assert((object)symbol != null); symbols = ImmutableArray.Create<Symbol>(ReducedExtensionMethodSymbol.Create(symbol)); resultKind = conversion.ResultKind; } else if (conversion.ConversionKind.IsUserDefinedConversion()) { GetSymbolsAndResultKind(conversion, conversion.SymbolOpt, conversion.OriginalUserDefinedConversionsOpt, out symbols, out resultKind); } else { goto default; } } break; case BoundKind.BinaryOperator: GetSymbolsAndResultKind((BoundBinaryOperator)boundNode, out isDynamic, ref resultKind, ref symbols); break; case BoundKind.UnaryOperator: GetSymbolsAndResultKind((BoundUnaryOperator)boundNode, out isDynamic, ref resultKind, ref symbols); break; case BoundKind.UserDefinedConditionalLogicalOperator: var @operator = (BoundUserDefinedConditionalLogicalOperator)boundNode; isDynamic = false; GetSymbolsAndResultKind(@operator, @operator.LogicalOperator, @operator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); break; case BoundKind.CompoundAssignmentOperator: GetSymbolsAndResultKind((BoundCompoundAssignmentOperator)boundNode, out isDynamic, ref resultKind, ref symbols); break; case BoundKind.IncrementOperator: GetSymbolsAndResultKind((BoundIncrementOperator)boundNode, out isDynamic, ref resultKind, ref symbols); break; case BoundKind.AwaitExpression: var await = (BoundAwaitExpression)boundNode; isDynamic = await.AwaitableInfo.IsDynamic; goto default; case BoundKind.ConditionalOperator: var conditional = (BoundConditionalOperator)boundNode; Debug.Assert(conditional.ExpressionSymbol is null); isDynamic = conditional.IsDynamic; goto default; case BoundKind.Attribute: { Debug.Assert(boundNodeForSyntacticParent == null); var attribute = (BoundAttribute)boundNode; resultKind = attribute.ResultKind; // If attribute name bound to a single named type or an error type // with a single named type candidate symbol, we will return constructors // of the named type in the semantic info. // Otherwise, we will return the error type candidate symbols. var namedType = (NamedTypeSymbol)attribute.Type; if (namedType.IsErrorType()) { Debug.Assert(resultKind != LookupResultKind.Viable); var errorType = (ErrorTypeSymbol)namedType; var candidateSymbols = errorType.CandidateSymbols; // If error type has a single named type candidate symbol, we want to // use that type for symbol info. if (candidateSymbols.Length == 1 && candidateSymbols[0] is NamedTypeSymbol) { namedType = (NamedTypeSymbol)candidateSymbols[0]; } else { symbols = candidateSymbols; break; } } AdjustSymbolsForObjectCreation(attribute, namedType, attribute.Constructor, binderOpt, ref resultKind, ref symbols, ref memberGroup); } break; case BoundKind.QueryClause: { var query = (BoundQueryClause)boundNode; var builder = ArrayBuilder<Symbol>.GetInstance(); if (query.Operation != null && (object)query.Operation.ExpressionSymbol != null) builder.Add(query.Operation.ExpressionSymbol); if ((object)query.DefinedSymbol != null) builder.Add(query.DefinedSymbol); if (query.Cast != null && (object)query.Cast.ExpressionSymbol != null) builder.Add(query.Cast.ExpressionSymbol); symbols = builder.ToImmutableAndFree(); } break; case BoundKind.DynamicInvocation: var dynamicInvocation = (BoundDynamicInvocation)boundNode; Debug.Assert(dynamicInvocation.ExpressionSymbol is null); symbols = memberGroup = dynamicInvocation.ApplicableMethods.Cast<MethodSymbol, Symbol>(); isDynamic = true; break; case BoundKind.DynamicCollectionElementInitializer: var collectionInit = (BoundDynamicCollectionElementInitializer)boundNode; Debug.Assert(collectionInit.ExpressionSymbol is null); symbols = memberGroup = collectionInit.ApplicableMethods.Cast<MethodSymbol, Symbol>(); isDynamic = true; break; case BoundKind.DynamicIndexerAccess: var dynamicIndexer = (BoundDynamicIndexerAccess)boundNode; Debug.Assert(dynamicIndexer.ExpressionSymbol is null); symbols = memberGroup = dynamicIndexer.ApplicableIndexers.Cast<PropertySymbol, Symbol>(); isDynamic = true; break; case BoundKind.DynamicMemberAccess: Debug.Assert((object)boundNode.ExpressionSymbol == null); isDynamic = true; break; case BoundKind.DynamicObjectCreationExpression: var objectCreation = (BoundDynamicObjectCreationExpression)boundNode; symbols = memberGroup = objectCreation.ApplicableMethods.Cast<MethodSymbol, Symbol>(); isDynamic = true; break; case BoundKind.ObjectCreationExpression: var boundObjectCreation = (BoundObjectCreationExpression)boundNode; if ((object)boundObjectCreation.Constructor != null) { Debug.Assert(boundObjectCreation.ConstructorsGroup.Contains(boundObjectCreation.Constructor)); symbols = ImmutableArray.Create<Symbol>(boundObjectCreation.Constructor); } else if (boundObjectCreation.ConstructorsGroup.Length > 0) { symbols = StaticCast<Symbol>.From(boundObjectCreation.ConstructorsGroup); resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); } memberGroup = boundObjectCreation.ConstructorsGroup.Cast<MethodSymbol, Symbol>(); break; case BoundKind.ThisReference: case BoundKind.BaseReference: { Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); NamedTypeSymbol containingType = binder.ContainingType; var containingMember = binder.ContainingMember(); var thisParam = GetThisParameter(boundNode.Type, containingType, containingMember, out resultKind); symbols = thisParam != null ? ImmutableArray.Create<Symbol>(thisParam) : ImmutableArray<Symbol>.Empty; } break; case BoundKind.FromEndIndexExpression: { var fromEndIndexExpression = (BoundFromEndIndexExpression)boundNode; if ((object)fromEndIndexExpression.MethodOpt != null) { symbols = ImmutableArray.Create<Symbol>(fromEndIndexExpression.MethodOpt); } break; } case BoundKind.RangeExpression: { var rangeExpression = (BoundRangeExpression)boundNode; if ((object)rangeExpression.MethodOpt != null) { symbols = ImmutableArray.Create<Symbol>(rangeExpression.MethodOpt); } break; } default: { if (boundNode.ExpressionSymbol is Symbol symbol) { symbols = ImmutableArray.Create(symbol); resultKind = boundNode.ResultKind; } } break; } if (boundNodeForSyntacticParent != null && (options & SymbolInfoOptions.PreferConstructorsToType) != 0) { // Adjust symbols to get the constructors if we're T in a "new T(...)". AdjustSymbolsForObjectCreation(boundNode, boundNodeForSyntacticParent, binderOpt, ref resultKind, ref symbols, ref memberGroup); } return symbols; } private static ParameterSymbol GetThisParameter(TypeSymbol typeOfThis, NamedTypeSymbol containingType, Symbol containingMember, out LookupResultKind resultKind) { if ((object)containingMember == null || (object)containingType == null) { // not in a member of a type (can happen when speculating) resultKind = LookupResultKind.NotReferencable; return new ThisParameterSymbol(containingMember as MethodSymbol, typeOfThis); } ParameterSymbol thisParam; switch (containingMember.Kind) { case SymbolKind.Method: case SymbolKind.Field: case SymbolKind.Property: if (containingMember.IsStatic) { // in a static member resultKind = LookupResultKind.StaticInstanceMismatch; thisParam = new ThisParameterSymbol(containingMember as MethodSymbol, containingType); } else { if ((object)typeOfThis == ErrorTypeSymbol.UnknownResultType) { // in an instance member, but binder considered this/base unreferenceable thisParam = new ThisParameterSymbol(containingMember as MethodSymbol, containingType); resultKind = LookupResultKind.NotReferencable; } else { switch (containingMember.Kind) { case SymbolKind.Method: resultKind = LookupResultKind.Viable; thisParam = containingMember.EnclosingThisSymbol(); break; // Fields and properties can't access 'this' since // initializers are run in the constructor case SymbolKind.Field: case SymbolKind.Property: resultKind = LookupResultKind.NotReferencable; thisParam = containingMember.EnclosingThisSymbol() ?? new ThisParameterSymbol(null, containingType); break; default: throw ExceptionUtilities.UnexpectedValue(containingMember.Kind); } } } break; default: thisParam = new ThisParameterSymbol(containingMember as MethodSymbol, typeOfThis); resultKind = LookupResultKind.NotReferencable; break; } return thisParam; } private static void GetSymbolsAndResultKind(BoundUnaryOperator unaryOperator, out bool isDynamic, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols) { UnaryOperatorKind operandType = unaryOperator.OperatorKind.OperandTypes(); isDynamic = unaryOperator.OperatorKind.IsDynamic(); if (operandType == 0 || operandType == UnaryOperatorKind.UserDefined || unaryOperator.ResultKind != LookupResultKind.Viable) { if (!isDynamic) { GetSymbolsAndResultKind(unaryOperator, unaryOperator.MethodOpt, unaryOperator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); } } else { Debug.Assert((object)unaryOperator.MethodOpt == null && unaryOperator.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); UnaryOperatorKind op = unaryOperator.OperatorKind.Operator(); symbols = ImmutableArray.Create<Symbol>(new SynthesizedIntrinsicOperatorSymbol(unaryOperator.Operand.Type.StrippedType(), OperatorFacts.UnaryOperatorNameFromOperatorKind(op), unaryOperator.Type.StrippedType(), unaryOperator.OperatorKind.IsChecked())); resultKind = unaryOperator.ResultKind; } } private static void GetSymbolsAndResultKind(BoundIncrementOperator increment, out bool isDynamic, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols) { UnaryOperatorKind operandType = increment.OperatorKind.OperandTypes(); isDynamic = increment.OperatorKind.IsDynamic(); if (operandType == 0 || operandType == UnaryOperatorKind.UserDefined || increment.ResultKind != LookupResultKind.Viable) { if (!isDynamic) { GetSymbolsAndResultKind(increment, increment.MethodOpt, increment.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); } } else { Debug.Assert((object)increment.MethodOpt == null && increment.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); UnaryOperatorKind op = increment.OperatorKind.Operator(); symbols = ImmutableArray.Create<Symbol>(new SynthesizedIntrinsicOperatorSymbol(increment.Operand.Type.StrippedType(), OperatorFacts.UnaryOperatorNameFromOperatorKind(op), increment.Type.StrippedType(), increment.OperatorKind.IsChecked())); resultKind = increment.ResultKind; } } private static void GetSymbolsAndResultKind(BoundBinaryOperator binaryOperator, out bool isDynamic, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols) { BinaryOperatorKind operandType = binaryOperator.OperatorKind.OperandTypes(); BinaryOperatorKind op = binaryOperator.OperatorKind.Operator(); isDynamic = binaryOperator.OperatorKind.IsDynamic(); if (operandType == 0 || operandType == BinaryOperatorKind.UserDefined || binaryOperator.ResultKind != LookupResultKind.Viable || binaryOperator.OperatorKind.IsLogical()) { if (!isDynamic) { GetSymbolsAndResultKind(binaryOperator, binaryOperator.Method, binaryOperator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); } } else { Debug.Assert((object)binaryOperator.Method == null && binaryOperator.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); if (!isDynamic && (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) && ((binaryOperator.Left.IsLiteralNull() && binaryOperator.Right.Type.IsNullableType()) || (binaryOperator.Right.IsLiteralNull() && binaryOperator.Left.Type.IsNullableType())) && binaryOperator.Type.SpecialType == SpecialType.System_Boolean) { // Comparison of a nullable type with null, return corresponding operator for Object. var objectType = binaryOperator.Type.ContainingAssembly.GetSpecialType(SpecialType.System_Object); symbols = ImmutableArray.Create<Symbol>(new SynthesizedIntrinsicOperatorSymbol(objectType, OperatorFacts.BinaryOperatorNameFromOperatorKind(op), objectType, binaryOperator.Type, binaryOperator.OperatorKind.IsChecked())); } else { symbols = ImmutableArray.Create(GetIntrinsicOperatorSymbol(op, isDynamic, binaryOperator.Left.Type, binaryOperator.Right.Type, binaryOperator.Type, binaryOperator.OperatorKind.IsChecked())); } resultKind = binaryOperator.ResultKind; } } private static Symbol GetIntrinsicOperatorSymbol(BinaryOperatorKind op, bool isDynamic, TypeSymbol leftType, TypeSymbol rightType, TypeSymbol returnType, bool isChecked) { if (!isDynamic) { leftType = leftType.StrippedType(); rightType = rightType.StrippedType(); returnType = returnType.StrippedType(); } else { Debug.Assert(returnType.IsDynamic()); if ((object)leftType == null) { Debug.Assert(rightType.IsDynamic()); leftType = rightType; } else if ((object)rightType == null) { Debug.Assert(leftType.IsDynamic()); rightType = leftType; } } return new SynthesizedIntrinsicOperatorSymbol(leftType, OperatorFacts.BinaryOperatorNameFromOperatorKind(op), rightType, returnType, isChecked); } private static void GetSymbolsAndResultKind(BoundCompoundAssignmentOperator compoundAssignment, out bool isDynamic, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols) { BinaryOperatorKind operandType = compoundAssignment.Operator.Kind.OperandTypes(); BinaryOperatorKind op = compoundAssignment.Operator.Kind.Operator(); isDynamic = compoundAssignment.Operator.Kind.IsDynamic(); if (operandType == 0 || operandType == BinaryOperatorKind.UserDefined || compoundAssignment.ResultKind != LookupResultKind.Viable) { if (!isDynamic) { GetSymbolsAndResultKind(compoundAssignment, compoundAssignment.Operator.Method, compoundAssignment.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); } } else { Debug.Assert((object)compoundAssignment.Operator.Method == null && compoundAssignment.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); symbols = ImmutableArray.Create(GetIntrinsicOperatorSymbol(op, isDynamic, compoundAssignment.Operator.LeftType, compoundAssignment.Operator.RightType, compoundAssignment.Operator.ReturnType, compoundAssignment.Operator.Kind.IsChecked())); resultKind = compoundAssignment.ResultKind; } } private static void GetSymbolsAndResultKind(BoundExpression node, Symbol symbolOpt, ImmutableArray<MethodSymbol> originalCandidates, out ImmutableArray<Symbol> symbols, out LookupResultKind resultKind) { if (!ReferenceEquals(symbolOpt, null)) { symbols = ImmutableArray.Create(symbolOpt); resultKind = node.ResultKind; } else if (!originalCandidates.IsDefault) { symbols = StaticCast<Symbol>.From(originalCandidates); resultKind = node.ResultKind; } else { symbols = ImmutableArray<Symbol>.Empty; resultKind = LookupResultKind.Empty; } } // In cases where we are binding C in "[C(...)]", the bound nodes return the symbol for the type. However, we've // decided that we want this case to return the constructor of the type instead. This affects attributes. // This method checks for this situation and adjusts the syntax and method or property group. private void AdjustSymbolsForObjectCreation( BoundExpression boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols, ref ImmutableArray<Symbol> memberGroup) { NamedTypeSymbol typeSymbol = null; MethodSymbol constructor = null; // Check if boundNode.Syntax is the type-name child of an Attribute. SyntaxNode parentSyntax = boundNodeForSyntacticParent.Syntax; if (parentSyntax != null && parentSyntax == boundNode.Syntax.Parent && parentSyntax.Kind() == SyntaxKind.Attribute && ((AttributeSyntax)parentSyntax).Name == boundNode.Syntax) { var unwrappedSymbols = UnwrapAliases(symbols); switch (boundNodeForSyntacticParent.Kind) { case BoundKind.Attribute: BoundAttribute boundAttribute = (BoundAttribute)boundNodeForSyntacticParent; if (unwrappedSymbols.Length == 1 && unwrappedSymbols[0].Kind == SymbolKind.NamedType) { Debug.Assert(resultKind != LookupResultKind.Viable || TypeSymbol.Equals((TypeSymbol)unwrappedSymbols[0], boundAttribute.Type.GetNonErrorGuess(), TypeCompareKind.ConsiderEverything2)); typeSymbol = (NamedTypeSymbol)unwrappedSymbols[0]; constructor = boundAttribute.Constructor; resultKind = resultKind.WorseResultKind(boundAttribute.ResultKind); } break; case BoundKind.BadExpression: BoundBadExpression boundBadExpression = (BoundBadExpression)boundNodeForSyntacticParent; if (unwrappedSymbols.Length == 1) { resultKind = resultKind.WorseResultKind(boundBadExpression.ResultKind); typeSymbol = unwrappedSymbols[0] as NamedTypeSymbol; } break; default: throw ExceptionUtilities.UnexpectedValue(boundNodeForSyntacticParent.Kind); } AdjustSymbolsForObjectCreation(boundNode, typeSymbol, constructor, binderOpt, ref resultKind, ref symbols, ref memberGroup); } } private void AdjustSymbolsForObjectCreation( BoundNode lowestBoundNode, NamedTypeSymbol typeSymbolOpt, MethodSymbol constructorOpt, Binder binderOpt, ref LookupResultKind resultKind, ref ImmutableArray<Symbol> symbols, ref ImmutableArray<Symbol> memberGroup) { Debug.Assert(lowestBoundNode != null); Debug.Assert(binderOpt != null || IsInTree(lowestBoundNode.Syntax)); if ((object)typeSymbolOpt != null) { Debug.Assert(lowestBoundNode.Syntax != null); // Filter typeSymbol's instance constructors by accessibility. // If all the instance constructors are inaccessible, we retain // all of them for correct semantic info. Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(lowestBoundNode.Syntax)); ImmutableArray<MethodSymbol> candidateConstructors; if (binder != null) { var instanceConstructors = typeSymbolOpt.IsInterfaceType() && (object)typeSymbolOpt.ComImportCoClass != null ? typeSymbolOpt.ComImportCoClass.InstanceConstructors : typeSymbolOpt.InstanceConstructors; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; candidateConstructors = binder.FilterInaccessibleConstructors(instanceConstructors, allowProtectedConstructorsOfBaseType: false, useSiteInfo: ref discardedUseSiteInfo); if ((object)constructorOpt == null ? !candidateConstructors.Any() : !candidateConstructors.Contains(constructorOpt)) { // All instance constructors are inaccessible or if the specified constructor // isn't a candidate, then we retain all of them for correct semantic info. Debug.Assert(resultKind != LookupResultKind.Viable); candidateConstructors = instanceConstructors; } } else { candidateConstructors = ImmutableArray<MethodSymbol>.Empty; } if ((object)constructorOpt != null) { Debug.Assert(candidateConstructors.Contains(constructorOpt)); symbols = ImmutableArray.Create<Symbol>(constructorOpt); } else if (candidateConstructors.Length > 0) { symbols = StaticCast<Symbol>.From(candidateConstructors); Debug.Assert(resultKind != LookupResultKind.Viable); resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); } memberGroup = candidateConstructors.Cast<MethodSymbol, Symbol>(); } } /// <summary> /// Returns a list of accessible, non-hidden indexers that could be invoked with the given expression /// as a receiver. /// </summary> /// <remarks> /// If the given expression is an indexer access, then this method will return the list of indexers /// that could be invoked on the result, not the list of indexers that were considered. /// </remarks> private ImmutableArray<IPropertySymbol> GetIndexerGroupSemanticSymbols(BoundExpression boundNode, Binder binderOpt) { Debug.Assert(binderOpt != null || IsInTree(boundNode.Syntax)); TypeSymbol type = boundNode.Type; if (ReferenceEquals(type, null) || type.IsStatic) { return ImmutableArray<IPropertySymbol>.Empty; } Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); var symbols = ArrayBuilder<ISymbol>.GetInstance(); AppendSymbolsWithNameAndArity(symbols, WellKnownMemberNames.Indexer, 0, binder, type, LookupOptions.MustBeInstance); if (symbols.Count == 0) { symbols.Free(); return ImmutableArray<IPropertySymbol>.Empty; } return FilterOverriddenOrHiddenIndexers(symbols.ToImmutableAndFree()); } private static ImmutableArray<IPropertySymbol> FilterOverriddenOrHiddenIndexers(ImmutableArray<ISymbol> symbols) { PooledHashSet<Symbol> hiddenSymbols = null; foreach (ISymbol iSymbol in symbols) { Symbol symbol = iSymbol.GetSymbol(); Debug.Assert(symbol.IsIndexer(), "Only indexers can have name " + WellKnownMemberNames.Indexer); PropertySymbol indexer = (PropertySymbol)symbol; OverriddenOrHiddenMembersResult overriddenOrHiddenMembers = indexer.OverriddenOrHiddenMembers; foreach (Symbol overridden in overriddenOrHiddenMembers.OverriddenMembers) { if (hiddenSymbols == null) { hiddenSymbols = PooledHashSet<Symbol>.GetInstance(); } hiddenSymbols.Add(overridden); } // Don't worry about RuntimeOverriddenMembers - this check is for the API, which // should reflect the C# semantics. foreach (Symbol hidden in overriddenOrHiddenMembers.HiddenMembers) { if (hiddenSymbols == null) { hiddenSymbols = PooledHashSet<Symbol>.GetInstance(); } hiddenSymbols.Add(hidden); } } var builder = ArrayBuilder<IPropertySymbol>.GetInstance(); foreach (IPropertySymbol indexer in symbols) { if (hiddenSymbols == null || !hiddenSymbols.Contains(indexer.GetSymbol())) { builder.Add(indexer); } } hiddenSymbols?.Free(); return builder.ToImmutableAndFree(); } /// <remarks> /// The method group can contain "duplicate" symbols that we do not want to display in the IDE analysis. /// /// For example, there could be an overriding virtual method and the method it overrides both in /// the method group. This, strictly speaking, is a violation of the C# specification because we are /// supposed to strip out overriding methods from the method group before overload resolution; overload /// resolution is supposed to treat overridden methods as being methods of the less derived type. However, /// in the IDE we want to display information about the overriding method, not the overridden method, and /// therefore we leave both in the method group. The overload resolution algorithm has been written /// to handle this departure from the specification. /// /// Similarly, we might have two methods in the method group where one is a "new" method that hides /// another. Again, in overload resolution this would be handled by the rule that says that methods /// declared on more derived types take priority over methods declared on less derived types. Both /// will be in the method group, but in the IDE we want to only display information about the /// hiding method, not the hidden method. /// /// We can also have "diamond" inheritance of interfaces leading to multiple copies of the same /// method ending up in the method group: /// /// interface IB { void M(); } /// interface IL : IB {} /// interface IR : IB {} /// interface ID : IL, IR {} /// ... /// id.M(); /// /// We only want to display one symbol in the IDE, even if the member lookup algorithm is unsophisticated /// and puts IB.M in the member group twice. (Again, this is a mild spec violation since a method group /// is supposed to be a set, without duplicates.) /// /// Finally, the interaction of multiple inheritance of interfaces and hiding can lead to some subtle /// situations. Suppose we make a slight modification to the scenario above: /// /// interface IL : IB { new void M(); } /// /// Again, we only want to display one symbol in the method group. The fact that there is a "path" /// to IB.M from ID via IR is irrelevant; if the symbol IB.M is hidden by IL.M then it is hidden /// in ID, period. /// </remarks> private static ImmutableArray<MethodSymbol> FilterOverriddenOrHiddenMethods(ImmutableArray<MethodSymbol> methods) { // Optimization, not required for correctness. if (methods.Length <= 1) { return methods; } HashSet<Symbol> hiddenSymbols = new HashSet<Symbol>(); foreach (MethodSymbol method in methods) { OverriddenOrHiddenMembersResult overriddenOrHiddenMembers = method.OverriddenOrHiddenMembers; foreach (Symbol overridden in overriddenOrHiddenMembers.OverriddenMembers) { hiddenSymbols.Add(overridden); } // Don't worry about RuntimeOverriddenMembers - this check is for the API, which // should reflect the C# semantics. foreach (Symbol hidden in overriddenOrHiddenMembers.HiddenMembers) { hiddenSymbols.Add(hidden); } } return methods.WhereAsArray((m, hiddenSymbols) => !hiddenSymbols.Contains(m), hiddenSymbols); } // Get the symbols and possible method group associated with a method group bound node, as // they should be exposed through GetSemanticInfo. // NB: It is not safe to pass a null binderOpt during speculative binding. // // If the parent node of the method group syntax node provides information (such as arguments) // that allows us to return more specific symbols (a specific overload or applicable candidates) // we return these. The complete set of symbols of the method group is then returned in methodGroup parameter. private ImmutableArray<Symbol> GetMethodGroupSemanticSymbols( BoundMethodGroup boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, out LookupResultKind resultKind, out bool isDynamic, out ImmutableArray<Symbol> methodGroup) { Debug.Assert(binderOpt != null || IsInTree(boundNode.Syntax)); ImmutableArray<Symbol> symbols = ImmutableArray<Symbol>.Empty; resultKind = boundNode.ResultKind; if (resultKind == LookupResultKind.Empty) { resultKind = LookupResultKind.Viable; } isDynamic = false; // The method group needs filtering. Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); methodGroup = GetReducedAndFilteredMethodGroupSymbols(binder, boundNode).Cast<MethodSymbol, Symbol>(); // We want to get the actual node chosen by overload resolution, if possible. if (boundNodeForSyntacticParent != null) { switch (boundNodeForSyntacticParent.Kind) { case BoundKind.Call: // If we are looking for info on M in M(args), we want the symbol that overload resolution // chose for M. var call = (BoundCall)boundNodeForSyntacticParent; InvocationExpressionSyntax invocation = call.Syntax as InvocationExpressionSyntax; if (invocation != null && invocation.Expression.SkipParens() == ((ExpressionSyntax)boundNode.Syntax).SkipParens() && (object)call.Method != null) { if (call.OriginalMethodsOpt.IsDefault) { // Overload resolution succeeded. symbols = CreateReducedExtensionMethodIfPossible(call); resultKind = LookupResultKind.Viable; } else { resultKind = call.ResultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); symbols = StaticCast<Symbol>.From(CreateReducedExtensionMethodsFromOriginalsIfNecessary(call, Compilation)); } } break; case BoundKind.DelegateCreationExpression: // If we are looking for info on "M" in "new Action(M)" // we want to get the symbol that overload resolution chose for M, not the whole method group M. var delegateCreation = (BoundDelegateCreationExpression)boundNodeForSyntacticParent; if (delegateCreation.Argument == boundNode && (object)delegateCreation.MethodOpt != null) { symbols = CreateReducedExtensionMethodIfPossible(delegateCreation, boundNode.ReceiverOpt); } break; case BoundKind.Conversion: // If we are looking for info on "M" in "(Action)M" // we want to get the symbol that overload resolution chose for M, not the whole method group M. var conversion = (BoundConversion)boundNodeForSyntacticParent; var method = conversion.SymbolOpt; if ((object)method != null) { Debug.Assert(conversion.ConversionKind == ConversionKind.MethodGroup); if (conversion.IsExtensionMethod) { method = ReducedExtensionMethodSymbol.Create(method); } symbols = ImmutableArray.Create((Symbol)method); resultKind = conversion.ResultKind; } else { goto default; } break; case BoundKind.DynamicInvocation: var dynamicInvocation = (BoundDynamicInvocation)boundNodeForSyntacticParent; symbols = dynamicInvocation.ApplicableMethods.Cast<MethodSymbol, Symbol>(); isDynamic = true; break; case BoundKind.BadExpression: // If the bad expression has symbol(s) from this method group, it better indicates any problems. ImmutableArray<Symbol> myMethodGroup = methodGroup; symbols = ((BoundBadExpression)boundNodeForSyntacticParent).Symbols.WhereAsArray((sym, myMethodGroup) => myMethodGroup.Contains(sym), myMethodGroup); if (symbols.Any()) { resultKind = ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind; } break; case BoundKind.NameOfOperator: symbols = methodGroup; resultKind = resultKind.WorseResultKind(LookupResultKind.MemberGroup); break; default: symbols = methodGroup; if (symbols.Length > 0) { resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); } break; } } else if (methodGroup.Length == 1 && !boundNode.HasAnyErrors) { // During speculative binding, there won't be a parent bound node. The parent bound // node may also be absent if the syntactic parent has errors or if one is simply // not specified (see SemanticModel.GetSymbolInfoForNode). However, if there's exactly // one candidate, then we should probably succeed. symbols = methodGroup; if (symbols.Length > 0) { resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); } } if (!symbols.Any()) { // If we didn't find a better set of symbols, then assume this is a method group that didn't // get resolved. Return all members of the method group, with a resultKind of OverloadResolutionFailure // (unless the method group already has a worse result kind). symbols = methodGroup; if (!isDynamic && resultKind > LookupResultKind.OverloadResolutionFailure) { resultKind = LookupResultKind.OverloadResolutionFailure; } } return symbols; } // NB: It is not safe to pass a null binderOpt during speculative binding. private ImmutableArray<Symbol> GetPropertyGroupSemanticSymbols( BoundPropertyGroup boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, out LookupResultKind resultKind, out ImmutableArray<Symbol> propertyGroup) { Debug.Assert(binderOpt != null || IsInTree(boundNode.Syntax)); ImmutableArray<Symbol> symbols = ImmutableArray<Symbol>.Empty; resultKind = boundNode.ResultKind; if (resultKind == LookupResultKind.Empty) { resultKind = LookupResultKind.Viable; } // The property group needs filtering. propertyGroup = boundNode.Properties.Cast<PropertySymbol, Symbol>(); // We want to get the actual node chosen by overload resolution, if possible. if (boundNodeForSyntacticParent != null) { switch (boundNodeForSyntacticParent.Kind) { case BoundKind.IndexerAccess: // If we are looking for info on P in P[args], we want the symbol that overload resolution // chose for P. var indexer = (BoundIndexerAccess)boundNodeForSyntacticParent; var elementAccess = indexer.Syntax as ElementAccessExpressionSyntax; if (elementAccess != null && elementAccess.Expression == boundNode.Syntax && (object)indexer.Indexer != null) { if (indexer.OriginalIndexersOpt.IsDefault) { // Overload resolution succeeded. symbols = ImmutableArray.Create<Symbol>(indexer.Indexer); resultKind = LookupResultKind.Viable; } else { resultKind = indexer.ResultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); symbols = StaticCast<Symbol>.From(indexer.OriginalIndexersOpt); } } break; case BoundKind.BadExpression: // If the bad expression has symbol(s) from this property group, it better indicates any problems. ImmutableArray<Symbol> myPropertyGroup = propertyGroup; symbols = ((BoundBadExpression)boundNodeForSyntacticParent).Symbols.WhereAsArray((sym, myPropertyGroup) => myPropertyGroup.Contains(sym), myPropertyGroup); if (symbols.Any()) { resultKind = ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind; } break; } } else if (propertyGroup.Length == 1 && !boundNode.HasAnyErrors) { // During speculative binding, there won't be a parent bound node. The parent bound // node may also be absent if the syntactic parent has errors or if one is simply // not specified (see SemanticModel.GetSymbolInfoForNode). However, if there's exactly // one candidate, then we should probably succeed. // If we're speculatively binding and there's exactly one candidate, then we should probably succeed. symbols = propertyGroup; } if (!symbols.Any()) { // If we didn't find a better set of symbols, then assume this is a property group that didn't // get resolved. Return all members of the property group, with a resultKind of OverloadResolutionFailure // (unless the property group already has a worse result kind). symbols = propertyGroup; if (resultKind > LookupResultKind.OverloadResolutionFailure) { resultKind = LookupResultKind.OverloadResolutionFailure; } } return symbols; } /// <summary> /// Get the semantic info of a named argument in an invocation-like expression (e.g. `x` in `M(x: 3)`) /// or the name in a Subpattern (e.g. either `Name` in `e is (Name: 3){Name: 3}`). /// </summary> private SymbolInfo GetNamedArgumentSymbolInfo(IdentifierNameSyntax identifierNameSyntax, CancellationToken cancellationToken) { Debug.Assert(SyntaxFacts.IsNamedArgumentName(identifierNameSyntax)); // Argument names do not have bound nodes associated with them, so we cannot use the usual // GetSymbolInfo mechanism. Instead, we just do the following: // 1. Find the containing invocation. // 2. Call GetSymbolInfo on that. // 3. For each method or indexer in the return semantic info, find the argument // with the given name (if any). // 4. Use the ResultKind in that semantic info and any symbols to create the semantic info // for the named argument. // 5. Type is always null, as is constant value. string argumentName = identifierNameSyntax.Identifier.ValueText; if (argumentName.Length == 0) return SymbolInfo.None; // missing name. // argument could be an argument of a tuple expression // var x = (Identifier: 1, AnotherIdentifier: 2); var parent3 = identifierNameSyntax.Parent.Parent.Parent; if (parent3.IsKind(SyntaxKind.TupleExpression)) { var tupleArgument = (ArgumentSyntax)identifierNameSyntax.Parent.Parent; var tupleElement = GetDeclaredSymbol(tupleArgument, cancellationToken); return (object)tupleElement == null ? SymbolInfo.None : new SymbolInfo(tupleElement, ImmutableArray<ISymbol>.Empty, CandidateReason.None); } if (parent3.IsKind(SyntaxKind.PropertyPatternClause) || parent3.IsKind(SyntaxKind.PositionalPatternClause)) { return GetSymbolInfoWorker(identifierNameSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken); } CSharpSyntaxNode containingInvocation = parent3.Parent; SymbolInfo containingInvocationInfo = GetSymbolInfoWorker(containingInvocation, SymbolInfoOptions.PreferConstructorsToType | SymbolInfoOptions.ResolveAliases, cancellationToken); if ((object)containingInvocationInfo.Symbol != null) { ParameterSymbol param = FindNamedParameter(containingInvocationInfo.Symbol.GetSymbol().GetParameters(), argumentName); return (object)param == null ? SymbolInfo.None : new SymbolInfo(param.GetPublicSymbol(), ImmutableArray<ISymbol>.Empty, CandidateReason.None); } else { var symbols = ArrayBuilder<ISymbol>.GetInstance(); foreach (ISymbol invocationSym in containingInvocationInfo.CandidateSymbols) { switch (invocationSym.Kind) { case SymbolKind.Method: case SymbolKind.Property: break; // Could have parameters. default: continue; // Definitely doesn't have parameters. } ParameterSymbol param = FindNamedParameter(invocationSym.GetSymbol().GetParameters(), argumentName); if ((object)param != null) { symbols.Add(param.GetPublicSymbol()); } } if (symbols.Count == 0) { symbols.Free(); return SymbolInfo.None; } else { return new SymbolInfo(null, symbols.ToImmutableAndFree(), containingInvocationInfo.CandidateReason); } } } /// <summary> /// Find the first parameter named "argumentName". /// </summary> private static ParameterSymbol FindNamedParameter(ImmutableArray<ParameterSymbol> parameters, string argumentName) { foreach (ParameterSymbol param in parameters) { if (param.Name == argumentName) return param; } return null; } internal static ImmutableArray<MethodSymbol> GetReducedAndFilteredMethodGroupSymbols(Binder binder, BoundMethodGroup node) { var methods = ArrayBuilder<MethodSymbol>.GetInstance(); var filteredMethods = ArrayBuilder<MethodSymbol>.GetInstance(); var resultKind = LookupResultKind.Empty; var typeArguments = node.TypeArgumentsOpt; // Non-extension methods. if (node.Methods.Any()) { // This is the only place we care about overridden/hidden methods. If there aren't methods // in the method group, there's only one fallback candidate and extension methods never override // or hide instance methods or other extension methods. ImmutableArray<MethodSymbol> nonHiddenMethods = FilterOverriddenOrHiddenMethods(node.Methods); Debug.Assert(nonHiddenMethods.Any()); // Something must be hiding, so can't all be hidden. foreach (var method in nonHiddenMethods) { MergeReducedAndFilteredMethodGroupSymbol( methods, filteredMethods, new SingleLookupResult(node.ResultKind, method, node.LookupError), typeArguments, null, ref resultKind, binder.Compilation); } } else { var otherSymbol = node.LookupSymbolOpt; if (((object)otherSymbol != null) && (otherSymbol.Kind == SymbolKind.Method)) { MergeReducedAndFilteredMethodGroupSymbol( methods, filteredMethods, new SingleLookupResult(node.ResultKind, otherSymbol, node.LookupError), typeArguments, null, ref resultKind, binder.Compilation); } } var receiver = node.ReceiverOpt; var name = node.Name; // Extension methods, all scopes. if (node.SearchExtensionMethods) { Debug.Assert(receiver != null); int arity; LookupOptions options; if (typeArguments.IsDefault) { arity = 0; options = LookupOptions.AllMethodsOnArityZero; } else { arity = typeArguments.Length; options = LookupOptions.Default; } binder = binder.WithAdditionalFlags(BinderFlags.SemanticModel); foreach (var scope in new ExtensionMethodScopes(binder)) { var extensionMethods = ArrayBuilder<MethodSymbol>.GetInstance(); var otherBinder = scope.Binder; otherBinder.GetCandidateExtensionMethods(extensionMethods, name, arity, options, originalBinder: binder); foreach (var method in extensionMethods) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; MergeReducedAndFilteredMethodGroupSymbol( methods, filteredMethods, binder.CheckViability(method, arity, options, accessThroughType: null, diagnose: false, useSiteInfo: ref discardedUseSiteInfo), typeArguments, receiver.Type, ref resultKind, binder.Compilation); } extensionMethods.Free(); } } methods.Free(); return filteredMethods.ToImmutableAndFree(); } // Reduce extension methods to their reduced form, and remove: // a) Extension methods are aren't applicable to receiverType // including constraint checking. // b) Duplicate methods // c) Methods that are hidden or overridden by another method in the group. private static bool AddReducedAndFilteredMethodGroupSymbol( ArrayBuilder<MethodSymbol> methods, ArrayBuilder<MethodSymbol> filteredMethods, MethodSymbol method, ImmutableArray<TypeWithAnnotations> typeArguments, TypeSymbol receiverType, CSharpCompilation compilation) { MethodSymbol constructedMethod; if (!typeArguments.IsDefaultOrEmpty && method.Arity == typeArguments.Length) { constructedMethod = method.Construct(typeArguments); Debug.Assert((object)constructedMethod != null); } else { constructedMethod = method; } if ((object)receiverType != null) { constructedMethod = constructedMethod.ReduceExtensionMethod(receiverType, compilation); if ((object)constructedMethod == null) { return false; } } // Don't add exact duplicates. if (filteredMethods.Contains(constructedMethod)) { return false; } methods.Add(method); filteredMethods.Add(constructedMethod); return true; } private static void MergeReducedAndFilteredMethodGroupSymbol( ArrayBuilder<MethodSymbol> methods, ArrayBuilder<MethodSymbol> filteredMethods, SingleLookupResult singleResult, ImmutableArray<TypeWithAnnotations> typeArguments, TypeSymbol receiverType, ref LookupResultKind resultKind, CSharpCompilation compilation) { Debug.Assert(singleResult.Kind != LookupResultKind.Empty); Debug.Assert((object)singleResult.Symbol != null); Debug.Assert(singleResult.Symbol.Kind == SymbolKind.Method); var singleKind = singleResult.Kind; if (resultKind > singleKind) { return; } else if (resultKind < singleKind) { methods.Clear(); filteredMethods.Clear(); resultKind = LookupResultKind.Empty; } var method = (MethodSymbol)singleResult.Symbol; if (AddReducedAndFilteredMethodGroupSymbol(methods, filteredMethods, method, typeArguments, receiverType, compilation)) { Debug.Assert(methods.Count > 0); if (resultKind < singleKind) { resultKind = singleKind; } } Debug.Assert((methods.Count == 0) == (resultKind == LookupResultKind.Empty)); Debug.Assert(methods.Count == filteredMethods.Count); } /// <summary> /// If the call represents an extension method invocation with an explicit receiver, return the original /// methods as ReducedExtensionMethodSymbols. Otherwise, return the original methods unchanged. /// </summary> private static ImmutableArray<MethodSymbol> CreateReducedExtensionMethodsFromOriginalsIfNecessary(BoundCall call, CSharpCompilation compilation) { var methods = call.OriginalMethodsOpt; TypeSymbol extensionThisType = null; Debug.Assert(!methods.IsDefault); if (call.InvokedAsExtensionMethod) { // If the call was invoked as an extension method, the receiver // should be non-null and all methods should be extension methods. if (call.ReceiverOpt != null) { extensionThisType = call.ReceiverOpt.Type; } else { extensionThisType = call.Arguments[0].Type; } Debug.Assert((object)extensionThisType != null); } var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); var filteredMethodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var method in FilterOverriddenOrHiddenMethods(methods)) { AddReducedAndFilteredMethodGroupSymbol(methodBuilder, filteredMethodBuilder, method, default(ImmutableArray<TypeWithAnnotations>), extensionThisType, compilation); } methodBuilder.Free(); return filteredMethodBuilder.ToImmutableAndFree(); } /// <summary> /// If the call represents an extension method with an explicit receiver, return a /// ReducedExtensionMethodSymbol if it can be constructed. Otherwise, return the /// original call method. /// </summary> private ImmutableArray<Symbol> CreateReducedExtensionMethodIfPossible(BoundCall call) { var method = call.Method; Debug.Assert((object)method != null); if (call.InvokedAsExtensionMethod && method.IsExtensionMethod && method.MethodKind != MethodKind.ReducedExtension) { Debug.Assert(call.Arguments.Length > 0); BoundExpression receiver = call.Arguments[0]; MethodSymbol reduced = method.ReduceExtensionMethod(receiver.Type, Compilation); // If the extension method can't be applied to the receiver of the given // type, we should also return the original call method. method = reduced ?? method; } return ImmutableArray.Create<Symbol>(method); } private ImmutableArray<Symbol> CreateReducedExtensionMethodIfPossible(BoundDelegateCreationExpression delegateCreation, BoundExpression receiverOpt) { var method = delegateCreation.MethodOpt; Debug.Assert((object)method != null); if (delegateCreation.IsExtensionMethod && method.IsExtensionMethod && (receiverOpt != null)) { MethodSymbol reduced = method.ReduceExtensionMethod(receiverOpt.Type, Compilation); method = reduced ?? method; } return ImmutableArray.Create<Symbol>(method); } /// <summary> /// Gets for each statement info. /// </summary> /// <param name="node">The node.</param> public abstract ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node); /// <summary> /// Gets for each statement info. /// </summary> /// <param name="node">The node.</param> public abstract ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node); /// <summary> /// Gets deconstruction assignment info. /// </summary> /// <param name="node">The node.</param> public abstract DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node); /// <summary> /// Gets deconstruction foreach info. /// </summary> /// <param name="node">The node.</param> public abstract DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node); /// <summary> /// Gets await expression info. /// </summary> /// <param name="node">The node.</param> public abstract AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node); /// <summary> /// If the given node is within a preprocessing directive, gets the preprocessing symbol info for it. /// </summary> /// <param name="node">Preprocessing symbol identifier node.</param> public PreprocessingSymbolInfo GetPreprocessingSymbolInfo(IdentifierNameSyntax node) { CheckSyntaxNode(node); if (node.Ancestors().Any(n => SyntaxFacts.IsPreprocessorDirective(n.Kind()))) { bool isDefined = this.SyntaxTree.IsPreprocessorSymbolDefined(node.Identifier.ValueText, node.Identifier.SpanStart); return new PreprocessingSymbolInfo(new Symbols.PublicModel.PreprocessingSymbol(node.Identifier.ValueText), isDefined); } return PreprocessingSymbolInfo.None; } /// <summary> /// Options to control the internal working of GetSymbolInfoWorker. Not currently exposed /// to public clients, but could be if desired. /// </summary> [Flags] internal enum SymbolInfoOptions { /// <summary> /// When binding "C" new C(...), return the type C and do not return information about /// which constructor was bound to. Bind "new C(...)" to get information about which constructor /// was chosen. /// </summary> PreferTypeToConstructors = 0x1, /// <summary> /// When binding "C" new C(...), return the constructor of C that was bound to, if C unambiguously /// binds to a single type with at least one constructor. /// </summary> PreferConstructorsToType = 0x2, /// <summary> /// When binding a name X that was declared with a "using X=OtherTypeOrNamespace", return OtherTypeOrNamespace. /// </summary> ResolveAliases = 0x4, /// <summary> /// When binding a name X that was declared with a "using X=OtherTypeOrNamespace", return the alias symbol X. /// </summary> PreserveAliases = 0x8, // Default Options. DefaultOptions = PreferConstructorsToType | ResolveAliases } internal static void ValidateSymbolInfoOptions(SymbolInfoOptions options) { Debug.Assert(((options & SymbolInfoOptions.PreferConstructorsToType) != 0) != ((options & SymbolInfoOptions.PreferTypeToConstructors) != 0), "Options are mutually exclusive"); Debug.Assert(((options & SymbolInfoOptions.ResolveAliases) != 0) != ((options & SymbolInfoOptions.PreserveAliases) != 0), "Options are mutually exclusive"); } /// <summary> /// Given a position in the SyntaxTree for this SemanticModel returns the innermost /// NamedType that the position is considered inside of. /// </summary> public new ISymbol GetEnclosingSymbol( int position, CancellationToken cancellationToken = default(CancellationToken)) { position = CheckAndAdjustPosition(position); var binder = GetEnclosingBinder(position); return binder == null ? null : binder.ContainingMemberOrLambda.GetPublicSymbol(); } #region SemanticModel Members public sealed override string Language { get { return LanguageNames.CSharp; } } protected sealed override Compilation CompilationCore { get { return this.Compilation; } } protected sealed override SemanticModel ParentModelCore { get { return this.ParentModel; } } protected sealed override SyntaxTree SyntaxTreeCore { get { return this.SyntaxTree; } } protected sealed override SyntaxNode RootCore => this.Root; private SymbolInfo GetSymbolInfoFromNode(SyntaxNode node, CancellationToken cancellationToken) { switch (node) { case null: throw new ArgumentNullException(nameof(node)); case ExpressionSyntax expression: return this.GetSymbolInfo(expression, cancellationToken); case ConstructorInitializerSyntax initializer: return this.GetSymbolInfo(initializer, cancellationToken); case PrimaryConstructorBaseTypeSyntax initializer: return this.GetSymbolInfo(initializer, cancellationToken); case AttributeSyntax attribute: return this.GetSymbolInfo(attribute, cancellationToken); case CrefSyntax cref: return this.GetSymbolInfo(cref, cancellationToken); case SelectOrGroupClauseSyntax selectOrGroupClause: return this.GetSymbolInfo(selectOrGroupClause, cancellationToken); case OrderingSyntax orderingSyntax: return this.GetSymbolInfo(orderingSyntax, cancellationToken); case PositionalPatternClauseSyntax ppcSyntax: return this.GetSymbolInfo(ppcSyntax, cancellationToken); } return SymbolInfo.None; } private TypeInfo GetTypeInfoFromNode(SyntaxNode node, CancellationToken cancellationToken) { switch (node) { case null: throw new ArgumentNullException(nameof(node)); case ExpressionSyntax expression: return this.GetTypeInfo(expression, cancellationToken); case ConstructorInitializerSyntax initializer: return this.GetTypeInfo(initializer, cancellationToken); case AttributeSyntax attribute: return this.GetTypeInfo(attribute, cancellationToken); case SelectOrGroupClauseSyntax selectOrGroupClause: return this.GetTypeInfo(selectOrGroupClause, cancellationToken); case PatternSyntax pattern: return this.GetTypeInfo(pattern, cancellationToken); } return CSharpTypeInfo.None; } private ImmutableArray<ISymbol> GetMemberGroupFromNode(SyntaxNode node, CancellationToken cancellationToken) { switch (node) { case null: throw new ArgumentNullException(nameof(node)); case ExpressionSyntax expression: return this.GetMemberGroup(expression, cancellationToken); case ConstructorInitializerSyntax initializer: return this.GetMemberGroup(initializer, cancellationToken); case AttributeSyntax attribute: return this.GetMemberGroup(attribute, cancellationToken); } return ImmutableArray<ISymbol>.Empty; } protected sealed override ImmutableArray<ISymbol> GetMemberGroupCore(SyntaxNode node, CancellationToken cancellationToken) { var methodGroup = this.GetMemberGroupFromNode(node, cancellationToken); return StaticCast<ISymbol>.From(methodGroup); } protected sealed override SymbolInfo GetSpeculativeSymbolInfoCore(int position, SyntaxNode node, SpeculativeBindingOption bindingOption) { switch (node) { case ExpressionSyntax expression: return GetSpeculativeSymbolInfo(position, expression, bindingOption); case ConstructorInitializerSyntax initializer: return GetSpeculativeSymbolInfo(position, initializer); case PrimaryConstructorBaseTypeSyntax initializer: return GetSpeculativeSymbolInfo(position, initializer); case AttributeSyntax attribute: return GetSpeculativeSymbolInfo(position, attribute); case CrefSyntax cref: return GetSpeculativeSymbolInfo(position, cref); } return SymbolInfo.None; } protected sealed override TypeInfo GetSpeculativeTypeInfoCore(int position, SyntaxNode node, SpeculativeBindingOption bindingOption) { return node is ExpressionSyntax expression ? GetSpeculativeTypeInfo(position, expression, bindingOption) : CSharpTypeInfo.None; } protected sealed override IAliasSymbol GetSpeculativeAliasInfoCore(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption) { return nameSyntax is IdentifierNameSyntax identifier ? GetSpeculativeAliasInfo(position, identifier, bindingOption) : null; } protected sealed override SymbolInfo GetSymbolInfoCore(SyntaxNode node, CancellationToken cancellationToken) { return this.GetSymbolInfoFromNode(node, cancellationToken); } protected sealed override TypeInfo GetTypeInfoCore(SyntaxNode node, CancellationToken cancellationToken) { return this.GetTypeInfoFromNode(node, cancellationToken); } protected sealed override IAliasSymbol GetAliasInfoCore(SyntaxNode node, CancellationToken cancellationToken) { return node is IdentifierNameSyntax nameSyntax ? GetAliasInfo(nameSyntax, cancellationToken) : null; } protected sealed override PreprocessingSymbolInfo GetPreprocessingSymbolInfoCore(SyntaxNode node) { return node is IdentifierNameSyntax nameSyntax ? GetPreprocessingSymbolInfo(nameSyntax) : PreprocessingSymbolInfo.None; } protected sealed override ISymbol GetDeclaredSymbolCore(SyntaxNode node, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); switch (node) { case AccessorDeclarationSyntax accessor: return this.GetDeclaredSymbol(accessor, cancellationToken); case BaseTypeDeclarationSyntax type: return this.GetDeclaredSymbol(type, cancellationToken); case QueryClauseSyntax clause: return this.GetDeclaredSymbol(clause, cancellationToken); case MemberDeclarationSyntax member: return this.GetDeclaredSymbol(member, cancellationToken); } switch (node.Kind()) { case SyntaxKind.LocalFunctionStatement: return this.GetDeclaredSymbol((LocalFunctionStatementSyntax)node, cancellationToken); case SyntaxKind.LabeledStatement: return this.GetDeclaredSymbol((LabeledStatementSyntax)node, cancellationToken); case SyntaxKind.CaseSwitchLabel: case SyntaxKind.DefaultSwitchLabel: return this.GetDeclaredSymbol((SwitchLabelSyntax)node, cancellationToken); case SyntaxKind.AnonymousObjectCreationExpression: return this.GetDeclaredSymbol((AnonymousObjectCreationExpressionSyntax)node, cancellationToken); case SyntaxKind.AnonymousObjectMemberDeclarator: return this.GetDeclaredSymbol((AnonymousObjectMemberDeclaratorSyntax)node, cancellationToken); case SyntaxKind.TupleExpression: return this.GetDeclaredSymbol((TupleExpressionSyntax)node, cancellationToken); case SyntaxKind.Argument: return this.GetDeclaredSymbol((ArgumentSyntax)node, cancellationToken); case SyntaxKind.VariableDeclarator: return this.GetDeclaredSymbol((VariableDeclaratorSyntax)node, cancellationToken); case SyntaxKind.SingleVariableDesignation: return this.GetDeclaredSymbol((SingleVariableDesignationSyntax)node, cancellationToken); case SyntaxKind.TupleElement: return this.GetDeclaredSymbol((TupleElementSyntax)node, cancellationToken); case SyntaxKind.NamespaceDeclaration: return this.GetDeclaredSymbol((NamespaceDeclarationSyntax)node, cancellationToken); case SyntaxKind.FileScopedNamespaceDeclaration: return this.GetDeclaredSymbol((FileScopedNamespaceDeclarationSyntax)node, cancellationToken); case SyntaxKind.Parameter: return this.GetDeclaredSymbol((ParameterSyntax)node, cancellationToken); case SyntaxKind.TypeParameter: return this.GetDeclaredSymbol((TypeParameterSyntax)node, cancellationToken); case SyntaxKind.UsingDirective: var usingDirective = (UsingDirectiveSyntax)node; if (usingDirective.Alias == null) { break; } return this.GetDeclaredSymbol(usingDirective, cancellationToken); case SyntaxKind.ForEachStatement: return this.GetDeclaredSymbol((ForEachStatementSyntax)node, cancellationToken); case SyntaxKind.CatchDeclaration: return this.GetDeclaredSymbol((CatchDeclarationSyntax)node, cancellationToken); case SyntaxKind.JoinIntoClause: return this.GetDeclaredSymbol((JoinIntoClauseSyntax)node, cancellationToken); case SyntaxKind.QueryContinuation: return this.GetDeclaredSymbol((QueryContinuationSyntax)node, cancellationToken); case SyntaxKind.CompilationUnit: return this.GetDeclaredSymbol((CompilationUnitSyntax)node, cancellationToken); } return null; } /// <summary> /// Given a tuple element syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a tuple element.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public ISymbol GetDeclaredSymbol(TupleElementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Parent is TupleTypeSyntax tupleTypeSyntax) { return (GetSymbolInfo(tupleTypeSyntax, cancellationToken).Symbol.GetSymbol() as NamedTypeSymbol)?.TupleElements.ElementAtOrDefault(tupleTypeSyntax.Elements.IndexOf(declarationSyntax)).GetPublicSymbol(); } return null; } protected sealed override ImmutableArray<ISymbol> GetDeclaredSymbolsCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (declaration is BaseFieldDeclarationSyntax field) { return this.GetDeclaredSymbols(field, cancellationToken); } var symbol = GetDeclaredSymbolCore(declaration, cancellationToken); if (symbol != null) { return ImmutableArray.Create(symbol); } return ImmutableArray.Create<ISymbol>(); } internal override void ComputeDeclarationsInSpan(TextSpan span, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken) { CSharpDeclarationComputer.ComputeDeclarationsInSpan(this, span, getSymbol, builder, cancellationToken); } internal override void ComputeDeclarationsInNode(SyntaxNode node, ISymbol associatedSymbol, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken, int? levelsToCompute = null) { CSharpDeclarationComputer.ComputeDeclarationsInNode(this, associatedSymbol, node, getSymbol, builder, cancellationToken, levelsToCompute); } internal abstract override Func<SyntaxNode, bool> GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol); protected internal override SyntaxNode GetTopmostNodeForDiagnosticAnalysis(ISymbol symbol, SyntaxNode declaringSyntax) { switch (symbol.Kind) { case SymbolKind.Event: // for field-like events case SymbolKind.Field: var fieldDecl = declaringSyntax.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); if (fieldDecl != null) { return fieldDecl; } break; } return declaringSyntax; } protected sealed override ImmutableArray<ISymbol> LookupSymbolsCore(int position, INamespaceOrTypeSymbol container, string name, bool includeReducedExtensionMethods) { return LookupSymbols(position, container.EnsureCSharpSymbolOrNull(nameof(container)), name, includeReducedExtensionMethods); } protected sealed override ImmutableArray<ISymbol> LookupBaseMembersCore(int position, string name) { return LookupBaseMembers(position, name); } protected sealed override ImmutableArray<ISymbol> LookupStaticMembersCore(int position, INamespaceOrTypeSymbol container, string name) { return LookupStaticMembers(position, container.EnsureCSharpSymbolOrNull(nameof(container)), name); } protected sealed override ImmutableArray<ISymbol> LookupNamespacesAndTypesCore(int position, INamespaceOrTypeSymbol container, string name) { return LookupNamespacesAndTypes(position, container.EnsureCSharpSymbolOrNull(nameof(container)), name); } protected sealed override ImmutableArray<ISymbol> LookupLabelsCore(int position, string name) { return LookupLabels(position, name); } protected sealed override ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement) { if (firstStatement == null) { throw new ArgumentNullException(nameof(firstStatement)); } if (lastStatement == null) { throw new ArgumentNullException(nameof(lastStatement)); } if (!(firstStatement is StatementSyntax firstStatementSyntax)) { throw new ArgumentException("firstStatement is not a StatementSyntax."); } if (!(lastStatement is StatementSyntax lastStatementSyntax)) { throw new ArgumentException("firstStatement is a StatementSyntax but lastStatement isn't."); } return this.AnalyzeControlFlow(firstStatementSyntax, lastStatementSyntax); } protected sealed override ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode statement) { if (statement == null) { throw new ArgumentNullException(nameof(statement)); } if (!(statement is StatementSyntax statementSyntax)) { throw new ArgumentException("statement is not a StatementSyntax."); } return this.AnalyzeControlFlow(statementSyntax); } protected sealed override DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement) { if (firstStatement == null) { throw new ArgumentNullException(nameof(firstStatement)); } if (lastStatement == null) { throw new ArgumentNullException(nameof(lastStatement)); } if (!(firstStatement is StatementSyntax firstStatementSyntax)) { throw new ArgumentException("firstStatement is not a StatementSyntax."); } if (!(lastStatement is StatementSyntax lastStatementSyntax)) { throw new ArgumentException("lastStatement is not a StatementSyntax."); } return this.AnalyzeDataFlow(firstStatementSyntax, lastStatementSyntax); } protected sealed override DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode statementOrExpression) { switch (statementOrExpression) { case null: throw new ArgumentNullException(nameof(statementOrExpression)); case StatementSyntax statementSyntax: return this.AnalyzeDataFlow(statementSyntax); case ExpressionSyntax expressionSyntax: return this.AnalyzeDataFlow(expressionSyntax); default: throw new ArgumentException("statementOrExpression is not a StatementSyntax or an ExpressionSyntax."); } } protected sealed override Optional<object> GetConstantValueCore(SyntaxNode node, CancellationToken cancellationToken) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return node is ExpressionSyntax expression ? GetConstantValue(expression, cancellationToken) : default(Optional<object>); } protected sealed override ISymbol GetEnclosingSymbolCore(int position, CancellationToken cancellationToken) { return this.GetEnclosingSymbol(position, cancellationToken); } protected sealed override bool IsAccessibleCore(int position, ISymbol symbol) { return this.IsAccessible(position, symbol.EnsureCSharpSymbolOrNull(nameof(symbol))); } protected sealed override bool IsEventUsableAsFieldCore(int position, IEventSymbol symbol) { return this.IsEventUsableAsField(position, symbol.EnsureCSharpSymbolOrNull(nameof(symbol))); } public sealed override NullableContext GetNullableContext(int position) { var syntaxTree = (CSharpSyntaxTree)Root.SyntaxTree; NullableContextState contextState = syntaxTree.GetNullableContextState(position); var defaultState = syntaxTree.IsGeneratedCode(Compilation.Options.SyntaxTreeOptionsProvider, CancellationToken.None) ? NullableContextOptions.Disable : Compilation.Options.NullableContextOptions; NullableContext context = getFlag(contextState.AnnotationsState, defaultState.AnnotationsEnabled(), NullableContext.AnnotationsContextInherited, NullableContext.AnnotationsEnabled); context |= getFlag(contextState.WarningsState, defaultState.WarningsEnabled(), NullableContext.WarningsContextInherited, NullableContext.WarningsEnabled); return context; static NullableContext getFlag(NullableContextState.State contextState, bool defaultEnableState, NullableContext inheritedFlag, NullableContext enableFlag) => contextState switch { NullableContextState.State.Enabled => enableFlag, NullableContextState.State.Disabled => NullableContext.Disabled, _ when defaultEnableState => (inheritedFlag | enableFlag), _ => inheritedFlag, }; } #endregion } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.ConstructorSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents an anonymous type constructor. /// </summary> private sealed partial class AnonymousTypeConstructorSymbol : SynthesizedMethodBase { private readonly ImmutableArray<ParameterSymbol> _parameters; internal AnonymousTypeConstructorSymbol(NamedTypeSymbol container, ImmutableArray<AnonymousTypePropertySymbol> properties) : base(container, WellKnownMemberNames.InstanceConstructorName) { // Create constructor parameters int fieldsCount = properties.Length; if (fieldsCount > 0) { var paramsArr = ArrayBuilder<ParameterSymbol>.GetInstance(fieldsCount); for (int index = 0; index < fieldsCount; index++) { PropertySymbol property = properties[index]; paramsArr.Add(SynthesizedParameterSymbol.Create(this, property.TypeWithAnnotations, index, RefKind.None, property.Name)); } _parameters = paramsArr.ToImmutableAndFree(); } else { _parameters = ImmutableArray<ParameterSymbol>.Empty; } } public override MethodKind MethodKind { get { return MethodKind.Constructor; } } public override bool ReturnsVoid { get { return true; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(this.Manager.System_Void); } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override bool IsOverride { get { return false; } } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override ImmutableArray<Location> Locations { get { // The accessor for an anonymous type constructor has the same location as the type. return this.ContainingSymbol.Locations; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents an anonymous type constructor. /// </summary> private sealed partial class AnonymousTypeConstructorSymbol : SynthesizedMethodBase { private readonly ImmutableArray<ParameterSymbol> _parameters; internal AnonymousTypeConstructorSymbol(NamedTypeSymbol container, ImmutableArray<AnonymousTypePropertySymbol> properties) : base(container, WellKnownMemberNames.InstanceConstructorName) { // Create constructor parameters int fieldsCount = properties.Length; if (fieldsCount > 0) { var paramsArr = ArrayBuilder<ParameterSymbol>.GetInstance(fieldsCount); for (int index = 0; index < fieldsCount; index++) { PropertySymbol property = properties[index]; paramsArr.Add(SynthesizedParameterSymbol.Create(this, property.TypeWithAnnotations, index, RefKind.None, property.Name)); } _parameters = paramsArr.ToImmutableAndFree(); } else { _parameters = ImmutableArray<ParameterSymbol>.Empty; } } public override MethodKind MethodKind { get { return MethodKind.Constructor; } } public override bool ReturnsVoid { get { return true; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(this.Manager.System_Void); } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override bool IsOverride { get { return false; } } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override ImmutableArray<Location> Locations { get { // The accessor for an anonymous type constructor has the same location as the type. return this.ContainingSymbol.Locations; } } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/Remote/Core/ISolutionSynchronizationService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Host; namespace Microsoft.CodeAnalysis.Remote { internal interface ISolutionAssetStorageProvider : IWorkspaceService { SolutionAssetStorage AssetStorage { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { internal interface ISolutionAssetStorageProvider : IWorkspaceService { SolutionAssetStorage AssetStorage { get; } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.ShortTC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct ShortTC : INumericTC<short> { short INumericTC<short>.MinValue => short.MinValue; short INumericTC<short>.MaxValue => short.MaxValue; short INumericTC<short>.Zero => 0; bool INumericTC<short>.Related(BinaryOperatorKind relation, short left, short right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } short INumericTC<short>.Next(short value) { Debug.Assert(value != short.MaxValue); return (short)(value + 1); } short INumericTC<short>.Prev(short value) { Debug.Assert(value != short.MinValue); return (short)(value - 1); } short INumericTC<short>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (short)0 : constantValue.Int16Value; ConstantValue INumericTC<short>.ToConstantValue(short value) => ConstantValue.Create(value); string INumericTC<short>.ToString(short value) => value.ToString(); short INumericTC<short>.Random(Random random) { return (short)random.Next(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct ShortTC : INumericTC<short> { short INumericTC<short>.MinValue => short.MinValue; short INumericTC<short>.MaxValue => short.MaxValue; short INumericTC<short>.Zero => 0; bool INumericTC<short>.Related(BinaryOperatorKind relation, short left, short right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } short INumericTC<short>.Next(short value) { Debug.Assert(value != short.MaxValue); return (short)(value + 1); } short INumericTC<short>.Prev(short value) { Debug.Assert(value != short.MinValue); return (short)(value - 1); } short INumericTC<short>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (short)0 : constantValue.Int16Value; ConstantValue INumericTC<short>.ToConstantValue(short value) => ConstantValue.Create(value); string INumericTC<short>.ToString(short value) => value.ToString(); short INumericTC<short>.Random(Random random) { return (short)random.Next(); } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseInferredMemberName { internal abstract class AbstractUseInferredMemberNameCodeFixProvider : SyntaxEditorBasedCodeFixProvider { protected abstract void LanguageSpecificRemoveSuggestedNode(SyntaxEditor editor, SyntaxNode node); public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var node = root.FindNode(diagnostic.Location.SourceSpan); LanguageSpecificRemoveSuggestedNode(editor, node); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_inferred_member_name, createChangedDocument, AnalyzersResources.Use_inferred_member_name) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseInferredMemberName { internal abstract class AbstractUseInferredMemberNameCodeFixProvider : SyntaxEditorBasedCodeFixProvider { protected abstract void LanguageSpecificRemoveSuggestedNode(SyntaxEditor editor, SyntaxNode node); public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var node = root.FindNode(diagnostic.Location.SourceSpan); LanguageSpecificRemoveSuggestedNode(editor, node); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_inferred_member_name, createChangedDocument, AnalyzersResources.Use_inferred_member_name) { } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/Implementation/Preview/PreviewEngine.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal class PreviewEngine : ForegroundThreadAffinitizedObject, IVsPreviewChangesEngine { private readonly IVsEditorAdaptersFactoryService _editorFactory; private readonly Solution _newSolution; private readonly Solution _oldSolution; private readonly string _topLevelName; private readonly Glyph _topLevelGlyph; private readonly string _helpString; private readonly string _description; private readonly string _title; private readonly IComponentModel _componentModel; private readonly IVsImageService2 _imageService; private TopLevelChange _topLevelChange; private PreviewUpdater _updater; public Solution FinalSolution { get; private set; } public bool ShowCheckBoxes { get; private set; } public PreviewEngine(IThreadingContext threadingContext, string title, string helpString, string description, string topLevelItemName, Glyph topLevelGlyph, Solution newSolution, Solution oldSolution, IComponentModel componentModel, bool showCheckBoxes = true) : this(threadingContext, title, helpString, description, topLevelItemName, topLevelGlyph, newSolution, oldSolution, componentModel, null, showCheckBoxes) { } public PreviewEngine( IThreadingContext threadingContext, string title, string helpString, string description, string topLevelItemName, Glyph topLevelGlyph, Solution newSolution, Solution oldSolution, IComponentModel componentModel, IVsImageService2 imageService, bool showCheckBoxes = true) : base(threadingContext) { _topLevelName = topLevelItemName; _topLevelGlyph = topLevelGlyph; _title = title ?? throw new ArgumentNullException(nameof(title)); _helpString = helpString ?? throw new ArgumentNullException(nameof(helpString)); _description = description ?? throw new ArgumentNullException(nameof(description)); _newSolution = newSolution.WithMergedLinkedFileChangesAsync(oldSolution, cancellationToken: CancellationToken.None).Result; _oldSolution = oldSolution; _editorFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _componentModel = componentModel; this.ShowCheckBoxes = showCheckBoxes; _imageService = imageService; } public void CloseWorkspace() { if (_updater != null) { _updater.CloseWorkspace(); } } public int ApplyChanges() { FinalSolution = _topLevelChange.GetUpdatedSolution(applyingChanges: true); return VSConstants.S_OK; } public int GetConfirmation(out string pbstrConfirmation) { pbstrConfirmation = EditorFeaturesResources.Apply2; return VSConstants.S_OK; } public int GetDescription(out string pbstrDescription) { pbstrDescription = _description; return VSConstants.S_OK; } public int GetHelpContext(out string pbstrHelpContext) { pbstrHelpContext = _helpString; return VSConstants.S_OK; } public int GetRootChangesList(out object ppIUnknownPreviewChangesList) { var changes = _newSolution.GetChanges(_oldSolution); var projectChanges = changes.GetProjectChanges(); _topLevelChange = new TopLevelChange(_topLevelName, _topLevelGlyph, _newSolution, this); var builder = ArrayBuilder<AbstractChange>.GetInstance(); // Documents // (exclude unchangeable ones if they will be ignored when applied to workspace.) var changedDocuments = projectChanges.SelectMany(p => p.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true, _oldSolution.Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges)); var addedDocuments = projectChanges.SelectMany(p => p.GetAddedDocuments()); var removedDocuments = projectChanges.SelectMany(p => p.GetRemovedDocuments()); var allDocumentsWithChanges = new List<DocumentId>(); allDocumentsWithChanges.AddRange(changedDocuments); allDocumentsWithChanges.AddRange(addedDocuments); allDocumentsWithChanges.AddRange(removedDocuments); // Additional Documents var changedAdditionalDocuments = projectChanges.SelectMany(p => p.GetChangedAdditionalDocuments()); var addedAdditionalDocuments = projectChanges.SelectMany(p => p.GetAddedAdditionalDocuments()); var removedAdditionalDocuments = projectChanges.SelectMany(p => p.GetRemovedAdditionalDocuments()); allDocumentsWithChanges.AddRange(changedAdditionalDocuments); allDocumentsWithChanges.AddRange(addedAdditionalDocuments); allDocumentsWithChanges.AddRange(removedAdditionalDocuments); // AnalyzerConfig Documents var changedAnalyzerConfigDocuments = projectChanges.SelectMany(p => p.GetChangedAnalyzerConfigDocuments()); var addedAnalyzerConfigDocuments = projectChanges.SelectMany(p => p.GetAddedAnalyzerConfigDocuments()); var removedAnalyzerConfigDocuments = projectChanges.SelectMany(p => p.GetRemovedAnalyzerConfigDocuments()); allDocumentsWithChanges.AddRange(changedAnalyzerConfigDocuments); allDocumentsWithChanges.AddRange(addedAnalyzerConfigDocuments); allDocumentsWithChanges.AddRange(removedAnalyzerConfigDocuments); AppendFileChanges(allDocumentsWithChanges, builder); // References (metadata/project/analyzer) ReferenceChange.AppendReferenceChanges(projectChanges, this, builder); _topLevelChange.Children = builder.Count == 0 ? ChangeList.Empty : new ChangeList(builder.ToArray()); ppIUnknownPreviewChangesList = _topLevelChange.Children.Changes.Length == 0 ? new ChangeList(new[] { new NoChange(this) }) : new ChangeList(new[] { _topLevelChange }); if (_topLevelChange.Children.Changes.Length == 0) { this.ShowCheckBoxes = false; } return VSConstants.S_OK; } private void AppendFileChanges(IEnumerable<DocumentId> changedDocuments, ArrayBuilder<AbstractChange> builder) { // Avoid showing linked changes to linked files multiple times. var linkedDocumentIds = new HashSet<DocumentId>(); var orderedChangedDocuments = changedDocuments.GroupBy(d => d.ProjectId).OrderByDescending(g => g.Count()).Flatten(); foreach (var documentId in orderedChangedDocuments) { if (linkedDocumentIds.Contains(documentId)) { continue; } var left = _oldSolution.GetTextDocument(documentId); var right = _newSolution.GetTextDocument(documentId); if (left is Document leftDocument) { linkedDocumentIds.AddRange(leftDocument.GetLinkedDocumentIds()); } else if (right is Document rightDocument) { // Added document. linkedDocumentIds.AddRange(rightDocument.GetLinkedDocumentIds()); } var fileChange = new FileChange(left, right, _componentModel, _topLevelChange, this, _imageService); if (fileChange.Children.Changes.Length > 0) { builder.Add(fileChange); } } } public int GetTextViewDescription(out string pbstrTextViewDescription) { pbstrTextViewDescription = EditorFeaturesResources.Preview_Code_Changes_colon; return VSConstants.S_OK; } public int GetTitle(out string pbstrTitle) { pbstrTitle = _title; return VSConstants.S_OK; } public int GetWarning(out string pbstrWarning, out int ppcwlWarningLevel) { pbstrWarning = null; ppcwlWarningLevel = 0; return VSConstants.E_NOTIMPL; } public void UpdatePreview(DocumentId documentId, SpanChange spanSource) { var updatedSolution = _topLevelChange.GetUpdatedSolution(applyingChanges: false); var document = updatedSolution.GetTextDocument(documentId); if (document != null) { _updater.UpdateView(document, spanSource); } } // We don't get a TexView until they call OnRequestChanges on a child. // However, once they've called it once, it's always the same TextView. public void SetTextView(object textView) { if (_updater == null) { _updater = new PreviewUpdater(ThreadingContext, EnsureTextViewIsInitialized(textView)); } } private ITextView EnsureTextViewIsInitialized(object previewTextView) { // We pass in a regular ITextView in tests if (previewTextView is not null and ITextView) { return (ITextView)previewTextView; } var adapter = (IVsTextView)previewTextView; var textView = _editorFactory.GetWpfTextView(adapter); if (textView == null) { EditBufferToInitialize(adapter); textView = _editorFactory.GetWpfTextView(adapter); } UpdateTextViewOptions(textView); return textView; } private static void UpdateTextViewOptions(IWpfTextView textView) { // Do not show the IndentationCharacterMargin, which controls spaces vs. tabs etc. textView.Options.SetOptionValue(DefaultTextViewHostOptions.IndentationCharacterMarginOptionId, false); // Do not show LineEndingMargin, which determines EOL and EOF settings. textView.Options.SetOptionValue(DefaultTextViewHostOptions.LineEndingMarginOptionId, false); // Do not show the "no issues found" health indicator for previews. textView.Options.SetOptionValue(DefaultTextViewHostOptions.EnableFileHealthIndicatorOptionId, false); } // When the dialog is first instantiated, the IVsTextView it contains may // not have been initialized, which will prevent us from using an // EditorAdaptersFactoryService to get the ITextView. If we edit the IVsTextView, // it will initialize and we can proceed. private static void EditBufferToInitialize(IVsTextView adapter) { if (adapter == null) { return; } var newText = ""; var newTextPtr = Marshal.StringToHGlobalAuto(newText); try { Marshal.ThrowExceptionForHR(adapter.GetBuffer(out var lines)); Marshal.ThrowExceptionForHR(lines.GetLastLineIndex(out _, out var piLineIndex)); Marshal.ThrowExceptionForHR(lines.GetLengthOfLine(piLineIndex, out var piLineLength)); Microsoft.VisualStudio.TextManager.Interop.TextSpan[] changes = null; piLineLength = piLineLength > 0 ? piLineLength - 1 : 0; Marshal.ThrowExceptionForHR(lines.ReplaceLines(0, 0, piLineIndex, piLineLength, newTextPtr, newText.Length, changes)); } finally { Marshal.FreeHGlobal(newTextPtr); } } private class NoChange : AbstractChange { public NoChange(PreviewEngine engine) : base(engine) { } public override int GetText(out VSTREETEXTOPTIONS tto, out string ppszText) { tto = VSTREETEXTOPTIONS.TTO_DEFAULT; ppszText = ServicesVSResources.No_Changes; return VSConstants.S_OK; } public override int GetTipText(out VSTREETOOLTIPTYPE eTipType, out string ppszText) { eTipType = VSTREETOOLTIPTYPE.TIPTYPE_DEFAULT; ppszText = null; return VSConstants.E_FAIL; } public override int CanRecurse => 0; public override int IsExpandable => 0; internal override void GetDisplayData(VSTREEDISPLAYDATA[] pData) => pData[0].Image = pData[0].SelectedImage = (ushort)StandardGlyphGroup.GlyphInformation; public override int OnRequestSource(object pIUnknownTextView) => VSConstants.S_OK; public override void UpdatePreview() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal class PreviewEngine : ForegroundThreadAffinitizedObject, IVsPreviewChangesEngine { private readonly IVsEditorAdaptersFactoryService _editorFactory; private readonly Solution _newSolution; private readonly Solution _oldSolution; private readonly string _topLevelName; private readonly Glyph _topLevelGlyph; private readonly string _helpString; private readonly string _description; private readonly string _title; private readonly IComponentModel _componentModel; private readonly IVsImageService2 _imageService; private TopLevelChange _topLevelChange; private PreviewUpdater _updater; public Solution FinalSolution { get; private set; } public bool ShowCheckBoxes { get; private set; } public PreviewEngine(IThreadingContext threadingContext, string title, string helpString, string description, string topLevelItemName, Glyph topLevelGlyph, Solution newSolution, Solution oldSolution, IComponentModel componentModel, bool showCheckBoxes = true) : this(threadingContext, title, helpString, description, topLevelItemName, topLevelGlyph, newSolution, oldSolution, componentModel, null, showCheckBoxes) { } public PreviewEngine( IThreadingContext threadingContext, string title, string helpString, string description, string topLevelItemName, Glyph topLevelGlyph, Solution newSolution, Solution oldSolution, IComponentModel componentModel, IVsImageService2 imageService, bool showCheckBoxes = true) : base(threadingContext) { _topLevelName = topLevelItemName; _topLevelGlyph = topLevelGlyph; _title = title ?? throw new ArgumentNullException(nameof(title)); _helpString = helpString ?? throw new ArgumentNullException(nameof(helpString)); _description = description ?? throw new ArgumentNullException(nameof(description)); _newSolution = newSolution.WithMergedLinkedFileChangesAsync(oldSolution, cancellationToken: CancellationToken.None).Result; _oldSolution = oldSolution; _editorFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _componentModel = componentModel; this.ShowCheckBoxes = showCheckBoxes; _imageService = imageService; } public void CloseWorkspace() { if (_updater != null) { _updater.CloseWorkspace(); } } public int ApplyChanges() { FinalSolution = _topLevelChange.GetUpdatedSolution(applyingChanges: true); return VSConstants.S_OK; } public int GetConfirmation(out string pbstrConfirmation) { pbstrConfirmation = EditorFeaturesResources.Apply2; return VSConstants.S_OK; } public int GetDescription(out string pbstrDescription) { pbstrDescription = _description; return VSConstants.S_OK; } public int GetHelpContext(out string pbstrHelpContext) { pbstrHelpContext = _helpString; return VSConstants.S_OK; } public int GetRootChangesList(out object ppIUnknownPreviewChangesList) { var changes = _newSolution.GetChanges(_oldSolution); var projectChanges = changes.GetProjectChanges(); _topLevelChange = new TopLevelChange(_topLevelName, _topLevelGlyph, _newSolution, this); var builder = ArrayBuilder<AbstractChange>.GetInstance(); // Documents // (exclude unchangeable ones if they will be ignored when applied to workspace.) var changedDocuments = projectChanges.SelectMany(p => p.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true, _oldSolution.Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges)); var addedDocuments = projectChanges.SelectMany(p => p.GetAddedDocuments()); var removedDocuments = projectChanges.SelectMany(p => p.GetRemovedDocuments()); var allDocumentsWithChanges = new List<DocumentId>(); allDocumentsWithChanges.AddRange(changedDocuments); allDocumentsWithChanges.AddRange(addedDocuments); allDocumentsWithChanges.AddRange(removedDocuments); // Additional Documents var changedAdditionalDocuments = projectChanges.SelectMany(p => p.GetChangedAdditionalDocuments()); var addedAdditionalDocuments = projectChanges.SelectMany(p => p.GetAddedAdditionalDocuments()); var removedAdditionalDocuments = projectChanges.SelectMany(p => p.GetRemovedAdditionalDocuments()); allDocumentsWithChanges.AddRange(changedAdditionalDocuments); allDocumentsWithChanges.AddRange(addedAdditionalDocuments); allDocumentsWithChanges.AddRange(removedAdditionalDocuments); // AnalyzerConfig Documents var changedAnalyzerConfigDocuments = projectChanges.SelectMany(p => p.GetChangedAnalyzerConfigDocuments()); var addedAnalyzerConfigDocuments = projectChanges.SelectMany(p => p.GetAddedAnalyzerConfigDocuments()); var removedAnalyzerConfigDocuments = projectChanges.SelectMany(p => p.GetRemovedAnalyzerConfigDocuments()); allDocumentsWithChanges.AddRange(changedAnalyzerConfigDocuments); allDocumentsWithChanges.AddRange(addedAnalyzerConfigDocuments); allDocumentsWithChanges.AddRange(removedAnalyzerConfigDocuments); AppendFileChanges(allDocumentsWithChanges, builder); // References (metadata/project/analyzer) ReferenceChange.AppendReferenceChanges(projectChanges, this, builder); _topLevelChange.Children = builder.Count == 0 ? ChangeList.Empty : new ChangeList(builder.ToArray()); ppIUnknownPreviewChangesList = _topLevelChange.Children.Changes.Length == 0 ? new ChangeList(new[] { new NoChange(this) }) : new ChangeList(new[] { _topLevelChange }); if (_topLevelChange.Children.Changes.Length == 0) { this.ShowCheckBoxes = false; } return VSConstants.S_OK; } private void AppendFileChanges(IEnumerable<DocumentId> changedDocuments, ArrayBuilder<AbstractChange> builder) { // Avoid showing linked changes to linked files multiple times. var linkedDocumentIds = new HashSet<DocumentId>(); var orderedChangedDocuments = changedDocuments.GroupBy(d => d.ProjectId).OrderByDescending(g => g.Count()).Flatten(); foreach (var documentId in orderedChangedDocuments) { if (linkedDocumentIds.Contains(documentId)) { continue; } var left = _oldSolution.GetTextDocument(documentId); var right = _newSolution.GetTextDocument(documentId); if (left is Document leftDocument) { linkedDocumentIds.AddRange(leftDocument.GetLinkedDocumentIds()); } else if (right is Document rightDocument) { // Added document. linkedDocumentIds.AddRange(rightDocument.GetLinkedDocumentIds()); } var fileChange = new FileChange(left, right, _componentModel, _topLevelChange, this, _imageService); if (fileChange.Children.Changes.Length > 0) { builder.Add(fileChange); } } } public int GetTextViewDescription(out string pbstrTextViewDescription) { pbstrTextViewDescription = EditorFeaturesResources.Preview_Code_Changes_colon; return VSConstants.S_OK; } public int GetTitle(out string pbstrTitle) { pbstrTitle = _title; return VSConstants.S_OK; } public int GetWarning(out string pbstrWarning, out int ppcwlWarningLevel) { pbstrWarning = null; ppcwlWarningLevel = 0; return VSConstants.E_NOTIMPL; } public void UpdatePreview(DocumentId documentId, SpanChange spanSource) { var updatedSolution = _topLevelChange.GetUpdatedSolution(applyingChanges: false); var document = updatedSolution.GetTextDocument(documentId); if (document != null) { _updater.UpdateView(document, spanSource); } } // We don't get a TexView until they call OnRequestChanges on a child. // However, once they've called it once, it's always the same TextView. public void SetTextView(object textView) { if (_updater == null) { _updater = new PreviewUpdater(ThreadingContext, EnsureTextViewIsInitialized(textView)); } } private ITextView EnsureTextViewIsInitialized(object previewTextView) { // We pass in a regular ITextView in tests if (previewTextView is not null and ITextView) { return (ITextView)previewTextView; } var adapter = (IVsTextView)previewTextView; var textView = _editorFactory.GetWpfTextView(adapter); if (textView == null) { EditBufferToInitialize(adapter); textView = _editorFactory.GetWpfTextView(adapter); } UpdateTextViewOptions(textView); return textView; } private static void UpdateTextViewOptions(IWpfTextView textView) { // Do not show the IndentationCharacterMargin, which controls spaces vs. tabs etc. textView.Options.SetOptionValue(DefaultTextViewHostOptions.IndentationCharacterMarginOptionId, false); // Do not show LineEndingMargin, which determines EOL and EOF settings. textView.Options.SetOptionValue(DefaultTextViewHostOptions.LineEndingMarginOptionId, false); // Do not show the "no issues found" health indicator for previews. textView.Options.SetOptionValue(DefaultTextViewHostOptions.EnableFileHealthIndicatorOptionId, false); } // When the dialog is first instantiated, the IVsTextView it contains may // not have been initialized, which will prevent us from using an // EditorAdaptersFactoryService to get the ITextView. If we edit the IVsTextView, // it will initialize and we can proceed. private static void EditBufferToInitialize(IVsTextView adapter) { if (adapter == null) { return; } var newText = ""; var newTextPtr = Marshal.StringToHGlobalAuto(newText); try { Marshal.ThrowExceptionForHR(adapter.GetBuffer(out var lines)); Marshal.ThrowExceptionForHR(lines.GetLastLineIndex(out _, out var piLineIndex)); Marshal.ThrowExceptionForHR(lines.GetLengthOfLine(piLineIndex, out var piLineLength)); Microsoft.VisualStudio.TextManager.Interop.TextSpan[] changes = null; piLineLength = piLineLength > 0 ? piLineLength - 1 : 0; Marshal.ThrowExceptionForHR(lines.ReplaceLines(0, 0, piLineIndex, piLineLength, newTextPtr, newText.Length, changes)); } finally { Marshal.FreeHGlobal(newTextPtr); } } private class NoChange : AbstractChange { public NoChange(PreviewEngine engine) : base(engine) { } public override int GetText(out VSTREETEXTOPTIONS tto, out string ppszText) { tto = VSTREETEXTOPTIONS.TTO_DEFAULT; ppszText = ServicesVSResources.No_Changes; return VSConstants.S_OK; } public override int GetTipText(out VSTREETOOLTIPTYPE eTipType, out string ppszText) { eTipType = VSTREETOOLTIPTYPE.TIPTYPE_DEFAULT; ppszText = null; return VSConstants.E_FAIL; } public override int CanRecurse => 0; public override int IsExpandable => 0; internal override void GetDisplayData(VSTREEDISPLAYDATA[] pData) => pData[0].Image = pData[0].SelectedImage = (ushort)StandardGlyphGroup.GlyphInformation; public override int OnRequestSource(object pIUnknownTextView) => VSConstants.S_OK; public override void UpdatePreview() { } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Features/Core/Portable/GenerateConstructorFromMembers/AbstractGenerateConstructorFromMembersCodeRefactoringProvider.FieldDelegatingCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider { private class FieldDelegatingCodeAction : CodeAction { private readonly AbstractGenerateConstructorFromMembersCodeRefactoringProvider _service; private readonly Document _document; private readonly State _state; private readonly bool _addNullChecks; public FieldDelegatingCodeAction( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, State state, bool addNullChecks) { _service = service; _document = document; _state = state; _addNullChecks = addNullChecks; } protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { // First, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. var parameterToExistingFieldMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); for (var i = 0; i < _state.Parameters.Length; i++) parameterToExistingFieldMap[_state.Parameters[i].Name] = _state.SelectedMembers[i]; var factory = _document.GetLanguageService<SyntaxGenerator>(); var semanticModel = await _document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxTree = semanticModel.SyntaxTree; var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var preferThrowExpression = _service.PrefersThrowExpression(options); var members = factory.CreateMemberDelegatingConstructor( semanticModel, _state.ContainingType.Name, _state.ContainingType, _state.Parameters, parameterToExistingFieldMap.ToImmutable(), parameterToNewMemberMap: null, addNullChecks: _addNullChecks, preferThrowExpression: preferThrowExpression, generateProperties: false, _state.IsContainedInUnsafeType); // If the user has selected a set of members (i.e. TextSpan is not empty), then we will // choose the right location (i.e. null) to insert the constructor. However, if they're // just invoking the feature manually at a specific location, then we'll insert the // members at that specific place in the class/struct. var afterThisLocation = _state.TextSpan.IsEmpty ? syntaxTree.GetLocation(_state.TextSpan) : null; var result = await CodeGenerator.AddMemberDeclarationsAsync( _document.Project.Solution, _state.ContainingType, members, new CodeGenerationOptions( contextLocation: syntaxTree.GetLocation(_state.TextSpan), afterThisLocation: afterThisLocation), cancellationToken).ConfigureAwait(false); return await AddNavigationAnnotationAsync(result, cancellationToken).ConfigureAwait(false); } public override string Title { get { var parameters = _state.Parameters.Select(p => _service.ToDisplayString(p, SimpleFormat)); var parameterString = string.Join(", ", parameters); if (_state.DelegatedConstructor == null) { return string.Format(FeaturesResources.Generate_constructor_0_1, _state.ContainingType.Name, parameterString); } else { return string.Format(FeaturesResources.Generate_field_assigning_constructor_0_1, _state.ContainingType.Name, parameterString); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider { private class FieldDelegatingCodeAction : CodeAction { private readonly AbstractGenerateConstructorFromMembersCodeRefactoringProvider _service; private readonly Document _document; private readonly State _state; private readonly bool _addNullChecks; public FieldDelegatingCodeAction( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, State state, bool addNullChecks) { _service = service; _document = document; _state = state; _addNullChecks = addNullChecks; } protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { // First, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. var parameterToExistingFieldMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); for (var i = 0; i < _state.Parameters.Length; i++) parameterToExistingFieldMap[_state.Parameters[i].Name] = _state.SelectedMembers[i]; var factory = _document.GetLanguageService<SyntaxGenerator>(); var semanticModel = await _document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxTree = semanticModel.SyntaxTree; var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var preferThrowExpression = _service.PrefersThrowExpression(options); var members = factory.CreateMemberDelegatingConstructor( semanticModel, _state.ContainingType.Name, _state.ContainingType, _state.Parameters, parameterToExistingFieldMap.ToImmutable(), parameterToNewMemberMap: null, addNullChecks: _addNullChecks, preferThrowExpression: preferThrowExpression, generateProperties: false, _state.IsContainedInUnsafeType); // If the user has selected a set of members (i.e. TextSpan is not empty), then we will // choose the right location (i.e. null) to insert the constructor. However, if they're // just invoking the feature manually at a specific location, then we'll insert the // members at that specific place in the class/struct. var afterThisLocation = _state.TextSpan.IsEmpty ? syntaxTree.GetLocation(_state.TextSpan) : null; var result = await CodeGenerator.AddMemberDeclarationsAsync( _document.Project.Solution, _state.ContainingType, members, new CodeGenerationOptions( contextLocation: syntaxTree.GetLocation(_state.TextSpan), afterThisLocation: afterThisLocation), cancellationToken).ConfigureAwait(false); return await AddNavigationAnnotationAsync(result, cancellationToken).ConfigureAwait(false); } public override string Title { get { var parameters = _state.Parameters.Select(p => _service.ToDisplayString(p, SimpleFormat)); var parameterString = string.Join(", ", parameters); if (_state.DelegatedConstructor == null) { return string.Format(FeaturesResources.Generate_constructor_0_1, _state.ContainingType.Name, parameterString); } else { return string.Format(FeaturesResources.Generate_field_assigning_constructor_0_1, _state.ContainingType.Name, parameterString); } } } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/YieldStatementHighlighter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class YieldStatementHighlighter : AbstractKeywordHighlighter<YieldStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public YieldStatementHighlighter() { } protected override void AddHighlights( YieldStatementSyntax yieldStatement, List<TextSpan> spans, CancellationToken cancellationToken) { var parent = yieldStatement .GetAncestorsOrThis<SyntaxNode>() .FirstOrDefault(n => n.IsReturnableConstruct()); if (parent == null) { return; } HighlightRelatedKeywords(parent, spans); } /// <summary> /// Finds all returns that are children of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans) { switch (node) { case YieldStatementSyntax statement: spans.Add( TextSpan.FromBounds( statement.YieldKeyword.SpanStart, statement.ReturnOrBreakKeyword.Span.End)); spans.Add(EmptySpan(statement.SemicolonToken.Span.End)); break; default: foreach (var child in node.ChildNodesAndTokens()) { if (child.IsToken) continue; // Only recurse if we have anything to do if (!child.AsNode().IsReturnableConstruct()) { HighlightRelatedKeywords(child.AsNode(), spans); } } 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; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class YieldStatementHighlighter : AbstractKeywordHighlighter<YieldStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public YieldStatementHighlighter() { } protected override void AddHighlights( YieldStatementSyntax yieldStatement, List<TextSpan> spans, CancellationToken cancellationToken) { var parent = yieldStatement .GetAncestorsOrThis<SyntaxNode>() .FirstOrDefault(n => n.IsReturnableConstruct()); if (parent == null) { return; } HighlightRelatedKeywords(parent, spans); } /// <summary> /// Finds all returns that are children of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans) { switch (node) { case YieldStatementSyntax statement: spans.Add( TextSpan.FromBounds( statement.YieldKeyword.SpanStart, statement.ReturnOrBreakKeyword.Span.End)); spans.Add(EmptySpan(statement.SemicolonToken.Span.End)); break; default: foreach (var child in node.ChildNodesAndTokens()) { if (child.IsToken) continue; // Only recurse if we have anything to do if (!child.AsNode().IsReturnableConstruct()) { HighlightRelatedKeywords(child.AsNode(), spans); } } break; } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxDiffingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxDiffingTests { [Fact] public void TestDiffEmptyVersusClass() { var oldTree = SyntaxFactory.ParseSyntaxTree(""); var newTree = SyntaxFactory.ParseSyntaxTree("class C { }"); // it should be all new var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(newTree.GetCompilationUnitRoot().FullSpan, spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(0, 0), changes[0].Span); Assert.Equal("class C { }", changes[0].NewText); } [Fact] public void TestDiffClassWithNameChanged() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = SyntaxFactory.ParseSyntaxTree("class B { }"); // since most tokens are automatically interned we should see only the name tokens change var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); var decl = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[0]; Assert.Equal(decl.Identifier.Span, spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(6, 1), changes[0].Span); Assert.Equal("B", changes[0].NewText); } [Fact] public void TestDiffTwoClassesWithBothNamesChanged() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { } class B { }"); var newTree = SyntaxFactory.ParseSyntaxTree("class C { } class D { }"); // since most tokens are automatically interned we should see only the name tokens change var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(2, spans.Count); var decl1 = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[0]; Assert.Equal(decl1.Identifier.Span, spans[0]); var decl2 = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[1]; Assert.Equal(decl2.Identifier.Span, spans[1]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(2, changes.Count); Assert.Equal(new TextSpan(6, 1), changes[0].Span); Assert.Equal("C", changes[0].NewText); Assert.Equal(new TextSpan(18, 1), changes[1].Span); Assert.Equal("D", changes[1].NewText); } [Fact] public void TestDiffClassWithNewClassStarted() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "class "); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(0, 6), spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(0, 0), changes[0].Span); Assert.Equal("class ", changes[0].NewText); } [Fact] public void TestDiffClassWithNewClassStarted2() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "class A "); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(0, 8), spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(0, 0), changes[0].Span); Assert.Equal("class A ", changes[0].NewText); } [Fact] public void TestDiffClassWithNewClassStarted3() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "class A { }"); // new tree appears to have two duplicate (similar) copies of the same declarations (indistinguishable) var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(11, 11), spans[0]); // its going to pick one of the two spans. var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(11, 0), changes[0].Span); Assert.Equal("class A { }", changes[0].NewText); } [Fact] public void TestDiffClassWithNewClassStarted4() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "class A { } "); // new tree appears to have two almost duplicate (similar) copies of the same declarations, except the // second (original) one is a closer match var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(10, 12), spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(10, 0), changes[0].Span); Assert.Equal("} class A { ", changes[0].NewText); } [Fact] public void TestDiffClassWithNewNamespaceEnclosing() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "namespace N { "); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(0, 14), spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(0, 0), changes[0].Span); Assert.Equal("namespace N { ", changes[0].NewText); } [Fact] public void TestDiffClassWithNewMemberInserted() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(10, "int X; "); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(10, 7), spans[0]); // int X; var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(10, 0), changes[0].Span); Assert.Equal("int X; ", changes[0].NewText); } [Fact] public void TestDiffClassWithMemberRemoved() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { int X; }"); var newTree = oldTree.WithRemoveAt(10, 7); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(0, spans.Count); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(10, 7), changes[0].Span); Assert.Equal("", changes[0].NewText); } [Fact] public void TestDiffClassWithMemberRemovedDeep() { var oldTree = SyntaxFactory.ParseSyntaxTree("namespace N { class A { int X; } }"); var newTree = oldTree.WithRemoveAt(24, 7); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(0, spans.Count); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(24, 7), changes[0].Span); Assert.Equal("", changes[0].NewText); } [Fact] public void TestDiffClassWithMemberNameRemoved() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { int X; }"); var newTree = oldTree.WithRemoveAt(14, 1); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(0, spans.Count); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(14, 1), changes[0].Span); Assert.Equal("", changes[0].NewText); } [Fact] public void TestDiffClassChangedToStruct() { var oldTree = SyntaxFactory.ParseSyntaxTree("namespace N { class A { int X; } }"); var newTree = oldTree.WithReplaceFirst("class", "struct"); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(14, 6), spans[0]); // 'struct' var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(14, 5), changes[0].Span); Assert.Equal("struct", changes[0].NewText); } [Fact, WorkItem(463, "https://github.com/dotnet/roslyn/issues/463")] public void TestQualifyWithThis() { var original = @" class C { int Sign; void F() { string x = @""namespace Namespace { class Type { void Goo() { int x = 1 "" + Sign + @"" "" + Sign + @""3; } } } ""; } }"; var oldTree = SyntaxFactory.ParseSyntaxTree(original); var root = oldTree.GetRoot(); var indexText = "Sign +"; // Expected behavior: Qualifying identifier 'Sign' with 'this.' and doing a diff between trees // should return a single text change with 'this.' as added text. // Works as expected for last index var index = original.LastIndexOf(indexText, StringComparison.Ordinal); TestQualifyWithThisCore(root, index); // Doesn't work as expected for first index. // It returns 2 changes with add followed by delete, // causing the 2 isolated edits of adding "this." to seem conflicting edits, even though they are not. // See https://github.com/dotnet/roslyn/issues/320 for details. index = original.IndexOf(indexText, StringComparison.Ordinal); TestQualifyWithThisCore(root, index); } private void TestQualifyWithThisCore(SyntaxNode root, int index) { var oldTree = root.SyntaxTree; var span = new TextSpan(index, 4); var node = root.FindNode(span, getInnermostNodeForTie: true) as SimpleNameSyntax; Assert.NotNull(node); Assert.Equal("Sign", node.Identifier.ValueText); var leadingTrivia = node.GetLeadingTrivia(); var newNode = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), node.WithoutLeadingTrivia()) .WithLeadingTrivia(leadingTrivia); var newRoot = root.ReplaceNode(node, newNode); var newTree = newRoot.SyntaxTree; var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal("this.", changes[0].NewText); } [Fact, WorkItem(463, "https://github.com/dotnet/roslyn/issues/463")] public void TestReplaceWithBuiltInType() { var original = @" using System; using System.Collections.Generic; public class TestClass { public void TestMethod() { var dictionary = new Dictionary<Object, Object>(); dictionary[new Object()] = new Object(); } }"; var oldTree = SyntaxFactory.ParseSyntaxTree(original); var root = oldTree.GetRoot(); var indexText = "Object"; // Expected behavior: Replacing identifier 'Object' with 'object' and doing a diff between trees // should return a single text change for character replace. // Works as expected for first index var index = original.IndexOf(indexText, StringComparison.Ordinal); TestReplaceWithBuiltInTypeCore(root, index); // Works as expected for last index index = original.LastIndexOf(indexText, StringComparison.Ordinal); TestReplaceWithBuiltInTypeCore(root, index); // Doesn't work as expected for the third index. // It returns 2 changes with add followed by delete, // causing the 2 isolated edits to seem conflicting edits, even though they are not. // See https://github.com/dotnet/roslyn/issues/320 for details. indexText = "Object()"; index = original.IndexOf(indexText, StringComparison.Ordinal); TestReplaceWithBuiltInTypeCore(root, index); } private void TestReplaceWithBuiltInTypeCore(SyntaxNode root, int index) { var oldTree = root.SyntaxTree; var span = new TextSpan(index, 6); var node = root.FindNode(span, getInnermostNodeForTie: true) as SimpleNameSyntax; Assert.NotNull(node); Assert.Equal("Object", node.Identifier.ValueText); var leadingTrivia = node.GetLeadingTrivia(); var newNode = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) .WithLeadingTrivia(leadingTrivia); var newRoot = root.ReplaceNode(node, newNode); var newTree = newRoot.SyntaxTree; var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal("o", changes[0].NewText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxDiffingTests { [Fact] public void TestDiffEmptyVersusClass() { var oldTree = SyntaxFactory.ParseSyntaxTree(""); var newTree = SyntaxFactory.ParseSyntaxTree("class C { }"); // it should be all new var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(newTree.GetCompilationUnitRoot().FullSpan, spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(0, 0), changes[0].Span); Assert.Equal("class C { }", changes[0].NewText); } [Fact] public void TestDiffClassWithNameChanged() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = SyntaxFactory.ParseSyntaxTree("class B { }"); // since most tokens are automatically interned we should see only the name tokens change var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); var decl = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[0]; Assert.Equal(decl.Identifier.Span, spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(6, 1), changes[0].Span); Assert.Equal("B", changes[0].NewText); } [Fact] public void TestDiffTwoClassesWithBothNamesChanged() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { } class B { }"); var newTree = SyntaxFactory.ParseSyntaxTree("class C { } class D { }"); // since most tokens are automatically interned we should see only the name tokens change var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(2, spans.Count); var decl1 = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[0]; Assert.Equal(decl1.Identifier.Span, spans[0]); var decl2 = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[1]; Assert.Equal(decl2.Identifier.Span, spans[1]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(2, changes.Count); Assert.Equal(new TextSpan(6, 1), changes[0].Span); Assert.Equal("C", changes[0].NewText); Assert.Equal(new TextSpan(18, 1), changes[1].Span); Assert.Equal("D", changes[1].NewText); } [Fact] public void TestDiffClassWithNewClassStarted() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "class "); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(0, 6), spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(0, 0), changes[0].Span); Assert.Equal("class ", changes[0].NewText); } [Fact] public void TestDiffClassWithNewClassStarted2() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "class A "); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(0, 8), spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(0, 0), changes[0].Span); Assert.Equal("class A ", changes[0].NewText); } [Fact] public void TestDiffClassWithNewClassStarted3() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "class A { }"); // new tree appears to have two duplicate (similar) copies of the same declarations (indistinguishable) var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(11, 11), spans[0]); // its going to pick one of the two spans. var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(11, 0), changes[0].Span); Assert.Equal("class A { }", changes[0].NewText); } [Fact] public void TestDiffClassWithNewClassStarted4() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "class A { } "); // new tree appears to have two almost duplicate (similar) copies of the same declarations, except the // second (original) one is a closer match var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(10, 12), spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(10, 0), changes[0].Span); Assert.Equal("} class A { ", changes[0].NewText); } [Fact] public void TestDiffClassWithNewNamespaceEnclosing() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(0, "namespace N { "); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(0, 14), spans[0]); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(0, 0), changes[0].Span); Assert.Equal("namespace N { ", changes[0].NewText); } [Fact] public void TestDiffClassWithNewMemberInserted() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }"); var newTree = oldTree.WithInsertAt(10, "int X; "); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(10, 7), spans[0]); // int X; var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(10, 0), changes[0].Span); Assert.Equal("int X; ", changes[0].NewText); } [Fact] public void TestDiffClassWithMemberRemoved() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { int X; }"); var newTree = oldTree.WithRemoveAt(10, 7); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(0, spans.Count); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(10, 7), changes[0].Span); Assert.Equal("", changes[0].NewText); } [Fact] public void TestDiffClassWithMemberRemovedDeep() { var oldTree = SyntaxFactory.ParseSyntaxTree("namespace N { class A { int X; } }"); var newTree = oldTree.WithRemoveAt(24, 7); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(0, spans.Count); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(24, 7), changes[0].Span); Assert.Equal("", changes[0].NewText); } [Fact] public void TestDiffClassWithMemberNameRemoved() { var oldTree = SyntaxFactory.ParseSyntaxTree("class A { int X; }"); var newTree = oldTree.WithRemoveAt(14, 1); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(0, spans.Count); var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(14, 1), changes[0].Span); Assert.Equal("", changes[0].NewText); } [Fact] public void TestDiffClassChangedToStruct() { var oldTree = SyntaxFactory.ParseSyntaxTree("namespace N { class A { int X; } }"); var newTree = oldTree.WithReplaceFirst("class", "struct"); var spans = newTree.GetChangedSpans(oldTree); Assert.NotNull(spans); Assert.Equal(1, spans.Count); Assert.Equal(new TextSpan(14, 6), spans[0]); // 'struct' var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(14, 5), changes[0].Span); Assert.Equal("struct", changes[0].NewText); } [Fact, WorkItem(463, "https://github.com/dotnet/roslyn/issues/463")] public void TestQualifyWithThis() { var original = @" class C { int Sign; void F() { string x = @""namespace Namespace { class Type { void Goo() { int x = 1 "" + Sign + @"" "" + Sign + @""3; } } } ""; } }"; var oldTree = SyntaxFactory.ParseSyntaxTree(original); var root = oldTree.GetRoot(); var indexText = "Sign +"; // Expected behavior: Qualifying identifier 'Sign' with 'this.' and doing a diff between trees // should return a single text change with 'this.' as added text. // Works as expected for last index var index = original.LastIndexOf(indexText, StringComparison.Ordinal); TestQualifyWithThisCore(root, index); // Doesn't work as expected for first index. // It returns 2 changes with add followed by delete, // causing the 2 isolated edits of adding "this." to seem conflicting edits, even though they are not. // See https://github.com/dotnet/roslyn/issues/320 for details. index = original.IndexOf(indexText, StringComparison.Ordinal); TestQualifyWithThisCore(root, index); } private void TestQualifyWithThisCore(SyntaxNode root, int index) { var oldTree = root.SyntaxTree; var span = new TextSpan(index, 4); var node = root.FindNode(span, getInnermostNodeForTie: true) as SimpleNameSyntax; Assert.NotNull(node); Assert.Equal("Sign", node.Identifier.ValueText); var leadingTrivia = node.GetLeadingTrivia(); var newNode = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), node.WithoutLeadingTrivia()) .WithLeadingTrivia(leadingTrivia); var newRoot = root.ReplaceNode(node, newNode); var newTree = newRoot.SyntaxTree; var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal("this.", changes[0].NewText); } [Fact, WorkItem(463, "https://github.com/dotnet/roslyn/issues/463")] public void TestReplaceWithBuiltInType() { var original = @" using System; using System.Collections.Generic; public class TestClass { public void TestMethod() { var dictionary = new Dictionary<Object, Object>(); dictionary[new Object()] = new Object(); } }"; var oldTree = SyntaxFactory.ParseSyntaxTree(original); var root = oldTree.GetRoot(); var indexText = "Object"; // Expected behavior: Replacing identifier 'Object' with 'object' and doing a diff between trees // should return a single text change for character replace. // Works as expected for first index var index = original.IndexOf(indexText, StringComparison.Ordinal); TestReplaceWithBuiltInTypeCore(root, index); // Works as expected for last index index = original.LastIndexOf(indexText, StringComparison.Ordinal); TestReplaceWithBuiltInTypeCore(root, index); // Doesn't work as expected for the third index. // It returns 2 changes with add followed by delete, // causing the 2 isolated edits to seem conflicting edits, even though they are not. // See https://github.com/dotnet/roslyn/issues/320 for details. indexText = "Object()"; index = original.IndexOf(indexText, StringComparison.Ordinal); TestReplaceWithBuiltInTypeCore(root, index); } private void TestReplaceWithBuiltInTypeCore(SyntaxNode root, int index) { var oldTree = root.SyntaxTree; var span = new TextSpan(index, 6); var node = root.FindNode(span, getInnermostNodeForTie: true) as SimpleNameSyntax; Assert.NotNull(node); Assert.Equal("Object", node.Identifier.ValueText); var leadingTrivia = node.GetLeadingTrivia(); var newNode = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) .WithLeadingTrivia(leadingTrivia); var newRoot = root.ReplaceNode(node, newNode); var newTree = newRoot.SyntaxTree; var changes = newTree.GetChanges(oldTree); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal("o", changes[0].NewText); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteWorkspaceTelemetryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Telemetry { [ExportWorkspaceService(typeof(IWorkspaceTelemetryService)), Shared] internal sealed class RemoteWorkspaceTelemetryService : AbstractWorkspaceTelemetryService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteWorkspaceTelemetryService() { } protected override ILogger CreateLogger(TelemetrySession telemetrySession) => AggregateLogger.Create( new VSTelemetryLogger(telemetrySession), Logger.GetLogger()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Telemetry { [ExportWorkspaceService(typeof(IWorkspaceTelemetryService)), Shared] internal sealed class RemoteWorkspaceTelemetryService : AbstractWorkspaceTelemetryService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteWorkspaceTelemetryService() { } protected override ILogger CreateLogger(TelemetrySession telemetrySession) => AggregateLogger.Create( new VSTelemetryLogger(telemetrySession), Logger.GetLogger()); } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.ConvertNumericLiteral { internal abstract class AbstractConvertNumericLiteralCodeRefactoringProvider<TNumericLiteralExpression> : CodeRefactoringProvider where TNumericLiteralExpression : SyntaxNode { protected abstract (string hexPrefix, string binaryPrefix) GetNumericLiteralPrefixes(); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var numericToken = await GetNumericTokenAsync(context).ConfigureAwait(false); if (numericToken == default || numericToken.ContainsDiagnostics) { return; } var syntaxNode = numericToken.GetRequiredParent(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = semanticModel.GetTypeInfo(syntaxNode, cancellationToken).Type; if (symbol == null) { return; } if (!IsIntegral(symbol.SpecialType)) { return; } var valueOpt = semanticModel.GetConstantValue(syntaxNode); if (!valueOpt.HasValue) { return; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var value = IntegerUtilities.ToInt64(valueOpt.Value); var numericText = numericToken.ToString(); var (hexPrefix, binaryPrefix) = GetNumericLiteralPrefixes(); var (prefix, number, suffix) = GetNumericLiteralParts(numericText, hexPrefix, binaryPrefix); var kind = string.IsNullOrEmpty(prefix) ? NumericKind.Decimal : prefix.Equals(hexPrefix, StringComparison.OrdinalIgnoreCase) ? NumericKind.Hexadecimal : prefix.Equals(binaryPrefix, StringComparison.OrdinalIgnoreCase) ? NumericKind.Binary : NumericKind.Unknown; if (kind == NumericKind.Unknown) { return; } if (kind != NumericKind.Decimal) { RegisterRefactoringWithResult(value.ToString(), FeaturesResources.Convert_to_decimal); } if (kind != NumericKind.Binary) { RegisterRefactoringWithResult(binaryPrefix + Convert.ToString(value, toBase: 2), FeaturesResources.Convert_to_binary); } if (kind != NumericKind.Hexadecimal) { RegisterRefactoringWithResult(hexPrefix + value.ToString("X"), FeaturesResources.Convert_to_hex); } const string DigitSeparator = "_"; if (numericText.Contains(DigitSeparator)) { RegisterRefactoringWithResult(prefix + number.Replace(DigitSeparator, string.Empty), FeaturesResources.Remove_separators); } else { switch (kind) { case NumericKind.Decimal when number.Length > 3: RegisterRefactoringWithResult(AddSeparators(number, interval: 3), FeaturesResources.Separate_thousands); break; case NumericKind.Hexadecimal when number.Length > 4: RegisterRefactoringWithResult(hexPrefix + AddSeparators(number, interval: 4), FeaturesResources.Separate_words); break; case NumericKind.Binary when number.Length > 4: RegisterRefactoringWithResult(binaryPrefix + AddSeparators(number, interval: 4), FeaturesResources.Separate_nibbles); break; } } void RegisterRefactoringWithResult(string text, string title) { context.RegisterRefactoring( new MyCodeAction(title, c => ReplaceTokenAsync(document, root, numericToken, value, text, suffix)), numericToken.Span); } } private static Task<Document> ReplaceTokenAsync(Document document, SyntaxNode root, SyntaxToken numericToken, long value, string text, string suffix) { var generator = SyntaxGenerator.GetGenerator(document); var updatedToken = generator.NumericLiteralToken(text + suffix, (ulong)value) .WithTriviaFrom(numericToken); var updatedRoot = root.ReplaceToken(numericToken, updatedToken); return Task.FromResult(document.WithSyntaxRoot(updatedRoot)); } internal virtual async Task<SyntaxToken> GetNumericTokenAsync(CodeRefactoringContext context) { var syntaxFacts = context.Document.GetRequiredLanguageService<ISyntaxFactsService>(); var literalNode = await context.TryGetRelevantNodeAsync<TNumericLiteralExpression>().ConfigureAwait(false); var numericLiteralExpressionNode = syntaxFacts.IsNumericLiteralExpression(literalNode) ? literalNode : null; return numericLiteralExpressionNode != null ? numericLiteralExpressionNode.GetFirstToken() // We know that TNumericLiteralExpression has always only one token: NumericLiteralToken : default; } private static (string prefix, string number, string suffix) GetNumericLiteralParts(string numericText, string hexPrefix, string binaryPrefix) { // Match literal text and extract out base prefix, type suffix and the number itself. var groups = Regex.Match(numericText, $"({hexPrefix}|{binaryPrefix})?([_0-9a-f]+)(.*)", RegexOptions.IgnoreCase).Groups; return (prefix: groups[1].Value, number: groups[2].Value, suffix: groups[3].Value); } private static string AddSeparators(string numericText, int interval) { // Insert digit separators in the given interval. var result = Regex.Replace(numericText, $"(.{{{interval}}})", "_$1", RegexOptions.RightToLeft); // Fix for the case "0x_1111" that is not supported yet. return result[0] == '_' ? result[1..] : result; } private static bool IsIntegral(SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } } private enum NumericKind { Unknown, Decimal, Binary, Hexadecimal } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.ConvertNumericLiteral { internal abstract class AbstractConvertNumericLiteralCodeRefactoringProvider<TNumericLiteralExpression> : CodeRefactoringProvider where TNumericLiteralExpression : SyntaxNode { protected abstract (string hexPrefix, string binaryPrefix) GetNumericLiteralPrefixes(); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var numericToken = await GetNumericTokenAsync(context).ConfigureAwait(false); if (numericToken == default || numericToken.ContainsDiagnostics) { return; } var syntaxNode = numericToken.GetRequiredParent(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = semanticModel.GetTypeInfo(syntaxNode, cancellationToken).Type; if (symbol == null) { return; } if (!IsIntegral(symbol.SpecialType)) { return; } var valueOpt = semanticModel.GetConstantValue(syntaxNode); if (!valueOpt.HasValue) { return; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var value = IntegerUtilities.ToInt64(valueOpt.Value); var numericText = numericToken.ToString(); var (hexPrefix, binaryPrefix) = GetNumericLiteralPrefixes(); var (prefix, number, suffix) = GetNumericLiteralParts(numericText, hexPrefix, binaryPrefix); var kind = string.IsNullOrEmpty(prefix) ? NumericKind.Decimal : prefix.Equals(hexPrefix, StringComparison.OrdinalIgnoreCase) ? NumericKind.Hexadecimal : prefix.Equals(binaryPrefix, StringComparison.OrdinalIgnoreCase) ? NumericKind.Binary : NumericKind.Unknown; if (kind == NumericKind.Unknown) { return; } if (kind != NumericKind.Decimal) { RegisterRefactoringWithResult(value.ToString(), FeaturesResources.Convert_to_decimal); } if (kind != NumericKind.Binary) { RegisterRefactoringWithResult(binaryPrefix + Convert.ToString(value, toBase: 2), FeaturesResources.Convert_to_binary); } if (kind != NumericKind.Hexadecimal) { RegisterRefactoringWithResult(hexPrefix + value.ToString("X"), FeaturesResources.Convert_to_hex); } const string DigitSeparator = "_"; if (numericText.Contains(DigitSeparator)) { RegisterRefactoringWithResult(prefix + number.Replace(DigitSeparator, string.Empty), FeaturesResources.Remove_separators); } else { switch (kind) { case NumericKind.Decimal when number.Length > 3: RegisterRefactoringWithResult(AddSeparators(number, interval: 3), FeaturesResources.Separate_thousands); break; case NumericKind.Hexadecimal when number.Length > 4: RegisterRefactoringWithResult(hexPrefix + AddSeparators(number, interval: 4), FeaturesResources.Separate_words); break; case NumericKind.Binary when number.Length > 4: RegisterRefactoringWithResult(binaryPrefix + AddSeparators(number, interval: 4), FeaturesResources.Separate_nibbles); break; } } void RegisterRefactoringWithResult(string text, string title) { context.RegisterRefactoring( new MyCodeAction(title, c => ReplaceTokenAsync(document, root, numericToken, value, text, suffix)), numericToken.Span); } } private static Task<Document> ReplaceTokenAsync(Document document, SyntaxNode root, SyntaxToken numericToken, long value, string text, string suffix) { var generator = SyntaxGenerator.GetGenerator(document); var updatedToken = generator.NumericLiteralToken(text + suffix, (ulong)value) .WithTriviaFrom(numericToken); var updatedRoot = root.ReplaceToken(numericToken, updatedToken); return Task.FromResult(document.WithSyntaxRoot(updatedRoot)); } internal virtual async Task<SyntaxToken> GetNumericTokenAsync(CodeRefactoringContext context) { var syntaxFacts = context.Document.GetRequiredLanguageService<ISyntaxFactsService>(); var literalNode = await context.TryGetRelevantNodeAsync<TNumericLiteralExpression>().ConfigureAwait(false); var numericLiteralExpressionNode = syntaxFacts.IsNumericLiteralExpression(literalNode) ? literalNode : null; return numericLiteralExpressionNode != null ? numericLiteralExpressionNode.GetFirstToken() // We know that TNumericLiteralExpression has always only one token: NumericLiteralToken : default; } private static (string prefix, string number, string suffix) GetNumericLiteralParts(string numericText, string hexPrefix, string binaryPrefix) { // Match literal text and extract out base prefix, type suffix and the number itself. var groups = Regex.Match(numericText, $"({hexPrefix}|{binaryPrefix})?([_0-9a-f]+)(.*)", RegexOptions.IgnoreCase).Groups; return (prefix: groups[1].Value, number: groups[2].Value, suffix: groups[3].Value); } private static string AddSeparators(string numericText, int interval) { // Insert digit separators in the given interval. var result = Regex.Replace(numericText, $"(.{{{interval}}})", "_$1", RegexOptions.RightToLeft); // Fix for the case "0x_1111" that is not supported yet. return result[0] == '_' ? result[1..] : result; } private static bool IsIntegral(SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } } private enum NumericKind { Unknown, Decimal, Binary, Hexadecimal } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/CSharpTest/Debugging/DataTipInfoGetterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Debugging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { [UseExportProvider] public class DataTipInfoGetterTests { private static async Task TestAsync(string markup, string expectedText = null) { await TestSpanGetterAsync(markup, async (document, position, expectedSpan) => { var result = await DataTipInfoGetter.GetInfoAsync(document, position, CancellationToken.None); Assert.Equal(expectedSpan, result.Span); Assert.Equal(expectedText, result.Text); }); } private static async Task TestNoDataTipAsync(string markup) { await TestSpanGetterAsync(markup, async (document, position, expectedSpan) => { var result = await DataTipInfoGetter.GetInfoAsync(document, position, CancellationToken.None); Assert.True(result.IsDefault); }); } private static async Task TestSpanGetterAsync(string markup, Func<Document, int, TextSpan?, Task> continuation) { using var workspace = TestWorkspace.CreateCSharp(markup); var testHostDocument = workspace.Documents.Single(); var position = testHostDocument.CursorPosition.Value; var expectedSpan = testHostDocument.SelectedSpans.Any() ? testHostDocument.SelectedSpans.Single() : (TextSpan?)null; await continuation( workspace.CurrentSolution.Projects.First().Documents.First(), position, expectedSpan); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestCSharpLanguageDebugInfoGetDataTipSpanAndText() { await TestAsync("class [|C$$|] { }"); await TestAsync("struct [|C$$|] { }"); await TestAsync("interface [|C$$|] { }"); await TestAsync("enum [|C$$|] { }"); await TestAsync("delegate void [|C$$|] ();"); // Without the space, that position is actually on the open paren. } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test1() { await TestAsync( @"class C { void Goo() { [|Sys$$tem|].Console.WriteLine(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test2() { await TestAsync( @"class C { void Goo() { [|System$$.Console|].WriteLine(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test3() { await TestAsync( @"class C { void Goo() { [|System.$$Console|].WriteLine(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test4() { await TestAsync( @"class C { void Goo() { [|System.Con$$sole|].WriteLine(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test5() { await TestAsync( @"class C { void Goo() { [|System.Console.Wri$$teLine|](args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test6() { await TestNoDataTipAsync( @"class C { void Goo() { [|System.Console.WriteLine|]$$(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test7() { await TestAsync( @"class C { void Goo() { System.Console.WriteLine($$[|args|]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test8() { await TestNoDataTipAsync( @"class C { void Goo() { [|System.Console.WriteLine|](args$$); } }"); } [Fact] public async Task TestVar() { await TestAsync( @"class C { void Goo() { [|va$$r|] v = 0; } }", "int"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestVariableType() { await TestAsync( @"class C { void Goo() { [|in$$t|] i = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestVariableIdentifier() { await TestAsync( @"class C { void Goo() { int [|$$i|] = 0; } }"); } [WorkItem(539910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539910")] [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestLiterals() { await TestAsync( @"class C { void Goo() { int i = [|4$$2|]; } }", "int"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestNonExpressions() { await TestNoDataTipAsync( @"class C { void Goo() { int i = 42; }$$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestParameterIdentifier() { await TestAsync( @"class C { void Goo(int [|$$i|]) { } }"); } [WorkItem(942699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942699")] [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestCatchIdentifier() { await TestAsync( @"class C { void Goo() { try { } catch (System.Exception [|$$e|]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestEvent() { await TestAsync( @"class C { event System.Action [|$$E|]; }"); await TestAsync( @"class C { event System.Action [|$$E|] { add { } remove { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestMethod() { await TestAsync( @"class C { int [|$$M|]() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestTypeParameter() { await TestAsync("class C<T, [|$$U|], V> { }"); await TestAsync( @"class C { void M<T, [|$$U|]>() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task UsingAlias() { await TestAsync( @"using [|$$S|] = Static; static class Static { }"); } [WorkItem(540921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540921")] [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestForEachIdentifier() { await TestAsync( @"class C { void Goo(string[] args) { foreach (string [|$$s|] in args) { } } }"); } [WorkItem(546328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546328")] [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestProperty() { await TestAsync( @"namespace ConsoleApplication16 { class C { public int [|$$goo|] { get; private set; } // hover over me public C() { this.goo = 1; } public int Goo() { return 2; // breakpoint here } } class Program { static void Main(string[] args) { new C().Goo(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestQueryIdentifier() { await TestAsync( // From @"class C { object Goo(string[] args) { return from [|$$a|] in args select a; } }"); await TestAsync( // Let @"class C { object Goo(string[] args) { return from a in args let [|$$b|] = ""END"" select a + b; } }"); await TestAsync( // Join @"class C { object Goo(string[] args) { return from a in args join [|$$b|] in args on a equals b; } }"); await TestAsync( // Join Into @"class C { object Goo(string[] args) { return from a in args join b in args on a equals b into [|$$c|]; } }"); await TestAsync( // Continuation @"class C { object Goo(string[] args) { return from a in args select a into [|$$b|] from c in b select c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips), WorkItem(1077843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077843")] public async Task TestConditionalAccessExpression() { var sourceTemplate = @" class A {{ B B; object M() {{ return {0}; }} }} class B {{ C C; }} class C {{ D D; }} class D {{ }} "; // One level. await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|]")); // Two levels. await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|].C")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.$$C|]")); await TestAsync(string.Format(sourceTemplate, "[|Me.$$B|]?.C")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.$$C|]")); await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|]?.C")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.$$C|]")); // Three levels. await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|].C.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.$$C|].D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.C.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me.$$B|]?.C.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.$$C|].D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.C.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me.$$B|].C?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B.$$C|]?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B.C?.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|]?.C.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.$$C|].D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.C.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|].C?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.$$C|]?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.C?.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me.$$B|]?.C?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.$$C|]?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.C?.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|]?.C?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.$$C|]?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.C?.$$D|]")); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips), WorkItem(1077843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077843")] public async Task TestConditionalAccessExpression_Trivia() { var sourceTemplate = @" class A {{ B B; object M() {{ return {0}; }} }} class B {{ C C; }} class C {{ }} "; await TestAsync(string.Format(sourceTemplate, "/*1*/[|$$Me|]/*2*/?./*3*/B/*4*/?./*5*/C/*6*/")); await TestAsync(string.Format(sourceTemplate, "/*1*/[|Me/*2*/?./*3*/$$B|]/*4*/?./*5*/C/*6*/")); await TestAsync(string.Format(sourceTemplate, "/*1*/[|Me/*2*/?./*3*/B/*4*/?./*5*/$$C|]/*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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Debugging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { [UseExportProvider] public class DataTipInfoGetterTests { private static async Task TestAsync(string markup, string expectedText = null) { await TestSpanGetterAsync(markup, async (document, position, expectedSpan) => { var result = await DataTipInfoGetter.GetInfoAsync(document, position, CancellationToken.None); Assert.Equal(expectedSpan, result.Span); Assert.Equal(expectedText, result.Text); }); } private static async Task TestNoDataTipAsync(string markup) { await TestSpanGetterAsync(markup, async (document, position, expectedSpan) => { var result = await DataTipInfoGetter.GetInfoAsync(document, position, CancellationToken.None); Assert.True(result.IsDefault); }); } private static async Task TestSpanGetterAsync(string markup, Func<Document, int, TextSpan?, Task> continuation) { using var workspace = TestWorkspace.CreateCSharp(markup); var testHostDocument = workspace.Documents.Single(); var position = testHostDocument.CursorPosition.Value; var expectedSpan = testHostDocument.SelectedSpans.Any() ? testHostDocument.SelectedSpans.Single() : (TextSpan?)null; await continuation( workspace.CurrentSolution.Projects.First().Documents.First(), position, expectedSpan); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestCSharpLanguageDebugInfoGetDataTipSpanAndText() { await TestAsync("class [|C$$|] { }"); await TestAsync("struct [|C$$|] { }"); await TestAsync("interface [|C$$|] { }"); await TestAsync("enum [|C$$|] { }"); await TestAsync("delegate void [|C$$|] ();"); // Without the space, that position is actually on the open paren. } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test1() { await TestAsync( @"class C { void Goo() { [|Sys$$tem|].Console.WriteLine(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test2() { await TestAsync( @"class C { void Goo() { [|System$$.Console|].WriteLine(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test3() { await TestAsync( @"class C { void Goo() { [|System.$$Console|].WriteLine(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test4() { await TestAsync( @"class C { void Goo() { [|System.Con$$sole|].WriteLine(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test5() { await TestAsync( @"class C { void Goo() { [|System.Console.Wri$$teLine|](args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test6() { await TestNoDataTipAsync( @"class C { void Goo() { [|System.Console.WriteLine|]$$(args); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test7() { await TestAsync( @"class C { void Goo() { System.Console.WriteLine($$[|args|]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task Test8() { await TestNoDataTipAsync( @"class C { void Goo() { [|System.Console.WriteLine|](args$$); } }"); } [Fact] public async Task TestVar() { await TestAsync( @"class C { void Goo() { [|va$$r|] v = 0; } }", "int"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestVariableType() { await TestAsync( @"class C { void Goo() { [|in$$t|] i = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestVariableIdentifier() { await TestAsync( @"class C { void Goo() { int [|$$i|] = 0; } }"); } [WorkItem(539910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539910")] [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestLiterals() { await TestAsync( @"class C { void Goo() { int i = [|4$$2|]; } }", "int"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestNonExpressions() { await TestNoDataTipAsync( @"class C { void Goo() { int i = 42; }$$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestParameterIdentifier() { await TestAsync( @"class C { void Goo(int [|$$i|]) { } }"); } [WorkItem(942699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942699")] [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestCatchIdentifier() { await TestAsync( @"class C { void Goo() { try { } catch (System.Exception [|$$e|]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestEvent() { await TestAsync( @"class C { event System.Action [|$$E|]; }"); await TestAsync( @"class C { event System.Action [|$$E|] { add { } remove { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestMethod() { await TestAsync( @"class C { int [|$$M|]() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestTypeParameter() { await TestAsync("class C<T, [|$$U|], V> { }"); await TestAsync( @"class C { void M<T, [|$$U|]>() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task UsingAlias() { await TestAsync( @"using [|$$S|] = Static; static class Static { }"); } [WorkItem(540921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540921")] [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestForEachIdentifier() { await TestAsync( @"class C { void Goo(string[] args) { foreach (string [|$$s|] in args) { } } }"); } [WorkItem(546328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546328")] [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestProperty() { await TestAsync( @"namespace ConsoleApplication16 { class C { public int [|$$goo|] { get; private set; } // hover over me public C() { this.goo = 1; } public int Goo() { return 2; // breakpoint here } } class Program { static void Main(string[] args) { new C().Goo(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public async Task TestQueryIdentifier() { await TestAsync( // From @"class C { object Goo(string[] args) { return from [|$$a|] in args select a; } }"); await TestAsync( // Let @"class C { object Goo(string[] args) { return from a in args let [|$$b|] = ""END"" select a + b; } }"); await TestAsync( // Join @"class C { object Goo(string[] args) { return from a in args join [|$$b|] in args on a equals b; } }"); await TestAsync( // Join Into @"class C { object Goo(string[] args) { return from a in args join b in args on a equals b into [|$$c|]; } }"); await TestAsync( // Continuation @"class C { object Goo(string[] args) { return from a in args select a into [|$$b|] from c in b select c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips), WorkItem(1077843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077843")] public async Task TestConditionalAccessExpression() { var sourceTemplate = @" class A {{ B B; object M() {{ return {0}; }} }} class B {{ C C; }} class C {{ D D; }} class D {{ }} "; // One level. await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|]")); // Two levels. await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|].C")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.$$C|]")); await TestAsync(string.Format(sourceTemplate, "[|Me.$$B|]?.C")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.$$C|]")); await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|]?.C")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.$$C|]")); // Three levels. await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|].C.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.$$C|].D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.C.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me.$$B|]?.C.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.$$C|].D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.C.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me.$$B|].C?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B.$$C|]?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B.C?.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|]?.C.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.$$C|].D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.C.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|].C?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.$$C|]?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B.C?.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me.$$B|]?.C?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.$$C|]?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me.B?.C?.$$D|]")); await TestAsync(string.Format(sourceTemplate, "[|Me?.$$B|]?.C?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.$$C|]?.D")); await TestAsync(string.Format(sourceTemplate, "[|Me?.B?.C?.$$D|]")); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips), WorkItem(1077843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077843")] public async Task TestConditionalAccessExpression_Trivia() { var sourceTemplate = @" class A {{ B B; object M() {{ return {0}; }} }} class B {{ C C; }} class C {{ }} "; await TestAsync(string.Format(sourceTemplate, "/*1*/[|$$Me|]/*2*/?./*3*/B/*4*/?./*5*/C/*6*/")); await TestAsync(string.Format(sourceTemplate, "/*1*/[|Me/*2*/?./*3*/$$B|]/*4*/?./*5*/C/*6*/")); await TestAsync(string.Format(sourceTemplate, "/*1*/[|Me/*2*/?./*3*/B/*4*/?./*5*/$$C|]/*6*/")); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/Remote/Core/PublicAPI.Unshipped.txt
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/Core/Portable/CodeActions/Annotations/WarningAnnotation.cs
// Licensed to the .NET Foundation under one or more 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.CodeActions { /// <summary> /// Apply this annotation to a SyntaxNode to indicate that a warning message should be presented to the user. /// </summary> public static class WarningAnnotation { public const string Kind = "CodeAction_Warning"; public static SyntaxAnnotation Create(string description) => new(Kind, description); public static string? GetDescription(SyntaxAnnotation annotation) => annotation.Data; } }
// Licensed to the .NET Foundation under one or more 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.CodeActions { /// <summary> /// Apply this annotation to a SyntaxNode to indicate that a warning message should be presented to the user. /// </summary> public static class WarningAnnotation { public const string Kind = "CodeAction_Warning"; public static SyntaxAnnotation Create(string description) => new(Kind, description); public static string? GetDescription(SyntaxAnnotation annotation) => annotation.Data; } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Features/Core/Portable/FindUsages/DefinitionItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { /// <summary> /// Information about a symbol's definition that can be displayed in an editor /// and used for navigation. /// /// Standard implmentations can be obtained through the various <see cref="DefinitionItem"/>.Create /// overloads. /// /// Subclassing is also supported for scenarios that fall outside the bounds of /// these common cases. /// </summary> internal abstract partial class DefinitionItem { /// <summary> /// The definition item corresponding to the initial symbol the user was trying to find. This item should get /// prominent placement in the final UI for the user. /// </summary> internal const string Primary = nameof(Primary); // Existing behavior is to do up to two lookups for 3rd party navigation for FAR. One // for the symbol itself and one for a 'fallback' symbol. For example, if we're FARing // on a constructor, then the fallback symbol will be the actual type that the constructor // is contained within. internal const string RQNameKey1 = nameof(RQNameKey1); internal const string RQNameKey2 = nameof(RQNameKey2); /// <summary> /// For metadata symbols we encode information in the <see cref="Properties"/> so we can /// retrieve the symbol later on when navigating. This is needed so that we can go to /// metadata-as-source for metadata symbols. We need to store the <see cref="SymbolKey"/> /// for the symbol and the project ID that originated the symbol. With these we can correctly recover the symbol. /// </summary> private const string MetadataSymbolKey = nameof(MetadataSymbolKey); private const string MetadataSymbolOriginatingProjectIdGuid = nameof(MetadataSymbolOriginatingProjectIdGuid); private const string MetadataSymbolOriginatingProjectIdDebugName = nameof(MetadataSymbolOriginatingProjectIdDebugName); /// <summary> /// If this item is something that cannot be navigated to. We store this in our /// <see cref="Properties"/> to act as an explicit marker that navigation is not possible. /// </summary> private const string NonNavigable = nameof(NonNavigable); /// <summary> /// Descriptive tags from <see cref="WellKnownTags"/>. These tags may influence how the /// item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Additional properties that can be attached to the definition for clients that want to /// keep track of additional data. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Additional diplayable properties that can be attached to the definition for clients that want to /// display additional data. /// </summary> public ImmutableDictionary<string, string> DisplayableProperties { get; } /// <summary> /// The DisplayParts just for the name of this definition. Generally used only for /// error messages. /// </summary> public ImmutableArray<TaggedText> NameDisplayParts { get; } /// <summary> /// The full display parts for this definition. Displayed in a classified /// manner when possible. /// </summary> public ImmutableArray<TaggedText> DisplayParts { get; } /// <summary> /// Where the location originally came from (for example, the containing assembly or /// project name). May be used in the presentation of a definition. /// </summary> public ImmutableArray<TaggedText> OriginationParts { get; } /// <summary> /// Additional locations to present in the UI. A definition may have multiple locations /// for cases like partial types/members. /// </summary> public ImmutableArray<DocumentSpan> SourceSpans { get; } /// <summary> /// Whether or not this definition should be presented if we never found any references to /// it. For example, when searching for a property, the FindReferences engine will cascade /// to the accessors in case any code specifically called those accessors (can happen in /// cross-language cases). However, in the normal case where there were no calls specifically /// to the accessor, we would not want to display them in the UI. /// /// For most definitions we will want to display them, even if no references were found. /// This property allows for this customization in behavior. /// </summary> public bool DisplayIfNoReferences { get; } internal abstract bool IsExternal { get; } // F# uses this protected DefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, bool displayIfNoReferences) : this( tags, displayParts, nameDisplayParts, originationParts, sourceSpans, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences) { } protected DefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts.IsDefaultOrEmpty ? displayParts : nameDisplayParts; OriginationParts = originationParts.NullToEmpty(); SourceSpans = sourceSpans.NullToEmpty(); Properties = properties ?? ImmutableDictionary<string, string>.Empty; DisplayableProperties = displayableProperties ?? ImmutableDictionary<string, string>.Empty; DisplayIfNoReferences = displayIfNoReferences; if (Properties.ContainsKey(MetadataSymbolKey)) { Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdGuid)); Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdDebugName)); } } [Obsolete("Override CanNavigateToAsync instead", error: false)] public abstract bool CanNavigateTo(Workspace workspace, CancellationToken cancellationToken); [Obsolete("Override TryNavigateToAsync instead", error: false)] public abstract bool TryNavigateTo(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken); public virtual Task<bool> CanNavigateToAsync(Workspace workspace, CancellationToken cancellationToken) { #pragma warning disable CS0618 // Type or member is obsolete return Task.FromResult(CanNavigateTo(workspace, cancellationToken)); #pragma warning restore CS0618 // Type or member is obsolete } public virtual Task<bool> TryNavigateToAsync(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken) { #pragma warning disable CS0618 // Type or member is obsolete return Task.FromResult(TryNavigateTo(workspace, showInPreviewTab, activateTab, cancellationToken)); #pragma warning restore CS0618 // Type or member is obsolete } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, DocumentSpan sourceSpan, ImmutableArray<TaggedText> nameDisplayParts = default, bool displayIfNoReferences = true) { return Create( tags, displayParts, ImmutableArray.Create(sourceSpan), nameDisplayParts, displayIfNoReferences); } // Kept around for binary compat with F#/TypeScript. public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts, bool displayIfNoReferences) { return Create( tags, displayParts, sourceSpans, nameDisplayParts, properties: null, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts = default, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { return Create(tags, displayParts, sourceSpans, nameDisplayParts, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences); } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts = default, ImmutableDictionary<string, string> properties = null, ImmutableDictionary<string, string> displayableProperties = null, bool displayIfNoReferences = true) { if (sourceSpans.Length == 0) { throw new ArgumentException($"{nameof(sourceSpans)} cannot be empty."); } var firstDocument = sourceSpans[0].Document; var originationParts = ImmutableArray.Create( new TaggedText(TextTags.Text, firstDocument.Project.Name)); return new DefaultDefinitionItem( tags, displayParts, nameDisplayParts, originationParts, sourceSpans, properties, displayableProperties, displayIfNoReferences); } internal static DefinitionItem CreateMetadataDefinition( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, Solution solution, ISymbol symbol, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { properties ??= ImmutableDictionary<string, string>.Empty; var symbolKey = symbol.GetSymbolKey().ToString(); var projectId = solution.GetOriginatingProjectId(symbol); Contract.ThrowIfNull(projectId); properties = properties.Add(MetadataSymbolKey, symbolKey) .Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString()) .Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName); var originationParts = GetOriginationParts(symbol); return new DefaultDefinitionItem( tags, displayParts, nameDisplayParts, originationParts, sourceSpans: ImmutableArray<DocumentSpan>.Empty, properties: properties, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } // Kept around for binary compat with F#/TypeScript. public static DefinitionItem CreateNonNavigableItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> originationParts, bool displayIfNoReferences) { return CreateNonNavigableItem( tags, displayParts, originationParts, properties: null, displayIfNoReferences: displayIfNoReferences); } public static DefinitionItem CreateNonNavigableItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> originationParts = default, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { properties ??= ImmutableDictionary<string, string>.Empty; properties = properties.Add(NonNavigable, ""); return new DefaultDefinitionItem( tags: tags, displayParts: displayParts, nameDisplayParts: ImmutableArray<TaggedText>.Empty, originationParts: originationParts, sourceSpans: ImmutableArray<DocumentSpan>.Empty, properties: properties, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } internal static ImmutableArray<TaggedText> GetOriginationParts(ISymbol symbol) { // We don't show an origination location for a namespace because it can span over // both metadata assemblies and source projects. // // Otherwise show the assembly this symbol came from as the Origination of // the DefinitionItem. if (symbol.Kind != SymbolKind.Namespace) { var assemblyName = symbol.ContainingAssembly?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); if (!string.IsNullOrWhiteSpace(assemblyName)) { return ImmutableArray.Create(new TaggedText(TextTags.Assembly, assemblyName)); } } return ImmutableArray<TaggedText>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { /// <summary> /// Information about a symbol's definition that can be displayed in an editor /// and used for navigation. /// /// Standard implmentations can be obtained through the various <see cref="DefinitionItem"/>.Create /// overloads. /// /// Subclassing is also supported for scenarios that fall outside the bounds of /// these common cases. /// </summary> internal abstract partial class DefinitionItem { /// <summary> /// The definition item corresponding to the initial symbol the user was trying to find. This item should get /// prominent placement in the final UI for the user. /// </summary> internal const string Primary = nameof(Primary); // Existing behavior is to do up to two lookups for 3rd party navigation for FAR. One // for the symbol itself and one for a 'fallback' symbol. For example, if we're FARing // on a constructor, then the fallback symbol will be the actual type that the constructor // is contained within. internal const string RQNameKey1 = nameof(RQNameKey1); internal const string RQNameKey2 = nameof(RQNameKey2); /// <summary> /// For metadata symbols we encode information in the <see cref="Properties"/> so we can /// retrieve the symbol later on when navigating. This is needed so that we can go to /// metadata-as-source for metadata symbols. We need to store the <see cref="SymbolKey"/> /// for the symbol and the project ID that originated the symbol. With these we can correctly recover the symbol. /// </summary> private const string MetadataSymbolKey = nameof(MetadataSymbolKey); private const string MetadataSymbolOriginatingProjectIdGuid = nameof(MetadataSymbolOriginatingProjectIdGuid); private const string MetadataSymbolOriginatingProjectIdDebugName = nameof(MetadataSymbolOriginatingProjectIdDebugName); /// <summary> /// If this item is something that cannot be navigated to. We store this in our /// <see cref="Properties"/> to act as an explicit marker that navigation is not possible. /// </summary> private const string NonNavigable = nameof(NonNavigable); /// <summary> /// Descriptive tags from <see cref="WellKnownTags"/>. These tags may influence how the /// item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Additional properties that can be attached to the definition for clients that want to /// keep track of additional data. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Additional diplayable properties that can be attached to the definition for clients that want to /// display additional data. /// </summary> public ImmutableDictionary<string, string> DisplayableProperties { get; } /// <summary> /// The DisplayParts just for the name of this definition. Generally used only for /// error messages. /// </summary> public ImmutableArray<TaggedText> NameDisplayParts { get; } /// <summary> /// The full display parts for this definition. Displayed in a classified /// manner when possible. /// </summary> public ImmutableArray<TaggedText> DisplayParts { get; } /// <summary> /// Where the location originally came from (for example, the containing assembly or /// project name). May be used in the presentation of a definition. /// </summary> public ImmutableArray<TaggedText> OriginationParts { get; } /// <summary> /// Additional locations to present in the UI. A definition may have multiple locations /// for cases like partial types/members. /// </summary> public ImmutableArray<DocumentSpan> SourceSpans { get; } /// <summary> /// Whether or not this definition should be presented if we never found any references to /// it. For example, when searching for a property, the FindReferences engine will cascade /// to the accessors in case any code specifically called those accessors (can happen in /// cross-language cases). However, in the normal case where there were no calls specifically /// to the accessor, we would not want to display them in the UI. /// /// For most definitions we will want to display them, even if no references were found. /// This property allows for this customization in behavior. /// </summary> public bool DisplayIfNoReferences { get; } internal abstract bool IsExternal { get; } // F# uses this protected DefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, bool displayIfNoReferences) : this( tags, displayParts, nameDisplayParts, originationParts, sourceSpans, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences) { } protected DefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts.IsDefaultOrEmpty ? displayParts : nameDisplayParts; OriginationParts = originationParts.NullToEmpty(); SourceSpans = sourceSpans.NullToEmpty(); Properties = properties ?? ImmutableDictionary<string, string>.Empty; DisplayableProperties = displayableProperties ?? ImmutableDictionary<string, string>.Empty; DisplayIfNoReferences = displayIfNoReferences; if (Properties.ContainsKey(MetadataSymbolKey)) { Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdGuid)); Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdDebugName)); } } [Obsolete("Override CanNavigateToAsync instead", error: false)] public abstract bool CanNavigateTo(Workspace workspace, CancellationToken cancellationToken); [Obsolete("Override TryNavigateToAsync instead", error: false)] public abstract bool TryNavigateTo(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken); public virtual Task<bool> CanNavigateToAsync(Workspace workspace, CancellationToken cancellationToken) { #pragma warning disable CS0618 // Type or member is obsolete return Task.FromResult(CanNavigateTo(workspace, cancellationToken)); #pragma warning restore CS0618 // Type or member is obsolete } public virtual Task<bool> TryNavigateToAsync(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken) { #pragma warning disable CS0618 // Type or member is obsolete return Task.FromResult(TryNavigateTo(workspace, showInPreviewTab, activateTab, cancellationToken)); #pragma warning restore CS0618 // Type or member is obsolete } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, DocumentSpan sourceSpan, ImmutableArray<TaggedText> nameDisplayParts = default, bool displayIfNoReferences = true) { return Create( tags, displayParts, ImmutableArray.Create(sourceSpan), nameDisplayParts, displayIfNoReferences); } // Kept around for binary compat with F#/TypeScript. public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts, bool displayIfNoReferences) { return Create( tags, displayParts, sourceSpans, nameDisplayParts, properties: null, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts = default, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { return Create(tags, displayParts, sourceSpans, nameDisplayParts, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences); } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts = default, ImmutableDictionary<string, string> properties = null, ImmutableDictionary<string, string> displayableProperties = null, bool displayIfNoReferences = true) { if (sourceSpans.Length == 0) { throw new ArgumentException($"{nameof(sourceSpans)} cannot be empty."); } var firstDocument = sourceSpans[0].Document; var originationParts = ImmutableArray.Create( new TaggedText(TextTags.Text, firstDocument.Project.Name)); return new DefaultDefinitionItem( tags, displayParts, nameDisplayParts, originationParts, sourceSpans, properties, displayableProperties, displayIfNoReferences); } internal static DefinitionItem CreateMetadataDefinition( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, Solution solution, ISymbol symbol, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { properties ??= ImmutableDictionary<string, string>.Empty; var symbolKey = symbol.GetSymbolKey().ToString(); var projectId = solution.GetOriginatingProjectId(symbol); Contract.ThrowIfNull(projectId); properties = properties.Add(MetadataSymbolKey, symbolKey) .Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString()) .Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName); var originationParts = GetOriginationParts(symbol); return new DefaultDefinitionItem( tags, displayParts, nameDisplayParts, originationParts, sourceSpans: ImmutableArray<DocumentSpan>.Empty, properties: properties, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } // Kept around for binary compat with F#/TypeScript. public static DefinitionItem CreateNonNavigableItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> originationParts, bool displayIfNoReferences) { return CreateNonNavigableItem( tags, displayParts, originationParts, properties: null, displayIfNoReferences: displayIfNoReferences); } public static DefinitionItem CreateNonNavigableItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> originationParts = default, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { properties ??= ImmutableDictionary<string, string>.Empty; properties = properties.Add(NonNavigable, ""); return new DefaultDefinitionItem( tags: tags, displayParts: displayParts, nameDisplayParts: ImmutableArray<TaggedText>.Empty, originationParts: originationParts, sourceSpans: ImmutableArray<DocumentSpan>.Empty, properties: properties, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } internal static ImmutableArray<TaggedText> GetOriginationParts(ISymbol symbol) { // We don't show an origination location for a namespace because it can span over // both metadata assemblies and source projects. // // Otherwise show the assembly this symbol came from as the Origination of // the DefinitionItem. if (symbol.Kind != SymbolKind.Namespace) { var assemblyName = symbol.ContainingAssembly?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); if (!string.IsNullOrWhiteSpace(assemblyName)) { return ImmutableArray.Create(new TaggedText(TextTags.Assembly, assemblyName)); } } return ImmutableArray<TaggedText>.Empty; } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractRoslynTableDataSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// A version of ITableDataSource who knows how to connect them to Roslyn solution crawler for live information. /// </summary> internal abstract class AbstractRoslynTableDataSource<TItem, TData> : AbstractTableDataSource<TItem, TData> where TItem : TableItem { public AbstractRoslynTableDataSource(Workspace workspace) : base(workspace) => ConnectToSolutionCrawlerService(workspace); protected ImmutableArray<DocumentId> GetDocumentsWithSameFilePath(Solution solution, DocumentId documentId) { var document = solution.GetDocument(documentId); if (document == null) { return ImmutableArray<DocumentId>.Empty; } return solution.GetDocumentIdsWithFilePath(document.FilePath); } /// <summary> /// Flag indicating if a solution crawler is running incremental analyzers in background. /// We get build progress updates from <see cref="ISolutionCrawlerProgressReporter.ProgressChanged"/>. /// Solution crawler progress events are guaranteed to be invoked in a serial fashion. /// </summary> protected bool IsSolutionCrawlerRunning { get; private set; } private void ConnectToSolutionCrawlerService(Workspace workspace) { var crawlerService = workspace.Services.GetService<ISolutionCrawlerService>(); if (crawlerService == null) { // can happen depends on host such as testing host. return; } var reporter = crawlerService.GetProgressReporter(workspace); reporter.ProgressChanged += OnSolutionCrawlerProgressChanged; // set initial value SolutionCrawlerProgressChanged(reporter.InProgress); } private void OnSolutionCrawlerProgressChanged(object sender, ProgressData progressData) { switch (progressData.Status) { case ProgressStatus.Started: SolutionCrawlerProgressChanged(running: true); break; case ProgressStatus.Stopped: SolutionCrawlerProgressChanged(running: false); break; } } private void SolutionCrawlerProgressChanged(bool running) { IsSolutionCrawlerRunning = running; ChangeStableStateIfRequired(newIsStable: !IsSolutionCrawlerRunning); } protected void ChangeStableStateIfRequired(bool newIsStable) { var oldIsStable = IsStable; if (oldIsStable != newIsStable) { IsStable = newIsStable; ChangeStableState(newIsStable); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// A version of ITableDataSource who knows how to connect them to Roslyn solution crawler for live information. /// </summary> internal abstract class AbstractRoslynTableDataSource<TItem, TData> : AbstractTableDataSource<TItem, TData> where TItem : TableItem { public AbstractRoslynTableDataSource(Workspace workspace) : base(workspace) => ConnectToSolutionCrawlerService(workspace); protected ImmutableArray<DocumentId> GetDocumentsWithSameFilePath(Solution solution, DocumentId documentId) { var document = solution.GetDocument(documentId); if (document == null) { return ImmutableArray<DocumentId>.Empty; } return solution.GetDocumentIdsWithFilePath(document.FilePath); } /// <summary> /// Flag indicating if a solution crawler is running incremental analyzers in background. /// We get build progress updates from <see cref="ISolutionCrawlerProgressReporter.ProgressChanged"/>. /// Solution crawler progress events are guaranteed to be invoked in a serial fashion. /// </summary> protected bool IsSolutionCrawlerRunning { get; private set; } private void ConnectToSolutionCrawlerService(Workspace workspace) { var crawlerService = workspace.Services.GetService<ISolutionCrawlerService>(); if (crawlerService == null) { // can happen depends on host such as testing host. return; } var reporter = crawlerService.GetProgressReporter(workspace); reporter.ProgressChanged += OnSolutionCrawlerProgressChanged; // set initial value SolutionCrawlerProgressChanged(reporter.InProgress); } private void OnSolutionCrawlerProgressChanged(object sender, ProgressData progressData) { switch (progressData.Status) { case ProgressStatus.Started: SolutionCrawlerProgressChanged(running: true); break; case ProgressStatus.Stopped: SolutionCrawlerProgressChanged(running: false); break; } } private void SolutionCrawlerProgressChanged(bool running) { IsSolutionCrawlerRunning = running; ChangeStableStateIfRequired(newIsStable: !IsSolutionCrawlerRunning); } protected void ChangeStableStateIfRequired(bool newIsStable) { var oldIsStable = IsStable; if (oldIsStable != newIsStable) { IsStable = newIsStable; ChangeStableState(newIsStable); } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/Implementation/TodoComments/VisualStudioTodoCommentsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; 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.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TodoComments { [Export(typeof(IVsTypeScriptTodoCommentService))] [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class VisualStudioTodoCommentsService : ForegroundThreadAffinitizedObject, ITodoCommentsListener, ITodoListProvider, IVsTypeScriptTodoCommentService, IEventListener<object>, IDisposable { private readonly VisualStudioWorkspaceImpl _workspace; private readonly EventListenerTracker<ITodoListProvider> _eventListenerTracker; private readonly IAsynchronousOperationListener _asyncListener; private readonly ConcurrentDictionary<DocumentId, ImmutableArray<TodoCommentData>> _documentToInfos = new(); /// <summary> /// Remote service connection. Created on demand when we startup and then /// kept around for the lifetime of this service. /// </summary> private RemoteServiceConnection<IRemoteTodoCommentsDiscoveryService>? _lazyConnection; /// <summary> /// Queue where we enqueue the information we get from OOP to process in batch in the future. /// </summary> private readonly TaskCompletionSource<AsyncBatchingWorkQueue<DocumentAndComments>> _workQueueSource = new(); public event EventHandler<TodoItemsUpdatedArgs>? TodoListUpdated; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTodoCommentsService( VisualStudioWorkspaceImpl workspace, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider, [ImportMany] IEnumerable<Lazy<IEventListener, EventListenerMetadata>> eventListeners) : base(threadingContext) { _workspace = workspace; _eventListenerTracker = new EventListenerTracker<ITodoListProvider>(eventListeners, WellKnownEventListeners.TodoListProvider); _asyncListener = asynchronousOperationListenerProvider.GetListener(FeatureAttribute.TodoCommentList); } 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; _workQueueSource.SetResult( new AsyncBatchingWorkQueue<DocumentAndComments>( TimeSpan.FromSeconds(1), ProcessTodoCommentInfosAsync, _asyncListener, cancellationToken)); var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { ComputeTodoCommentsInCurrentProcess(cancellationToken); return; } // Pass ourselves in as the callback target for the OOP service. As it discovers // todo comments it will call back into us to notify VS about it. _lazyConnection = client.CreateConnection<IRemoteTodoCommentsDiscoveryService>(callbackTarget: this); // Now that we've started, let the VS todo list know to start listening to us _eventListenerTracker.EnsureEventListener(_workspace, 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.ComputeTodoCommentsAsync(callbackId, cancellationToken), cancellationToken).ConfigureAwait(false); } private void ComputeTodoCommentsInCurrentProcess(CancellationToken cancellationToken) { var registrationService = _workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); var analyzerProvider = new InProcTodoCommentsIncrementalAnalyzerProvider(this); registrationService.AddAnalyzerProvider( analyzerProvider, new IncrementalAnalyzerProviderMetadata( nameof(InProcTodoCommentsIncrementalAnalyzerProvider), highPriorityForActiveFile: false, workspaceKinds: WorkspaceKind.Host)); } private ValueTask ProcessTodoCommentInfosAsync( ImmutableArray<DocumentAndComments> docAndCommentsArray, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var _1 = ArrayBuilder<DocumentAndComments>.GetInstance(out var filteredArray); AddFilteredInfos(docAndCommentsArray, filteredArray); foreach (var docAndComments in filteredArray) { var documentId = docAndComments.DocumentId; var newComments = docAndComments.Comments; var oldComments = _documentToInfos.TryGetValue(documentId, out var oldBoxedInfos) ? oldBoxedInfos : ImmutableArray<TodoCommentData>.Empty; // only one thread can be executing ProcessTodoCommentInfosAsync at a time, // so it's safe to remove/add here. if (newComments.IsEmpty) { _documentToInfos.TryRemove(documentId, out _); } else { _documentToInfos[documentId] = newComments; } // If we have someone listening for updates, and our new items are different from // our old ones, then notify them of the change. if (this.TodoListUpdated != null && !oldComments.SequenceEqual(newComments)) { this.TodoListUpdated?.Invoke( this, new TodoItemsUpdatedArgs( documentId, _workspace, _workspace.CurrentSolution, documentId.ProjectId, documentId, newComments)); } } return ValueTaskFactory.CompletedTask; } private void AddFilteredInfos( ImmutableArray<DocumentAndComments> array, ArrayBuilder<DocumentAndComments> filteredArray) { using var _ = PooledHashSet<DocumentId>.GetInstance(out var seenDocumentIds); // Walk the list of todo comments in reverse, and skip any items for a document once // we've already seen it once. That way, we're only reporting the most up to date // information for a document, and we're skipping the stale information. for (var i = array.Length - 1; i >= 0; i--) { var info = array[i]; if (seenDocumentIds.Add(info.DocumentId)) filteredArray.Add(info); } } public ImmutableArray<TodoCommentData> GetTodoItems(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { return _documentToInfos.TryGetValue(documentId, out var values) ? values : ImmutableArray<TodoCommentData>.Empty; } /// <summary> /// Callback from the OOP service back into us. /// </summary> public async ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> infos, CancellationToken cancellationToken) { try { var workQueue = await _workQueueSource.Task.ConfigureAwait(false); workQueue.AddWork(new DocumentAndComments(documentId, infos)); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { // report NFW before returning back to the remote process throw ExceptionUtilities.Unreachable; } } /// <inheritdoc cref="IVsTypeScriptTodoCommentService.ReportTodoCommentsAsync(Document, ImmutableArray{TodoComment}, CancellationToken)"/> async Task IVsTypeScriptTodoCommentService.ReportTodoCommentsAsync( Document document, ImmutableArray<TodoComment> todoComments, CancellationToken cancellationToken) { using var _ = ArrayBuilder<TodoCommentData>.GetInstance(out var converted); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); await TodoComment.ConvertAsync(document, todoComments, converted, cancellationToken).ConfigureAwait(false); await ReportTodoCommentDataAsync( document.Id, converted.ToImmutable(), cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; 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.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TodoComments { [Export(typeof(IVsTypeScriptTodoCommentService))] [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class VisualStudioTodoCommentsService : ForegroundThreadAffinitizedObject, ITodoCommentsListener, ITodoListProvider, IVsTypeScriptTodoCommentService, IEventListener<object>, IDisposable { private readonly VisualStudioWorkspaceImpl _workspace; private readonly EventListenerTracker<ITodoListProvider> _eventListenerTracker; private readonly IAsynchronousOperationListener _asyncListener; private readonly ConcurrentDictionary<DocumentId, ImmutableArray<TodoCommentData>> _documentToInfos = new(); /// <summary> /// Remote service connection. Created on demand when we startup and then /// kept around for the lifetime of this service. /// </summary> private RemoteServiceConnection<IRemoteTodoCommentsDiscoveryService>? _lazyConnection; /// <summary> /// Queue where we enqueue the information we get from OOP to process in batch in the future. /// </summary> private readonly TaskCompletionSource<AsyncBatchingWorkQueue<DocumentAndComments>> _workQueueSource = new(); public event EventHandler<TodoItemsUpdatedArgs>? TodoListUpdated; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTodoCommentsService( VisualStudioWorkspaceImpl workspace, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider, [ImportMany] IEnumerable<Lazy<IEventListener, EventListenerMetadata>> eventListeners) : base(threadingContext) { _workspace = workspace; _eventListenerTracker = new EventListenerTracker<ITodoListProvider>(eventListeners, WellKnownEventListeners.TodoListProvider); _asyncListener = asynchronousOperationListenerProvider.GetListener(FeatureAttribute.TodoCommentList); } 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; _workQueueSource.SetResult( new AsyncBatchingWorkQueue<DocumentAndComments>( TimeSpan.FromSeconds(1), ProcessTodoCommentInfosAsync, _asyncListener, cancellationToken)); var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { ComputeTodoCommentsInCurrentProcess(cancellationToken); return; } // Pass ourselves in as the callback target for the OOP service. As it discovers // todo comments it will call back into us to notify VS about it. _lazyConnection = client.CreateConnection<IRemoteTodoCommentsDiscoveryService>(callbackTarget: this); // Now that we've started, let the VS todo list know to start listening to us _eventListenerTracker.EnsureEventListener(_workspace, 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.ComputeTodoCommentsAsync(callbackId, cancellationToken), cancellationToken).ConfigureAwait(false); } private void ComputeTodoCommentsInCurrentProcess(CancellationToken cancellationToken) { var registrationService = _workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); var analyzerProvider = new InProcTodoCommentsIncrementalAnalyzerProvider(this); registrationService.AddAnalyzerProvider( analyzerProvider, new IncrementalAnalyzerProviderMetadata( nameof(InProcTodoCommentsIncrementalAnalyzerProvider), highPriorityForActiveFile: false, workspaceKinds: WorkspaceKind.Host)); } private ValueTask ProcessTodoCommentInfosAsync( ImmutableArray<DocumentAndComments> docAndCommentsArray, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var _1 = ArrayBuilder<DocumentAndComments>.GetInstance(out var filteredArray); AddFilteredInfos(docAndCommentsArray, filteredArray); foreach (var docAndComments in filteredArray) { var documentId = docAndComments.DocumentId; var newComments = docAndComments.Comments; var oldComments = _documentToInfos.TryGetValue(documentId, out var oldBoxedInfos) ? oldBoxedInfos : ImmutableArray<TodoCommentData>.Empty; // only one thread can be executing ProcessTodoCommentInfosAsync at a time, // so it's safe to remove/add here. if (newComments.IsEmpty) { _documentToInfos.TryRemove(documentId, out _); } else { _documentToInfos[documentId] = newComments; } // If we have someone listening for updates, and our new items are different from // our old ones, then notify them of the change. if (this.TodoListUpdated != null && !oldComments.SequenceEqual(newComments)) { this.TodoListUpdated?.Invoke( this, new TodoItemsUpdatedArgs( documentId, _workspace, _workspace.CurrentSolution, documentId.ProjectId, documentId, newComments)); } } return ValueTaskFactory.CompletedTask; } private void AddFilteredInfos( ImmutableArray<DocumentAndComments> array, ArrayBuilder<DocumentAndComments> filteredArray) { using var _ = PooledHashSet<DocumentId>.GetInstance(out var seenDocumentIds); // Walk the list of todo comments in reverse, and skip any items for a document once // we've already seen it once. That way, we're only reporting the most up to date // information for a document, and we're skipping the stale information. for (var i = array.Length - 1; i >= 0; i--) { var info = array[i]; if (seenDocumentIds.Add(info.DocumentId)) filteredArray.Add(info); } } public ImmutableArray<TodoCommentData> GetTodoItems(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { return _documentToInfos.TryGetValue(documentId, out var values) ? values : ImmutableArray<TodoCommentData>.Empty; } /// <summary> /// Callback from the OOP service back into us. /// </summary> public async ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> infos, CancellationToken cancellationToken) { try { var workQueue = await _workQueueSource.Task.ConfigureAwait(false); workQueue.AddWork(new DocumentAndComments(documentId, infos)); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { // report NFW before returning back to the remote process throw ExceptionUtilities.Unreachable; } } /// <inheritdoc cref="IVsTypeScriptTodoCommentService.ReportTodoCommentsAsync(Document, ImmutableArray{TodoComment}, CancellationToken)"/> async Task IVsTypeScriptTodoCommentService.ReportTodoCommentsAsync( Document document, ImmutableArray<TodoComment> todoComments, CancellationToken cancellationToken) { using var _ = ArrayBuilder<TodoCommentData>.GetInstance(out var converted); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); await TodoComment.ConvertAsync(document, todoComments, converted, cancellationToken).ConfigureAwait(false); await ReportTodoCommentDataAsync( document.Id, converted.ToImmutable(), cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Test/Semantic/Semantics/LookupTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class GetSemanticInfoTests : SemanticModelTestBase { #region helpers internal List<string> GetLookupNames(string testSrc) { var parseOptions = TestOptions.Regular; var compilation = CreateCompilationWithMscorlib45(testSrc, parseOptions: parseOptions); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = testSrc.Contains("/*<bind>*/") ? GetPositionForBinding(tree) : GetPositionForBinding(testSrc); return model.LookupNames(position); } internal List<ISymbol> GetLookupSymbols(string testSrc, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, bool isScript = false, IEnumerable<string> globalUsings = null) { var tree = Parse(testSrc, options: isScript ? TestOptions.Script : TestOptions.Regular); var compilation = CreateCompilationWithMscorlib45(new[] { tree }, options: TestOptions.ReleaseDll.WithUsings(globalUsings)); var model = compilation.GetSemanticModel(tree); var position = testSrc.Contains("/*<bind>*/") ? GetPositionForBinding(tree) : GetPositionForBinding(testSrc); return model.LookupSymbols(position, container.GetPublicSymbol(), name).Where(s => !arity.HasValue || arity == s.GetSymbol().GetMemberArity()).ToList(); } #endregion helpers #region tests [Fact] public void LookupExpressionBodyProp01() { var text = @" class C { public int P => /*<bind>*/10/*</bind>*/; }"; var actual = GetLookupNames(text).ListToSortedString(); var expected_lookupNames = new List<string> { "C", "Equals", "Finalize", "GetHashCode", "GetType", "MemberwiseClone", "Microsoft", "P", "ReferenceEquals", "System", "ToString" }; Assert.Equal(expected_lookupNames.ListToSortedString(), actual); } [Fact] public void LookupExpressionBodiedMethod01() { var text = @" class C { public int M() => /*<bind>*/10/*</bind>*/; }"; var actual = GetLookupNames(text).ListToSortedString(); var expected_lookupNames = new List<string> { "C", "Equals", "Finalize", "GetHashCode", "GetType", "MemberwiseClone", "Microsoft", "M", "ReferenceEquals", "System", "ToString" }; Assert.Equal(expected_lookupNames.ListToSortedString(), actual); } [WorkItem(538262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538262")] [Fact] public void LookupCompilationUnitSyntax() { var testSrc = @" /*<bind>*/ class Test { } /*</bind>*/ "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(527476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527476")] [Fact] public void LookupConstrAndDestr() { var testSrc = @" class Test { Test() { } Test(int i) { } ~Test() { } static /*<bind>*/void/*</bind>*/Main() { } } "; List<string> expected_lookupNames = new List<string> { "Equals", "Finalize", "GetHashCode", "GetType", "Main", "MemberwiseClone", "Microsoft", "ReferenceEquals", "System", "Test", "ToString" }; List<string> expected_lookupSymbols = new List<string> { "Microsoft", "System", "System.Boolean System.Object.Equals(System.Object obj)", "System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", "System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)", "System.Int32 System.Object.GetHashCode()", "System.Object System.Object.MemberwiseClone()", "void System.Object.Finalize()", "System.String System.Object.ToString()", "System.Type System.Object.GetType()", "void Test.Finalize()", "void Test.Main()", "Test" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); Assert.Equal(expected_lookupNames.ListToSortedString(), actual_lookupNames.ListToSortedString()); Assert.Equal(expected_lookupSymbols.ListToSortedString(), actual_lookupSymbols.ListToSortedString()); } [WorkItem(527477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527477")] [Fact] public void LookupNotYetDeclLocalVar() { var testSrc = @" class Test { static void Main() { int j = /*<bind>*/9/*</bind>*/ ; int k = 45; } } "; List<string> expected_in_lookupNames = new List<string> { "j", "k" }; List<string> expected_in_lookupSymbols = new List<string> { "j", "k" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538301")] [Fact] public void LookupByNameIncorrectArity() { var testSrc = @" class Test { public static void Main() { int i = /*<bind>*/10/*</bind>*/; } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc, name: "i", arity: 1); var actual_lookupSymbols = GetLookupSymbols(testSrc, name: "i", arity: 1); Assert.Empty(actual_lookupSymbols); } [WorkItem(538310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538310")] [Fact] public void LookupInProtectedNonNestedType() { var testSrc = @" protected class MyClass { /*<bind>*/public static void Main()/*</bind>*/ {} } "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(538311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538311")] [Fact] public void LookupClassContainsVolatileEnumField() { var testSrc = @" enum E{} class Test { static volatile E x; static /*<bind>*/int/*</bind>*/ Main() { return 1; } } "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(538312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538312")] [Fact] public void LookupUsingAlias() { var testSrc = @" using T2 = System.IO; namespace T1 { class Test { static /*<bind>*/void/*</bind>*/ Main() { } } } "; List<string> expected_in_lookupNames = new List<string> { "T1", "T2" }; List<string> expected_in_lookupSymbols = new List<string> { "T1", "T2" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538313")] [Fact] public void LookupUsingNameSpaceContSameTypeNames() { var testSrc = @" namespace T1 { using T2; public class Test { static /*<bind>*/int/*</bind>*/ Main() { return 1; } } } namespace T2 { public class Test { } } "; List<string> expected_in_lookupNames = new List<string> { "T1", "T2", "Test" }; List<string> expected_in_lookupSymbols = new List<string> { "T1", "T2", "T1.Test", //"T2.Test" this is hidden by T1.Test }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(527489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527489")] [Fact] public void LookupMustNotBeNonInvocableMember() { var testSrc = @" class Test { public void TestMeth(int i, int j) { int m = /*<bind>*/10/*</bind>*/; } } "; List<string> expected_in_lookupNames = new List<string> { "TestMeth", "i", "j", "m", "System", "Microsoft", "Test" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.TestMeth(System.Int32 i, System.Int32 j)", "System.Int32 i", "System.Int32 j", "System.Int32 m", "System", "Microsoft", "Test" }; var comp = CreateCompilation(testSrc); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = GetPositionForBinding(tree); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(position); // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var info = LookupSymbolsInfo.GetInstance(); binder.AddLookupSymbolsInfo(info, LookupOptions.MustBeInvocableIfMember); var actual_lookupNames = info.Names; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = actual_lookupNames.SelectMany(name => { var lookupResult = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; binder.LookupSymbolsSimpleName( lookupResult, qualifierOpt: null, plainName: name, arity: 0, basesBeingResolved: null, options: LookupOptions.MustBeInvocableIfMember, diagnose: false, useSiteDiagnostics: ref useSiteDiagnostics); Assert.Null(useSiteDiagnostics); Assert.True(lookupResult.IsMultiViable || lookupResult.Kind == LookupResultKind.NotReferencable); var result = lookupResult.Symbols.ToArray(); lookupResult.Free(); return result; }); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupNames[3], actual_lookupNames); Assert.Contains(expected_in_lookupNames[4], actual_lookupNames); Assert.Contains(expected_in_lookupNames[5], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[3], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[4], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[5], actual_lookupSymbols_as_string); info.Free(); } [WorkItem(538365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538365")] [Fact] public void LookupWithNameZeroArity() { var testSrc = @" class Test { private void F<T>(T i) { } private void F<T, U>(T i, U j) { } private void F(int i) { } private void F(int i, int j) { } public static /*<bind>*/void/*</bind>*/ Main() { } } "; List<string> expected_in_lookupNames = new List<string> { "F" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.F(System.Int32 i)", "void Test.F(System.Int32 i, System.Int32 j)" }; List<string> not_expected_in_lookupSymbols = new List<string> { "void Test.F<T>(T i)", "void Test.F<T, U>(T i, U j)" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc, name: "F", arity: 0); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Equal(2, actual_lookupSymbols.Count); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538365")] [Fact] public void LookupWithNameZeroArityAndLookupOptionsAllMethods() { var testSrc = @" class Test { public void F<T>(T i) { } public void F<T, U>(T i, U j) { } public void F(int i) { } public void F(int i, int j) { } public void Main() { return; } } "; List<string> expected_in_lookupNames = new List<string> { "F" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.F(System.Int32 i)", "void Test.F(System.Int32 i, System.Int32 j)", "void Test.F<T>(T i)", "void Test.F<T, U>(T i, U j)" }; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var comp = CreateCompilation(testSrc); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = testSrc.IndexOf("return", StringComparison.Ordinal); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(position); var lookupResult = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; binder.LookupSymbolsSimpleName(lookupResult, qualifierOpt: null, plainName: "F", arity: 0, basesBeingResolved: null, options: LookupOptions.AllMethodsOnArityZero, diagnose: false, useSiteDiagnostics: ref useSiteDiagnostics); Assert.Null(useSiteDiagnostics); Assert.True(lookupResult.IsMultiViable); var actual_lookupSymbols_as_string = lookupResult.Symbols.Select(e => e.ToTestDisplayString()).ToArray(); lookupResult.Free(); // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = model.LookupNames(position); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Equal(4, actual_lookupSymbols_as_string.Length); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[3], actual_lookupSymbols_as_string); } [WorkItem(539160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539160")] [Fact] public void LookupExcludeInAppropriateNS() { var testSrc = @" class Test { public static /*<bind>*/void/*</bind>*/ Main() { } } "; var srcTrees = new SyntaxTree[] { Parse(testSrc) }; var refs = new MetadataReference[] { SystemDataRef }; CSharpCompilation compilation = CSharpCompilation.Create("Test.dll", srcTrees, refs); var tree = srcTrees[0]; var model = compilation.GetSemanticModel(tree); List<string> not_expected_in_lookup = new List<string> { "<CrtImplementationDetails>", "<CppImplementationDetails>" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = model.LookupNames(GetPositionForBinding(tree), null).ToList(); var actual_lookupNames_ignoreAcc = model.LookupNames(GetPositionForBinding(tree), null).ToList(); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = model.LookupSymbols(GetPositionForBinding(tree)); var actual_lookupSymbols_ignoreAcc = model.LookupSymbols(GetPositionForBinding(tree)); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); var actual_lookupSymbols_ignoreAcc_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupNames_ignoreAcc); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupNames_ignoreAcc); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupSymbols_ignoreAcc_as_string); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupSymbols_ignoreAcc_as_string); } /// <summary> /// Verify that there's a way to look up only the members of the base type that are visible /// from the current type. /// </summary> [Fact] [WorkItem(539814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539814")] public void LookupProtectedInBase() { var testSrc = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { /*<bind>*/base/*</bind>*/.Goo(); } } "; var srcTrees = new SyntaxTree[] { Parse(testSrc) }; var refs = new MetadataReference[] { SystemDataRef }; CSharpCompilation compilation = CSharpCompilation.Create("Test.dll", srcTrees, refs); var tree = srcTrees[0]; var model = compilation.GetSemanticModel(tree); var baseExprNode = GetSyntaxNodeForBinding(GetSyntaxNodeList(tree)); Assert.Equal("base", baseExprNode.ToString()); var baseExprLocation = baseExprNode.SpanStart; Assert.NotEqual(0, baseExprLocation); var baseExprInfo = model.GetTypeInfo((ExpressionSyntax)baseExprNode); Assert.NotEqual(default, baseExprInfo); var baseExprType = (INamedTypeSymbol)baseExprInfo.Type; Assert.NotNull(baseExprType); Assert.Equal("A", baseExprType.Name); var symbols = model.LookupBaseMembers(baseExprLocation); Assert.Equal("void A.Goo()", symbols.Single().ToTestDisplayString()); var names = model.LookupNames(baseExprLocation, useBaseReferenceAccessibility: true); Assert.Equal("Goo", names.Single()); } [WorkItem(528263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528263")] [Fact] public void LookupStartOfScopeMethodBody() { var testSrc = @"public class start { static public void Main() /*pos*/{ int num=10; } "; List<string> expected_in_lookupNames = new List<string> { "Main", "start", "num" }; List<string> expected_in_lookupSymbols = new List<string> { "void start.Main()", "start", "System.Int32 num" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Equal('{', testSrc[GetPositionForBinding(testSrc)]); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(528263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528263")] [Fact] public void LookupEndOfScopeMethodBody() { var testSrc = @"public class start { static public void Main() { int num=10; /*pos*/} "; List<string> expected_in_lookupNames = new List<string> { "Main", "start" }; List<string> expected_in_lookupSymbols = new List<string> { "void start.Main()", "start" }; List<string> not_expected_in_lookupNames = new List<string> { "num" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 num" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Equal('}', testSrc[GetPositionForBinding(testSrc)]); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540888")] [Fact] public void LookupLambdaParamInConstructorInitializer() { var testSrc = @" using System; class MyClass { public MyClass(Func<int, int> x) { } public MyClass(int j, int k) : this(lambdaParam => /*pos*/lambdaParam) { } } "; List<string> expected_in_lookupNames = new List<string> { "j", "k", "lambdaParam" }; List<string> expected_in_lookupSymbols = new List<string> { "System.Int32 j", "System.Int32 k", "System.Int32 lambdaParam" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(540893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540893")] [Fact] public void TestForLocalVarDeclLookupAtForKeywordInForStmt() { var testSrc = @" class MyClass { static void Main() { /*pos*/for (int forVar = 10; forVar < 10; forVar++) { } } } "; List<string> not_expected_in_lookupNames = new List<string> { "forVar" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 forVar", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540894")] [Fact] public void TestForeachIterVarLookupAtForeachKeyword() { var testSrc = @" class MyClass { static void Main() { System.Collections.Generic.List<int> listOfNumbers = new System.Collections.Generic.List<int>(); /*pos*/foreach (int number in listOfNumbers) { } } } "; List<string> not_expected_in_lookupNames = new List<string> { "number" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 number", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540912")] [Fact] public void TestLookupInConstrInitIncompleteConstrDecl() { var testSrc = @" class MyClass { public MyClass(int x) { } public MyClass(int j, int k) :this(/*pos*/k) "; List<string> expected_in_lookupNames = new List<string> { "j", "k" }; List<string> expected_in_lookupSymbols = new List<string> { "System.Int32 j", "System.Int32 k", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(541060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541060")] [Fact] public void TestLookupInsideIncompleteNestedLambdaBody() { var testSrc = @" class C { C() { D(() => { D(() => { }/*pos*/ "; List<string> expected_in_lookupNames = new List<string> { "C" }; List<string> expected_in_lookupSymbols = new List<string> { "C" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541611")] [Fact] public void LookupLambdaInsideAttributeUsage() { var testSrc = @" using System; class Program { [ObsoleteAttribute(x=>x/*pos*/ static void Main(string[] args) { } } "; List<string> expected_in_lookupNames = new List<string> { "x" }; List<string> expected_in_lookupSymbols = new List<string> { "? x" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [Fact] public void LookupInsideLocalFunctionAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; [ObsoleteAttribute(/*pos*/ static void local1(int z) { } } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [Fact] public void LookupInsideLambdaAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; Action<int> a = [ObsoleteAttribute(/*pos*/ (int z) => { }; } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [Fact] public void LookupInsideIncompleteStatementAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; [ObsoleteAttribute(/*pos*/ int } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [WorkItem(541909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541909")] [Fact] public void LookupFromRangeVariableAfterFromClause() { var testSrc = @" class Program { static void Main(string[] args) { var q = from i in new int[] { 4, 5 } where /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "i" }; List<string> expected_in_lookupSymbols = new List<string> { "? i" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541921")] [Fact] public void LookupFromRangeVariableInsideNestedFromClause() { var testSrc = @" class Program { static void Main(string[] args) { string[] strings = { }; var query = from s in strings from s1 in /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "s" }; List<string> expected_in_lookupSymbols = new List<string> { "? s" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541919")] [Fact] public void LookupLambdaVariableInQueryExpr() { var testSrc = @" class Program { static void Main(string[] args) { Func<int, IEnumerable<int>> f1 = (x) => from n in /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "x" }; List<string> expected_in_lookupSymbols = new List<string> { "x" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.Name); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541910")] [Fact] public void LookupInsideQueryExprOutsideTypeDecl() { var testSrc = @"var q = from i in/*pos*/ f"; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols_as_string); } [WorkItem(542203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542203")] [Fact] public void LookupInsideQueryExprInMalformedFromClause() { var testSrc = @" using System; using System.Linq; class Program { static void Main(string[] args) { int[] numbers = new int[] { 4, 5 }; var q1 = from I<x/*pos*/ in numbers.Where(x1 => x1 > 2) select x; } } "; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols_as_string); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void MultipleOverlappingInterfaceConstraints() { var testSrc = @"public interface IEntity { object Key { get; } } public interface INumberedProjectChild : IEntity { } public interface IAggregateRoot : IEntity { } public interface ISpecification<TCandidate> { void IsSatisfiedBy(TCandidate candidate); } public abstract class Specification<TCandidate> : ISpecification<TCandidate> { public abstract void IsSatisfiedBy(TCandidate candidate); } public class NumberSpecification<TCandidate> : Specification<TCandidate> where TCandidate : IAggregateRoot, INumberedProjectChild { public override void IsSatisfiedBy(TCandidate candidate) { var key = candidate.Key; } }"; CreateCompilation(testSrc).VerifyDiagnostics(); } [WorkItem(529406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529406")] [Fact] public void FixedPointerInitializer() { var testSrc = @" class Program { static int num = 0; unsafe static void Main(string[] args) { fixed(int* p1 = /*pos*/&num, p2 = &num) { } } } "; List<string> expected_in_lookupNames = new List<string> { "p2" }; List<string> expected_in_lookupSymbols = new List<string> { "p2" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()).ToList(); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [Fact] public void LookupSymbolsAtEOF() { var source = @"class { }"; var tree = Parse(source); var comp = CreateCompilationWithMscorlib40(new[] { tree }); var model = comp.GetSemanticModel(tree); var eof = tree.GetCompilationUnitRoot().FullSpan.End; Assert.NotEqual(0, eof); var symbols = model.LookupSymbols(eof); CompilationUtils.CheckISymbols(symbols, "System", "Microsoft"); } [Fact, WorkItem(546523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546523")] public void TestLookupSymbolsNestedNamespacesNotImportedByUsings_01() { var source = @" using System; class Program { static void Main(string[] args) { /*pos*/ } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode var actual_lookupSymbols = GetLookupSymbols(source); // Verify nested namespaces *are not* imported. var systemNS = (INamespaceSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("System") && sym.Kind == SymbolKind.Namespace).Single(); INamespaceSymbol systemXmlNS = systemNS.GetNestedNamespace("Xml"); Assert.DoesNotContain(systemXmlNS, actual_lookupSymbols); } [Fact, WorkItem(546523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546523")] public void TestLookupSymbolsNestedNamespacesNotImportedByUsings_02() { var usings = new[] { "using X;" }; var source = @" using aliasY = X.Y; namespace X { namespace Y { public class InnerZ { } } public class Z { } public static class StaticZ { } } public class A { public class B { } } class Program { public static void Main() { /*pos*/ } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode var actual_lookupSymbols = GetLookupSymbols(usings.ToString() + source, isScript: false); TestLookupSymbolsNestedNamespaces(actual_lookupSymbols); actual_lookupSymbols = GetLookupSymbols(source, isScript: true, globalUsings: usings); TestLookupSymbolsNestedNamespaces(actual_lookupSymbols); Action<ModuleSymbol> validator = (module) => { NamespaceSymbol globalNS = module.GlobalNamespace; Assert.Equal(1, globalNS.GetMembers("X").Length); Assert.Equal(1, globalNS.GetMembers("A").Length); Assert.Equal(1, globalNS.GetMembers("Program").Length); Assert.Empty(globalNS.GetMembers("Y")); Assert.Empty(globalNS.GetMembers("Z")); Assert.Empty(globalNS.GetMembers("StaticZ")); Assert.Empty(globalNS.GetMembers("B")); }; CompileAndVerify(source, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] [WorkItem(530826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530826")] public void TestAmbiguousInterfaceLookup() { var source = @"delegate void D(); interface I1 { void M(); } interface I2 { event D M; } interface I3 : I1, I2 { } public class P : I3 { event D I2.M { add { } remove { } } void I1.M() { } } class Q : P { static int Main(string[] args) { Q p = new Q(); I3 m = p; if (m.M is object) {} return 0; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "m.M").Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.Equal("void I1.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var node2 = (ExpressionSyntax)SyntaxFactory.SyntaxTree(node).GetRoot(); symbolInfo = model.GetSpeculativeSymbolInfo(node.Position, node2, SpeculativeBindingOption.BindAsExpression); Assert.Equal("void I1.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact] public void TestLookupVerbatimVar() { var source = "class C { public static void Main() { @var v = 1; } }"; CreateCompilation(source).VerifyDiagnostics( // (1,39): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) // class C { public static void Main() { @var v = 1; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@var").WithArguments("var").WithLocation(1, 39) ); } private void TestLookupSymbolsNestedNamespaces(List<ISymbol> actual_lookupSymbols) { var namespaceX = (INamespaceSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("X") && sym.Kind == SymbolKind.Namespace).Single(); // Verify nested namespaces within namespace X *are not* present in lookup symbols. INamespaceSymbol namespaceY = namespaceX.GetNestedNamespace("Y"); Assert.DoesNotContain(namespaceY, actual_lookupSymbols); INamedTypeSymbol typeInnerZ = namespaceY.GetTypeMembers("InnerZ").Single(); Assert.DoesNotContain(typeInnerZ, actual_lookupSymbols); // Verify nested types *are not* present in lookup symbols. var typeA = (INamedTypeSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("A") && sym.Kind == SymbolKind.NamedType).Single(); INamedTypeSymbol typeB = typeA.GetTypeMembers("B").Single(); Assert.DoesNotContain(typeB, actual_lookupSymbols); // Verify aliases to nested namespaces within namespace X *are* present in lookup symbols. var aliasY = (IAliasSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("aliasY") && sym.Kind == SymbolKind.Alias).Single(); Assert.Contains(aliasY, actual_lookupSymbols); } [Fact] public void ExtensionMethodCall() { var source = @"static class E { internal static void F(this object o) { } } class C { void M() { /*<bind>*/this.F/*</bind>*/(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var exprs = GetExprSyntaxList(tree); var expr = GetExprSyntaxForBinding(exprs); var method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Equal("object.F()", method.ToDisplayString()); var reducedFrom = method.ReducedFrom; Assert.NotNull(reducedFrom); Assert.Equal("E.F(object)", reducedFrom.ToDisplayString()); } [WorkItem(3651, "https://github.com/dotnet/roslyn/issues/3651")] [Fact] public void ExtensionMethodDelegateCreation() { var source = @"static class E { internal static void F(this object o) { } } class C { void M() { (new System.Action<object>(/*<bind>*/E.F/*</bind>*/))(this); (new System.Action(/*<bind1>*/this.F/*</bind1>*/))(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var exprs = GetExprSyntaxList(tree); var expr = GetExprSyntaxForBinding(exprs, index: 0); var method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Null(method.ReducedFrom); Assert.Equal("E.F(object)", method.ToDisplayString()); expr = GetExprSyntaxForBinding(exprs, index: 1); method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Equal("object.F()", method.ToDisplayString()); var reducedFrom = method.ReducedFrom; Assert.NotNull(reducedFrom); Assert.Equal("E.F(object)", reducedFrom.ToDisplayString()); } [WorkItem(7493, "https://github.com/dotnet/roslyn/issues/7493")] [Fact] public void GenericNameLookup() { var source = @"using A = List<int>;"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (1,11): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // using A = List<int>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(1, 11), // (1,1): hidden CS8019: Unnecessary using directive. // using A = List<int>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = List<int>;").WithLocation(1, 1)); } #endregion tests #region regressions [Fact] [WorkItem(552472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552472")] public void BrokenCode01() { var source = @"Dele<Str> d3 = delegate (Dele<Str> d2 = delegate () { returne<double> d1 = delegate () { return 1; }; { int result = 0; Dels Test : Base"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); SemanticModel imodel = model; var node = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "returne<double>").First(); imodel.GetSymbolInfo(node, default(CancellationToken)); } [Fact] [WorkItem(552472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552472")] public void BrokenCode02() { var source = @"public delegate D D(D d); class Program { public D d3 = delegate(D d2 = delegate { System.Object x = 3; return null; }) {}; public static void Main(string[] args) { } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); SemanticModel imodel = model; var node = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "System.Object").First(); imodel.GetSymbolInfo(node, default(CancellationToken)); } [Fact] public void InterfaceDiamondHiding() { var source = @" interface T { int P { get; set; } int Q { get; set; } } interface L : T { new int P { get; set; } } interface R : T { new int Q { get; set; } } interface B : L, R { } class Test { int M(B b) { return b.P + b.Q; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var interfaceT = global.GetMember<NamedTypeSymbol>("T"); var interfaceL = global.GetMember<NamedTypeSymbol>("L"); var interfaceR = global.GetMember<NamedTypeSymbol>("R"); var interfaceB = global.GetMember<NamedTypeSymbol>("B"); var propertyTP = interfaceT.GetMember<PropertySymbol>("P"); var propertyTQ = interfaceT.GetMember<PropertySymbol>("Q"); var propertyLP = interfaceL.GetMember<PropertySymbol>("P"); var propertyRQ = interfaceR.GetMember<PropertySymbol>("Q"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntaxes = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray(); Assert.Equal(2, syntaxes.Length); // The properties in T are hidden - we bind to the properties on more-derived interfaces Assert.Equal(propertyLP.GetPublicSymbol(), model.GetSymbolInfo(syntaxes[0]).Symbol); Assert.Equal(propertyRQ.GetPublicSymbol(), model.GetSymbolInfo(syntaxes[1]).Symbol); int position = source.IndexOf("return", StringComparison.Ordinal); // We do the right thing with diamond inheritance (i.e. member is hidden along all paths // if it is hidden along any path) because we visit base interfaces in topological order. Assert.Equal(propertyLP.GetPublicSymbol(), model.LookupSymbols(position, interfaceB.GetPublicSymbol(), "P").Single()); Assert.Equal(propertyRQ.GetPublicSymbol(), model.LookupSymbols(position, interfaceB.GetPublicSymbol(), "Q").Single()); } [Fact] public void SemanticModel_OnlyInvalid() { var source = @" public class C { void M() { return; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupNamespacesAndTypes(position, name: "M"); Assert.Equal(0, symbols.Length); } [Fact] public void SemanticModel_InvalidHidingValid() { var source = @" public class C<T> { public class Inner { void T() { return; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var classC = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var methodT = classC.GetMember<NamedTypeSymbol>("Inner").GetMember<MethodSymbol>("T"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupSymbols(position, name: "T"); Assert.Equal(methodT.GetPublicSymbol(), symbols.Single()); // Hides type parameter. symbols = model.LookupNamespacesAndTypes(position, name: "T"); Assert.Equal(classC.TypeParameters.Single().GetPublicSymbol(), symbols.Single()); // Ignore intervening method. } [Fact] public void SemanticModel_MultipleValid() { var source = @" public class Outer { void M(int x) { } void M() { return; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupSymbols(position, name: "M"); Assert.Equal(2, symbols.Length); } [Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")] public void Bug1078958() { const string source = @" class C { static void Goo<T>() { /*<bind>*/T/*</bind>*/(); } static void T() { } }"; var symbols = GetLookupSymbols(source); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961() { const string source = @" class C { const int T = 42; static void Goo<T>(int x = /*<bind>*/T/*</bind>*/) { System.Console.Write(x); } static void Main() { Goo<object>(); } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_2() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Goo<T>([A(/*<bind>*/T/*</bind>*/)] int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_3() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; [A(/*<bind>*/T/*</bind>*/)] static void Goo<T>(int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_4() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Goo<[A(/*<bind>*/T/*</bind>*/)] T>(int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_5() { const string source = @" class C { class T { } static void Goo<T>(T x = default(/*<bind>*/T/*</bind>*/)) { System.Console.Write((object)x == null); } static void Main() { Goo<object>(); } }"; var symbols = GetLookupSymbols(source); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_6() { const string source = @" class C { class T { } static void Goo<T>(T x = default(/*<bind>*/T/*</bind>*/)) { System.Console.Write((object)x == null); } static void Main() { Goo<object>(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = GetPositionForBinding(tree); var symbols = model.LookupNamespacesAndTypes(position); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_1() { const string source = @" class Program { static object M(long l) { return null; } static object M(int i) { return null; } static void Main(string[] args) { (M(0))?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var ms = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").OfType<MethodSymbol>(); var m = ms.Where(mm => mm.Parameters[0].Type.SpecialType == SpecialType.System_Int32).Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var symbolInfo = model.GetSymbolInfo(call.Expression); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_2() { const string source = @" class Program { static object M = null; static void Main(string[] args) { M?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var m = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single().Expression; var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_3() { const string source = @" class Program { object M = null; static void Main(string[] args) { (new Program()).M?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var m = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single().Expression; var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_4() { const string source = @" class Program { static void Main(string[] args) { var y = (System.Linq.Enumerable.Select<string, int>(args, s => int.Parse(s)))?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<GenericNameSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.NotNull(symbolInfo.Symbol); } [Fact] public void GenericAttribute_LookupSymbols_01() { var source = @" using System; class Attr1<T> : Attribute { public Attr1(T t) { } } [Attr1<string>(""a"")] class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single(); var symbol = model.GetSymbolInfo(node); Assert.Equal("Attr1<System.String>..ctor(System.String t)", symbol.Symbol.ToTestDisplayString()); } [Fact] public void GenericAttribute_LookupSymbols_02() { var source = @" using System; class Attr1<T> : Attribute { public Attr1(T t) { } } [Attr1</*<bind>*/string/*</bind>*/>] class C { }"; var names = GetLookupNames(source); Assert.Contains("C", names); Assert.Contains("Attr1", names); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class GetSemanticInfoTests : SemanticModelTestBase { #region helpers internal List<string> GetLookupNames(string testSrc) { var parseOptions = TestOptions.Regular; var compilation = CreateCompilationWithMscorlib45(testSrc, parseOptions: parseOptions); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = testSrc.Contains("/*<bind>*/") ? GetPositionForBinding(tree) : GetPositionForBinding(testSrc); return model.LookupNames(position); } internal List<ISymbol> GetLookupSymbols(string testSrc, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, bool isScript = false, IEnumerable<string> globalUsings = null) { var tree = Parse(testSrc, options: isScript ? TestOptions.Script : TestOptions.Regular); var compilation = CreateCompilationWithMscorlib45(new[] { tree }, options: TestOptions.ReleaseDll.WithUsings(globalUsings)); var model = compilation.GetSemanticModel(tree); var position = testSrc.Contains("/*<bind>*/") ? GetPositionForBinding(tree) : GetPositionForBinding(testSrc); return model.LookupSymbols(position, container.GetPublicSymbol(), name).Where(s => !arity.HasValue || arity == s.GetSymbol().GetMemberArity()).ToList(); } #endregion helpers #region tests [Fact] public void LookupExpressionBodyProp01() { var text = @" class C { public int P => /*<bind>*/10/*</bind>*/; }"; var actual = GetLookupNames(text).ListToSortedString(); var expected_lookupNames = new List<string> { "C", "Equals", "Finalize", "GetHashCode", "GetType", "MemberwiseClone", "Microsoft", "P", "ReferenceEquals", "System", "ToString" }; Assert.Equal(expected_lookupNames.ListToSortedString(), actual); } [Fact] public void LookupExpressionBodiedMethod01() { var text = @" class C { public int M() => /*<bind>*/10/*</bind>*/; }"; var actual = GetLookupNames(text).ListToSortedString(); var expected_lookupNames = new List<string> { "C", "Equals", "Finalize", "GetHashCode", "GetType", "MemberwiseClone", "Microsoft", "M", "ReferenceEquals", "System", "ToString" }; Assert.Equal(expected_lookupNames.ListToSortedString(), actual); } [WorkItem(538262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538262")] [Fact] public void LookupCompilationUnitSyntax() { var testSrc = @" /*<bind>*/ class Test { } /*</bind>*/ "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(527476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527476")] [Fact] public void LookupConstrAndDestr() { var testSrc = @" class Test { Test() { } Test(int i) { } ~Test() { } static /*<bind>*/void/*</bind>*/Main() { } } "; List<string> expected_lookupNames = new List<string> { "Equals", "Finalize", "GetHashCode", "GetType", "Main", "MemberwiseClone", "Microsoft", "ReferenceEquals", "System", "Test", "ToString" }; List<string> expected_lookupSymbols = new List<string> { "Microsoft", "System", "System.Boolean System.Object.Equals(System.Object obj)", "System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", "System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)", "System.Int32 System.Object.GetHashCode()", "System.Object System.Object.MemberwiseClone()", "void System.Object.Finalize()", "System.String System.Object.ToString()", "System.Type System.Object.GetType()", "void Test.Finalize()", "void Test.Main()", "Test" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); Assert.Equal(expected_lookupNames.ListToSortedString(), actual_lookupNames.ListToSortedString()); Assert.Equal(expected_lookupSymbols.ListToSortedString(), actual_lookupSymbols.ListToSortedString()); } [WorkItem(527477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527477")] [Fact] public void LookupNotYetDeclLocalVar() { var testSrc = @" class Test { static void Main() { int j = /*<bind>*/9/*</bind>*/ ; int k = 45; } } "; List<string> expected_in_lookupNames = new List<string> { "j", "k" }; List<string> expected_in_lookupSymbols = new List<string> { "j", "k" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538301")] [Fact] public void LookupByNameIncorrectArity() { var testSrc = @" class Test { public static void Main() { int i = /*<bind>*/10/*</bind>*/; } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc, name: "i", arity: 1); var actual_lookupSymbols = GetLookupSymbols(testSrc, name: "i", arity: 1); Assert.Empty(actual_lookupSymbols); } [WorkItem(538310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538310")] [Fact] public void LookupInProtectedNonNestedType() { var testSrc = @" protected class MyClass { /*<bind>*/public static void Main()/*</bind>*/ {} } "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(538311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538311")] [Fact] public void LookupClassContainsVolatileEnumField() { var testSrc = @" enum E{} class Test { static volatile E x; static /*<bind>*/int/*</bind>*/ Main() { return 1; } } "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(538312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538312")] [Fact] public void LookupUsingAlias() { var testSrc = @" using T2 = System.IO; namespace T1 { class Test { static /*<bind>*/void/*</bind>*/ Main() { } } } "; List<string> expected_in_lookupNames = new List<string> { "T1", "T2" }; List<string> expected_in_lookupSymbols = new List<string> { "T1", "T2" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538313")] [Fact] public void LookupUsingNameSpaceContSameTypeNames() { var testSrc = @" namespace T1 { using T2; public class Test { static /*<bind>*/int/*</bind>*/ Main() { return 1; } } } namespace T2 { public class Test { } } "; List<string> expected_in_lookupNames = new List<string> { "T1", "T2", "Test" }; List<string> expected_in_lookupSymbols = new List<string> { "T1", "T2", "T1.Test", //"T2.Test" this is hidden by T1.Test }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(527489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527489")] [Fact] public void LookupMustNotBeNonInvocableMember() { var testSrc = @" class Test { public void TestMeth(int i, int j) { int m = /*<bind>*/10/*</bind>*/; } } "; List<string> expected_in_lookupNames = new List<string> { "TestMeth", "i", "j", "m", "System", "Microsoft", "Test" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.TestMeth(System.Int32 i, System.Int32 j)", "System.Int32 i", "System.Int32 j", "System.Int32 m", "System", "Microsoft", "Test" }; var comp = CreateCompilation(testSrc); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = GetPositionForBinding(tree); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(position); // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var info = LookupSymbolsInfo.GetInstance(); binder.AddLookupSymbolsInfo(info, LookupOptions.MustBeInvocableIfMember); var actual_lookupNames = info.Names; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = actual_lookupNames.SelectMany(name => { var lookupResult = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; binder.LookupSymbolsSimpleName( lookupResult, qualifierOpt: null, plainName: name, arity: 0, basesBeingResolved: null, options: LookupOptions.MustBeInvocableIfMember, diagnose: false, useSiteDiagnostics: ref useSiteDiagnostics); Assert.Null(useSiteDiagnostics); Assert.True(lookupResult.IsMultiViable || lookupResult.Kind == LookupResultKind.NotReferencable); var result = lookupResult.Symbols.ToArray(); lookupResult.Free(); return result; }); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupNames[3], actual_lookupNames); Assert.Contains(expected_in_lookupNames[4], actual_lookupNames); Assert.Contains(expected_in_lookupNames[5], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[3], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[4], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[5], actual_lookupSymbols_as_string); info.Free(); } [WorkItem(538365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538365")] [Fact] public void LookupWithNameZeroArity() { var testSrc = @" class Test { private void F<T>(T i) { } private void F<T, U>(T i, U j) { } private void F(int i) { } private void F(int i, int j) { } public static /*<bind>*/void/*</bind>*/ Main() { } } "; List<string> expected_in_lookupNames = new List<string> { "F" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.F(System.Int32 i)", "void Test.F(System.Int32 i, System.Int32 j)" }; List<string> not_expected_in_lookupSymbols = new List<string> { "void Test.F<T>(T i)", "void Test.F<T, U>(T i, U j)" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc, name: "F", arity: 0); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Equal(2, actual_lookupSymbols.Count); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538365")] [Fact] public void LookupWithNameZeroArityAndLookupOptionsAllMethods() { var testSrc = @" class Test { public void F<T>(T i) { } public void F<T, U>(T i, U j) { } public void F(int i) { } public void F(int i, int j) { } public void Main() { return; } } "; List<string> expected_in_lookupNames = new List<string> { "F" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.F(System.Int32 i)", "void Test.F(System.Int32 i, System.Int32 j)", "void Test.F<T>(T i)", "void Test.F<T, U>(T i, U j)" }; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var comp = CreateCompilation(testSrc); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = testSrc.IndexOf("return", StringComparison.Ordinal); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(position); var lookupResult = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; binder.LookupSymbolsSimpleName(lookupResult, qualifierOpt: null, plainName: "F", arity: 0, basesBeingResolved: null, options: LookupOptions.AllMethodsOnArityZero, diagnose: false, useSiteDiagnostics: ref useSiteDiagnostics); Assert.Null(useSiteDiagnostics); Assert.True(lookupResult.IsMultiViable); var actual_lookupSymbols_as_string = lookupResult.Symbols.Select(e => e.ToTestDisplayString()).ToArray(); lookupResult.Free(); // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = model.LookupNames(position); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Equal(4, actual_lookupSymbols_as_string.Length); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[3], actual_lookupSymbols_as_string); } [WorkItem(539160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539160")] [Fact] public void LookupExcludeInAppropriateNS() { var testSrc = @" class Test { public static /*<bind>*/void/*</bind>*/ Main() { } } "; var srcTrees = new SyntaxTree[] { Parse(testSrc) }; var refs = new MetadataReference[] { SystemDataRef }; CSharpCompilation compilation = CSharpCompilation.Create("Test.dll", srcTrees, refs); var tree = srcTrees[0]; var model = compilation.GetSemanticModel(tree); List<string> not_expected_in_lookup = new List<string> { "<CrtImplementationDetails>", "<CppImplementationDetails>" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = model.LookupNames(GetPositionForBinding(tree), null).ToList(); var actual_lookupNames_ignoreAcc = model.LookupNames(GetPositionForBinding(tree), null).ToList(); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = model.LookupSymbols(GetPositionForBinding(tree)); var actual_lookupSymbols_ignoreAcc = model.LookupSymbols(GetPositionForBinding(tree)); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); var actual_lookupSymbols_ignoreAcc_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupNames_ignoreAcc); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupNames_ignoreAcc); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupSymbols_ignoreAcc_as_string); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupSymbols_ignoreAcc_as_string); } /// <summary> /// Verify that there's a way to look up only the members of the base type that are visible /// from the current type. /// </summary> [Fact] [WorkItem(539814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539814")] public void LookupProtectedInBase() { var testSrc = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { /*<bind>*/base/*</bind>*/.Goo(); } } "; var srcTrees = new SyntaxTree[] { Parse(testSrc) }; var refs = new MetadataReference[] { SystemDataRef }; CSharpCompilation compilation = CSharpCompilation.Create("Test.dll", srcTrees, refs); var tree = srcTrees[0]; var model = compilation.GetSemanticModel(tree); var baseExprNode = GetSyntaxNodeForBinding(GetSyntaxNodeList(tree)); Assert.Equal("base", baseExprNode.ToString()); var baseExprLocation = baseExprNode.SpanStart; Assert.NotEqual(0, baseExprLocation); var baseExprInfo = model.GetTypeInfo((ExpressionSyntax)baseExprNode); Assert.NotEqual(default, baseExprInfo); var baseExprType = (INamedTypeSymbol)baseExprInfo.Type; Assert.NotNull(baseExprType); Assert.Equal("A", baseExprType.Name); var symbols = model.LookupBaseMembers(baseExprLocation); Assert.Equal("void A.Goo()", symbols.Single().ToTestDisplayString()); var names = model.LookupNames(baseExprLocation, useBaseReferenceAccessibility: true); Assert.Equal("Goo", names.Single()); } [WorkItem(528263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528263")] [Fact] public void LookupStartOfScopeMethodBody() { var testSrc = @"public class start { static public void Main() /*pos*/{ int num=10; } "; List<string> expected_in_lookupNames = new List<string> { "Main", "start", "num" }; List<string> expected_in_lookupSymbols = new List<string> { "void start.Main()", "start", "System.Int32 num" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Equal('{', testSrc[GetPositionForBinding(testSrc)]); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(528263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528263")] [Fact] public void LookupEndOfScopeMethodBody() { var testSrc = @"public class start { static public void Main() { int num=10; /*pos*/} "; List<string> expected_in_lookupNames = new List<string> { "Main", "start" }; List<string> expected_in_lookupSymbols = new List<string> { "void start.Main()", "start" }; List<string> not_expected_in_lookupNames = new List<string> { "num" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 num" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Equal('}', testSrc[GetPositionForBinding(testSrc)]); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540888")] [Fact] public void LookupLambdaParamInConstructorInitializer() { var testSrc = @" using System; class MyClass { public MyClass(Func<int, int> x) { } public MyClass(int j, int k) : this(lambdaParam => /*pos*/lambdaParam) { } } "; List<string> expected_in_lookupNames = new List<string> { "j", "k", "lambdaParam" }; List<string> expected_in_lookupSymbols = new List<string> { "System.Int32 j", "System.Int32 k", "System.Int32 lambdaParam" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(540893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540893")] [Fact] public void TestForLocalVarDeclLookupAtForKeywordInForStmt() { var testSrc = @" class MyClass { static void Main() { /*pos*/for (int forVar = 10; forVar < 10; forVar++) { } } } "; List<string> not_expected_in_lookupNames = new List<string> { "forVar" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 forVar", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540894")] [Fact] public void TestForeachIterVarLookupAtForeachKeyword() { var testSrc = @" class MyClass { static void Main() { System.Collections.Generic.List<int> listOfNumbers = new System.Collections.Generic.List<int>(); /*pos*/foreach (int number in listOfNumbers) { } } } "; List<string> not_expected_in_lookupNames = new List<string> { "number" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 number", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540912")] [Fact] public void TestLookupInConstrInitIncompleteConstrDecl() { var testSrc = @" class MyClass { public MyClass(int x) { } public MyClass(int j, int k) :this(/*pos*/k) "; List<string> expected_in_lookupNames = new List<string> { "j", "k" }; List<string> expected_in_lookupSymbols = new List<string> { "System.Int32 j", "System.Int32 k", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(541060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541060")] [Fact] public void TestLookupInsideIncompleteNestedLambdaBody() { var testSrc = @" class C { C() { D(() => { D(() => { }/*pos*/ "; List<string> expected_in_lookupNames = new List<string> { "C" }; List<string> expected_in_lookupSymbols = new List<string> { "C" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541611")] [Fact] public void LookupLambdaInsideAttributeUsage() { var testSrc = @" using System; class Program { [ObsoleteAttribute(x=>x/*pos*/ static void Main(string[] args) { } } "; List<string> expected_in_lookupNames = new List<string> { "x" }; List<string> expected_in_lookupSymbols = new List<string> { "? x" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [Fact] public void LookupInsideLocalFunctionAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; [ObsoleteAttribute(/*pos*/ static void local1(int z) { } } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [Fact] public void LookupInsideLambdaAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; Action<int> a = [ObsoleteAttribute(/*pos*/ (int z) => { }; } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [Fact] public void LookupInsideIncompleteStatementAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; [ObsoleteAttribute(/*pos*/ int } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [WorkItem(541909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541909")] [Fact] public void LookupFromRangeVariableAfterFromClause() { var testSrc = @" class Program { static void Main(string[] args) { var q = from i in new int[] { 4, 5 } where /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "i" }; List<string> expected_in_lookupSymbols = new List<string> { "? i" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541921")] [Fact] public void LookupFromRangeVariableInsideNestedFromClause() { var testSrc = @" class Program { static void Main(string[] args) { string[] strings = { }; var query = from s in strings from s1 in /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "s" }; List<string> expected_in_lookupSymbols = new List<string> { "? s" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541919")] [Fact] public void LookupLambdaVariableInQueryExpr() { var testSrc = @" class Program { static void Main(string[] args) { Func<int, IEnumerable<int>> f1 = (x) => from n in /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "x" }; List<string> expected_in_lookupSymbols = new List<string> { "x" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.Name); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541910")] [Fact] public void LookupInsideQueryExprOutsideTypeDecl() { var testSrc = @"var q = from i in/*pos*/ f"; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols_as_string); } [WorkItem(542203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542203")] [Fact] public void LookupInsideQueryExprInMalformedFromClause() { var testSrc = @" using System; using System.Linq; class Program { static void Main(string[] args) { int[] numbers = new int[] { 4, 5 }; var q1 = from I<x/*pos*/ in numbers.Where(x1 => x1 > 2) select x; } } "; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols_as_string); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void MultipleOverlappingInterfaceConstraints() { var testSrc = @"public interface IEntity { object Key { get; } } public interface INumberedProjectChild : IEntity { } public interface IAggregateRoot : IEntity { } public interface ISpecification<TCandidate> { void IsSatisfiedBy(TCandidate candidate); } public abstract class Specification<TCandidate> : ISpecification<TCandidate> { public abstract void IsSatisfiedBy(TCandidate candidate); } public class NumberSpecification<TCandidate> : Specification<TCandidate> where TCandidate : IAggregateRoot, INumberedProjectChild { public override void IsSatisfiedBy(TCandidate candidate) { var key = candidate.Key; } }"; CreateCompilation(testSrc).VerifyDiagnostics(); } [WorkItem(529406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529406")] [Fact] public void FixedPointerInitializer() { var testSrc = @" class Program { static int num = 0; unsafe static void Main(string[] args) { fixed(int* p1 = /*pos*/&num, p2 = &num) { } } } "; List<string> expected_in_lookupNames = new List<string> { "p2" }; List<string> expected_in_lookupSymbols = new List<string> { "p2" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()).ToList(); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [Fact] public void LookupSymbolsAtEOF() { var source = @"class { }"; var tree = Parse(source); var comp = CreateCompilationWithMscorlib40(new[] { tree }); var model = comp.GetSemanticModel(tree); var eof = tree.GetCompilationUnitRoot().FullSpan.End; Assert.NotEqual(0, eof); var symbols = model.LookupSymbols(eof); CompilationUtils.CheckISymbols(symbols, "System", "Microsoft"); } [Fact, WorkItem(546523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546523")] public void TestLookupSymbolsNestedNamespacesNotImportedByUsings_01() { var source = @" using System; class Program { static void Main(string[] args) { /*pos*/ } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode var actual_lookupSymbols = GetLookupSymbols(source); // Verify nested namespaces *are not* imported. var systemNS = (INamespaceSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("System") && sym.Kind == SymbolKind.Namespace).Single(); INamespaceSymbol systemXmlNS = systemNS.GetNestedNamespace("Xml"); Assert.DoesNotContain(systemXmlNS, actual_lookupSymbols); } [Fact, WorkItem(546523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546523")] public void TestLookupSymbolsNestedNamespacesNotImportedByUsings_02() { var usings = new[] { "using X;" }; var source = @" using aliasY = X.Y; namespace X { namespace Y { public class InnerZ { } } public class Z { } public static class StaticZ { } } public class A { public class B { } } class Program { public static void Main() { /*pos*/ } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode var actual_lookupSymbols = GetLookupSymbols(usings.ToString() + source, isScript: false); TestLookupSymbolsNestedNamespaces(actual_lookupSymbols); actual_lookupSymbols = GetLookupSymbols(source, isScript: true, globalUsings: usings); TestLookupSymbolsNestedNamespaces(actual_lookupSymbols); Action<ModuleSymbol> validator = (module) => { NamespaceSymbol globalNS = module.GlobalNamespace; Assert.Equal(1, globalNS.GetMembers("X").Length); Assert.Equal(1, globalNS.GetMembers("A").Length); Assert.Equal(1, globalNS.GetMembers("Program").Length); Assert.Empty(globalNS.GetMembers("Y")); Assert.Empty(globalNS.GetMembers("Z")); Assert.Empty(globalNS.GetMembers("StaticZ")); Assert.Empty(globalNS.GetMembers("B")); }; CompileAndVerify(source, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] [WorkItem(530826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530826")] public void TestAmbiguousInterfaceLookup() { var source = @"delegate void D(); interface I1 { void M(); } interface I2 { event D M; } interface I3 : I1, I2 { } public class P : I3 { event D I2.M { add { } remove { } } void I1.M() { } } class Q : P { static int Main(string[] args) { Q p = new Q(); I3 m = p; if (m.M is object) {} return 0; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "m.M").Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.Equal("void I1.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var node2 = (ExpressionSyntax)SyntaxFactory.SyntaxTree(node).GetRoot(); symbolInfo = model.GetSpeculativeSymbolInfo(node.Position, node2, SpeculativeBindingOption.BindAsExpression); Assert.Equal("void I1.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact] public void TestLookupVerbatimVar() { var source = "class C { public static void Main() { @var v = 1; } }"; CreateCompilation(source).VerifyDiagnostics( // (1,39): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) // class C { public static void Main() { @var v = 1; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@var").WithArguments("var").WithLocation(1, 39) ); } private void TestLookupSymbolsNestedNamespaces(List<ISymbol> actual_lookupSymbols) { var namespaceX = (INamespaceSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("X") && sym.Kind == SymbolKind.Namespace).Single(); // Verify nested namespaces within namespace X *are not* present in lookup symbols. INamespaceSymbol namespaceY = namespaceX.GetNestedNamespace("Y"); Assert.DoesNotContain(namespaceY, actual_lookupSymbols); INamedTypeSymbol typeInnerZ = namespaceY.GetTypeMembers("InnerZ").Single(); Assert.DoesNotContain(typeInnerZ, actual_lookupSymbols); // Verify nested types *are not* present in lookup symbols. var typeA = (INamedTypeSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("A") && sym.Kind == SymbolKind.NamedType).Single(); INamedTypeSymbol typeB = typeA.GetTypeMembers("B").Single(); Assert.DoesNotContain(typeB, actual_lookupSymbols); // Verify aliases to nested namespaces within namespace X *are* present in lookup symbols. var aliasY = (IAliasSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("aliasY") && sym.Kind == SymbolKind.Alias).Single(); Assert.Contains(aliasY, actual_lookupSymbols); } [Fact] public void ExtensionMethodCall() { var source = @"static class E { internal static void F(this object o) { } } class C { void M() { /*<bind>*/this.F/*</bind>*/(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var exprs = GetExprSyntaxList(tree); var expr = GetExprSyntaxForBinding(exprs); var method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Equal("object.F()", method.ToDisplayString()); var reducedFrom = method.ReducedFrom; Assert.NotNull(reducedFrom); Assert.Equal("E.F(object)", reducedFrom.ToDisplayString()); } [WorkItem(3651, "https://github.com/dotnet/roslyn/issues/3651")] [Fact] public void ExtensionMethodDelegateCreation() { var source = @"static class E { internal static void F(this object o) { } } class C { void M() { (new System.Action<object>(/*<bind>*/E.F/*</bind>*/))(this); (new System.Action(/*<bind1>*/this.F/*</bind1>*/))(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var exprs = GetExprSyntaxList(tree); var expr = GetExprSyntaxForBinding(exprs, index: 0); var method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Null(method.ReducedFrom); Assert.Equal("E.F(object)", method.ToDisplayString()); expr = GetExprSyntaxForBinding(exprs, index: 1); method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Equal("object.F()", method.ToDisplayString()); var reducedFrom = method.ReducedFrom; Assert.NotNull(reducedFrom); Assert.Equal("E.F(object)", reducedFrom.ToDisplayString()); } [WorkItem(7493, "https://github.com/dotnet/roslyn/issues/7493")] [Fact] public void GenericNameLookup() { var source = @"using A = List<int>;"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (1,11): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // using A = List<int>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(1, 11), // (1,1): hidden CS8019: Unnecessary using directive. // using A = List<int>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = List<int>;").WithLocation(1, 1)); } #endregion tests #region regressions [Fact] [WorkItem(552472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552472")] public void BrokenCode01() { var source = @"Dele<Str> d3 = delegate (Dele<Str> d2 = delegate () { returne<double> d1 = delegate () { return 1; }; { int result = 0; Dels Test : Base"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); SemanticModel imodel = model; var node = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "returne<double>").First(); imodel.GetSymbolInfo(node, default(CancellationToken)); } [Fact] [WorkItem(552472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552472")] public void BrokenCode02() { var source = @"public delegate D D(D d); class Program { public D d3 = delegate(D d2 = delegate { System.Object x = 3; return null; }) {}; public static void Main(string[] args) { } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); SemanticModel imodel = model; var node = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "System.Object").First(); imodel.GetSymbolInfo(node, default(CancellationToken)); } [Fact] public void InterfaceDiamondHiding() { var source = @" interface T { int P { get; set; } int Q { get; set; } } interface L : T { new int P { get; set; } } interface R : T { new int Q { get; set; } } interface B : L, R { } class Test { int M(B b) { return b.P + b.Q; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var interfaceT = global.GetMember<NamedTypeSymbol>("T"); var interfaceL = global.GetMember<NamedTypeSymbol>("L"); var interfaceR = global.GetMember<NamedTypeSymbol>("R"); var interfaceB = global.GetMember<NamedTypeSymbol>("B"); var propertyTP = interfaceT.GetMember<PropertySymbol>("P"); var propertyTQ = interfaceT.GetMember<PropertySymbol>("Q"); var propertyLP = interfaceL.GetMember<PropertySymbol>("P"); var propertyRQ = interfaceR.GetMember<PropertySymbol>("Q"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntaxes = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray(); Assert.Equal(2, syntaxes.Length); // The properties in T are hidden - we bind to the properties on more-derived interfaces Assert.Equal(propertyLP.GetPublicSymbol(), model.GetSymbolInfo(syntaxes[0]).Symbol); Assert.Equal(propertyRQ.GetPublicSymbol(), model.GetSymbolInfo(syntaxes[1]).Symbol); int position = source.IndexOf("return", StringComparison.Ordinal); // We do the right thing with diamond inheritance (i.e. member is hidden along all paths // if it is hidden along any path) because we visit base interfaces in topological order. Assert.Equal(propertyLP.GetPublicSymbol(), model.LookupSymbols(position, interfaceB.GetPublicSymbol(), "P").Single()); Assert.Equal(propertyRQ.GetPublicSymbol(), model.LookupSymbols(position, interfaceB.GetPublicSymbol(), "Q").Single()); } [Fact] public void SemanticModel_OnlyInvalid() { var source = @" public class C { void M() { return; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupNamespacesAndTypes(position, name: "M"); Assert.Equal(0, symbols.Length); } [Fact] public void SemanticModel_InvalidHidingValid() { var source = @" public class C<T> { public class Inner { void T() { return; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var classC = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var methodT = classC.GetMember<NamedTypeSymbol>("Inner").GetMember<MethodSymbol>("T"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupSymbols(position, name: "T"); Assert.Equal(methodT.GetPublicSymbol(), symbols.Single()); // Hides type parameter. symbols = model.LookupNamespacesAndTypes(position, name: "T"); Assert.Equal(classC.TypeParameters.Single().GetPublicSymbol(), symbols.Single()); // Ignore intervening method. } [Fact] public void SemanticModel_MultipleValid() { var source = @" public class Outer { void M(int x) { } void M() { return; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupSymbols(position, name: "M"); Assert.Equal(2, symbols.Length); } [Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")] public void Bug1078958() { const string source = @" class C { static void Goo<T>() { /*<bind>*/T/*</bind>*/(); } static void T() { } }"; var symbols = GetLookupSymbols(source); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961() { const string source = @" class C { const int T = 42; static void Goo<T>(int x = /*<bind>*/T/*</bind>*/) { System.Console.Write(x); } static void Main() { Goo<object>(); } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_2() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Goo<T>([A(/*<bind>*/T/*</bind>*/)] int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_3() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; [A(/*<bind>*/T/*</bind>*/)] static void Goo<T>(int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_4() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Goo<[A(/*<bind>*/T/*</bind>*/)] T>(int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_5() { const string source = @" class C { class T { } static void Goo<T>(T x = default(/*<bind>*/T/*</bind>*/)) { System.Console.Write((object)x == null); } static void Main() { Goo<object>(); } }"; var symbols = GetLookupSymbols(source); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_6() { const string source = @" class C { class T { } static void Goo<T>(T x = default(/*<bind>*/T/*</bind>*/)) { System.Console.Write((object)x == null); } static void Main() { Goo<object>(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = GetPositionForBinding(tree); var symbols = model.LookupNamespacesAndTypes(position); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_1() { const string source = @" class Program { static object M(long l) { return null; } static object M(int i) { return null; } static void Main(string[] args) { (M(0))?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var ms = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").OfType<MethodSymbol>(); var m = ms.Where(mm => mm.Parameters[0].Type.SpecialType == SpecialType.System_Int32).Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var symbolInfo = model.GetSymbolInfo(call.Expression); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_2() { const string source = @" class Program { static object M = null; static void Main(string[] args) { M?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var m = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single().Expression; var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_3() { const string source = @" class Program { object M = null; static void Main(string[] args) { (new Program()).M?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var m = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single().Expression; var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_4() { const string source = @" class Program { static void Main(string[] args) { var y = (System.Linq.Enumerable.Select<string, int>(args, s => int.Parse(s)))?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<GenericNameSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.NotNull(symbolInfo.Symbol); } [Fact] public void GenericAttribute_LookupSymbols_01() { var source = @" using System; class Attr1<T> : Attribute { public Attr1(T t) { } } [Attr1<string>(""a"")] class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single(); var symbol = model.GetSymbolInfo(node); Assert.Equal("Attr1<System.String>..ctor(System.String t)", symbol.Symbol.ToTestDisplayString()); } [Fact] public void GenericAttribute_LookupSymbols_02() { var source = @" using System; class Attr1<T> : Attribute { public Attr1(T t) { } } [Attr1</*<bind>*/string/*</bind>*/>] class C { }"; var names = GetLookupNames(source); Assert.Contains("C", names); Assert.Contains("Attr1", names); } #endregion } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpArgumentProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpArgumentProvider : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpArgumentProvider(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpArgumentProvider)) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.Workspace.SetArgumentCompletionSnippetsOption(true); } [WpfFact] public void SimpleTabTabCompletion() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$", assertCaretPosition: true); } [WpfFact] public void TabTabCompleteObjectEquals() { SetUpEditor(@" public class Test { public void Method() { $$ } } "); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null)$$", assertCaretPosition: true); } [WpfFact] public void TabTabCompleteNewObject() { SetUpEditor(@" public class Test { public void Method() { var value = $$ } } "); VisualStudio.Editor.SendKeys("new obje"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("var value = new object$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("var value = new object($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("var value = new object()$$", assertCaretPosition: true); } [WpfFact] public void TabTabBeforeSemicolon() { SetUpEditor(@" public class Test { private object f; public void Method() { $$; } } "); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$;", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$);", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$;", assertCaretPosition: true); } [WpfFact] public void TabTabCompletionWithArguments() { SetUpEditor(@" using System; public class Test { private int f; public void Method(IFormatProvider provider) {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(null$$, provider)", assertCaretPosition: true); VisualStudio.Editor.SendKeys("\"format\""); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$, provider)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\", provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true); } [WpfFact] public void FullCycle() { SetUpEditor(@" using System; public class TestClass { public void Method() {$$ } void Test() { } void Test(int x) { } void Test(int x, int y) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("Test"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("Test$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); } [WpfFact] public void ImplicitArgumentSwitching() { SetUpEditor(@" using System; public class TestClass { public void Method() {$$ } void Test() { } void Test(int x) { } void Test(int x, int y) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("Tes"); // Trigger the session and type '0' without waiting for the session to finish initializing VisualStudio.Editor.SendKeys(VirtualKey.Tab, VirtualKey.Tab, '0'); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); } /// <summary> /// Argument completion with no arguments. /// </summary> [WpfFact] public void SemicolonWithTabTabCompletion1() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("f.ToString();$$", assertCaretPosition: true); } /// <summary> /// Argument completion with one or more arguments. /// </summary> [WpfFact] public void SemicolonWithTabTabCompletion2() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null)$$", assertCaretPosition: true); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/56394")] public void SmartBreakLineWithTabTabCompletion1() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter)); VisualStudio.Editor.Verify.TextContains(@" public class Test { private object f; public void Method() { f.ToString(); $$ } } ", assertCaretPosition: true); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/56394")] public void SmartBreakLineWithTabTabCompletion2() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter)); VisualStudio.Editor.Verify.TextContains(@" public class Test { private object f; public void Method() { object.Equals(null); $$ } } ", assertCaretPosition: true); } [WpfTheory] [InlineData("\"<\"", Skip = "https://github.com/dotnet/roslyn/issues/29669")] [InlineData("\">\"")] // testing things that might break XML [InlineData("\"&\"")] [InlineData("\" \"")] [InlineData("\"$placeholder$\"")] // ensuring our snippets aren't substituted in ways we don't expect [InlineData("\"$end$\"")] public void EnsureParameterContentPreserved(string parameterText) { SetUpEditor(@" public class Test { public void Method() {$$ } public void M(string s, int i) { } public void M(string s, int i, int i2) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("M"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("M$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("M(null, 0)"); VisualStudio.Editor.SendKeys(parameterText); VisualStudio.Editor.Verify.CurrentLineText("M(" + parameterText + ", 0)"); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("M(" + parameterText + ", 0, 0)"); } [WpfFact] [WorkItem(54038, "https://github.com/dotnet/roslyn/issues/54038")] public void InsertPreprocessorSnippet() { SetUpEditor(@" using System; public class TestClass { $$ } "); VisualStudio.Editor.SendKeys("#i"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("#if$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("#if true$$", assertCaretPosition: true); var expected = @" using System; public class TestClass { #if true #endif } "; AssertEx.EqualOrDiff(expected, VisualStudio.Editor.GetText()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpArgumentProvider : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpArgumentProvider(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpArgumentProvider)) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.Workspace.SetArgumentCompletionSnippetsOption(true); } [WpfFact] public void SimpleTabTabCompletion() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$", assertCaretPosition: true); } [WpfFact] public void TabTabCompleteObjectEquals() { SetUpEditor(@" public class Test { public void Method() { $$ } } "); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null)$$", assertCaretPosition: true); } [WpfFact] public void TabTabCompleteNewObject() { SetUpEditor(@" public class Test { public void Method() { var value = $$ } } "); VisualStudio.Editor.SendKeys("new obje"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("var value = new object$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("var value = new object($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("var value = new object()$$", assertCaretPosition: true); } [WpfFact] public void TabTabBeforeSemicolon() { SetUpEditor(@" public class Test { private object f; public void Method() { $$; } } "); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$;", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$);", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$;", assertCaretPosition: true); } [WpfFact] public void TabTabCompletionWithArguments() { SetUpEditor(@" using System; public class Test { private int f; public void Method(IFormatProvider provider) {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(null$$, provider)", assertCaretPosition: true); VisualStudio.Editor.SendKeys("\"format\""); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$, provider)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\", provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true); } [WpfFact] public void FullCycle() { SetUpEditor(@" using System; public class TestClass { public void Method() {$$ } void Test() { } void Test(int x) { } void Test(int x, int y) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("Test"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("Test$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); } [WpfFact] public void ImplicitArgumentSwitching() { SetUpEditor(@" using System; public class TestClass { public void Method() {$$ } void Test() { } void Test(int x) { } void Test(int x, int y) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("Tes"); // Trigger the session and type '0' without waiting for the session to finish initializing VisualStudio.Editor.SendKeys(VirtualKey.Tab, VirtualKey.Tab, '0'); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); } /// <summary> /// Argument completion with no arguments. /// </summary> [WpfFact] public void SemicolonWithTabTabCompletion1() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("f.ToString();$$", assertCaretPosition: true); } /// <summary> /// Argument completion with one or more arguments. /// </summary> [WpfFact] public void SemicolonWithTabTabCompletion2() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null)$$", assertCaretPosition: true); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/56394")] public void SmartBreakLineWithTabTabCompletion1() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter)); VisualStudio.Editor.Verify.TextContains(@" public class Test { private object f; public void Method() { f.ToString(); $$ } } ", assertCaretPosition: true); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/56394")] public void SmartBreakLineWithTabTabCompletion2() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter)); VisualStudio.Editor.Verify.TextContains(@" public class Test { private object f; public void Method() { object.Equals(null); $$ } } ", assertCaretPosition: true); } [WpfTheory] [InlineData("\"<\"", Skip = "https://github.com/dotnet/roslyn/issues/29669")] [InlineData("\">\"")] // testing things that might break XML [InlineData("\"&\"")] [InlineData("\" \"")] [InlineData("\"$placeholder$\"")] // ensuring our snippets aren't substituted in ways we don't expect [InlineData("\"$end$\"")] public void EnsureParameterContentPreserved(string parameterText) { SetUpEditor(@" public class Test { public void Method() {$$ } public void M(string s, int i) { } public void M(string s, int i, int i2) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("M"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("M$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("M(null, 0)"); VisualStudio.Editor.SendKeys(parameterText); VisualStudio.Editor.Verify.CurrentLineText("M(" + parameterText + ", 0)"); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("M(" + parameterText + ", 0, 0)"); } [WpfFact] [WorkItem(54038, "https://github.com/dotnet/roslyn/issues/54038")] public void InsertPreprocessorSnippet() { SetUpEditor(@" using System; public class TestClass { $$ } "); VisualStudio.Editor.SendKeys("#i"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("#if$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("#if true$$", assertCaretPosition: true); var expected = @" using System; public class TestClass { #if true #endif } "; AssertEx.EqualOrDiff(expected, VisualStudio.Editor.GetText()); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Features/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentRangeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Formatting { public class FormatDocumentRangeTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestFormatDocumentRangeAsync() { var markup = @"class A { {|format:void|} M() { int i = 1; } }"; var expected = @"class A { void M() { int i = 1; } }"; using var testLspServer = await CreateTestLspServerAsync(markup); var rangeToFormat = testLspServer.GetLocations("format").Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(rangeToFormat.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentRangeAsync(testLspServer, rangeToFormat); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } [Fact] public async Task TestFormatDocumentRange_UseTabsAsync() { var markup = @"class A { {|format:void|} M() { int i = 1; } }"; var expected = @"class A { void M() { int i = 1; } }"; using var testLspServer = await CreateTestLspServerAsync(markup); var rangeToFormat = testLspServer.GetLocations("format").Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(rangeToFormat.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentRangeAsync(testLspServer, rangeToFormat, insertSpaces: false, tabSize: 4); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } private static async Task<LSP.TextEdit[]> RunFormatDocumentRangeAsync( TestLspServer testLspServer, LSP.Location location, bool insertSpaces = true, int tabSize = 4) { return await testLspServer.ExecuteRequestAsync<LSP.DocumentRangeFormattingParams, LSP.TextEdit[]>( LSP.Methods.TextDocumentRangeFormattingName, CreateDocumentRangeFormattingParams(location, insertSpaces, tabSize), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); } private static LSP.DocumentRangeFormattingParams CreateDocumentRangeFormattingParams( LSP.Location location, bool insertSpaces, int tabSize) => new LSP.DocumentRangeFormattingParams() { Range = location.Range, TextDocument = CreateTextDocumentIdentifier(location.Uri), Options = new LSP.FormattingOptions() { InsertSpaces = insertSpaces, TabSize = tabSize } }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Formatting { public class FormatDocumentRangeTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestFormatDocumentRangeAsync() { var markup = @"class A { {|format:void|} M() { int i = 1; } }"; var expected = @"class A { void M() { int i = 1; } }"; using var testLspServer = await CreateTestLspServerAsync(markup); var rangeToFormat = testLspServer.GetLocations("format").Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(rangeToFormat.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentRangeAsync(testLspServer, rangeToFormat); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } [Fact] public async Task TestFormatDocumentRange_UseTabsAsync() { var markup = @"class A { {|format:void|} M() { int i = 1; } }"; var expected = @"class A { void M() { int i = 1; } }"; using var testLspServer = await CreateTestLspServerAsync(markup); var rangeToFormat = testLspServer.GetLocations("format").Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(rangeToFormat.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentRangeAsync(testLspServer, rangeToFormat, insertSpaces: false, tabSize: 4); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } private static async Task<LSP.TextEdit[]> RunFormatDocumentRangeAsync( TestLspServer testLspServer, LSP.Location location, bool insertSpaces = true, int tabSize = 4) { return await testLspServer.ExecuteRequestAsync<LSP.DocumentRangeFormattingParams, LSP.TextEdit[]>( LSP.Methods.TextDocumentRangeFormattingName, CreateDocumentRangeFormattingParams(location, insertSpaces, tabSize), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); } private static LSP.DocumentRangeFormattingParams CreateDocumentRangeFormattingParams( LSP.Location location, bool insertSpaces, int tabSize) => new LSP.DocumentRangeFormattingParams() { Range = location.Range, TextDocument = CreateTextDocumentIdentifier(location.Uri), Options = new LSP.FormattingOptions() { InsertSpaces = insertSpaces, TabSize = tabSize } }; } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType { public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning); private readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error); // specify all options explicitly to override defaults. private OptionsCollection ExplicitTypeEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeExceptWhereApparent() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeForBuiltInTypesOnly() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeEnforcements() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithWarning }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeSilentEnforcement() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent }, }; #region Error Cases [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnFieldDeclaration() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|var|] _myfield = 5; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnFieldLikeEvents() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { public event [|var|] _myevent; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnAnonymousMethodExpression() { var before = @"using System; class Program { void Method() { [|var|] comparer = delegate (string value) { return value != ""0""; }; } }"; var after = @"using System; class Program { void Method() { Func<string, bool> comparer = delegate (string value) { return value != ""0""; }; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnLambdaExpression() { var before = @"using System; class Program { void Method() { [|var|] x = (int y) => y * y; } }"; var after = @"using System; class Program { void Method() { Func<int, int> x = (int y) => y * y; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDeclarationWithMultipleDeclarators() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = 5, y = x; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDeclarationWithoutInitializer() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotDuringConflicts() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] p = new var(); } class var { } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotIfAlreadyExplicitlyTyped() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p = new Program(); } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task NotIfRefTypeAlreadyExplicitlyTyped() { await TestMissingInRegularAndScriptAsync( @"using System; struct Program { void Method() { ref [|Program|] p = Ref(); } ref Program Ref() => throw null; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnRHS() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { var c = new [|var|](); } } class var { }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorSymbol() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new Goo(); } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorConvertedType_ForEachVariableStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { void M() { // Error CS1061: 'KeyValuePair<int, int>' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair<int, int>' could be found (are you missing a using directive or an assembly reference?) // Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair<int, int>', with 2 out parameters and a void return type. foreach ([|var|] (key, value) in new Dictionary<int, int>()) { } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorConvertedType_AssignmentExpressionStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { void M(C c) { // Error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. [|var|] (key, value) = c; } }", new TestParameters(options: ExplicitTypeEverywhere())); } #endregion [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayType() { var before = @" class Program { void Method() { [|var|] x = new Program[0]; } }"; var after = @" class Program { void Method() { Program[] x = new Program[0]; } }"; // The type is apparent and not intrinsic await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayTypeWithIntrinsicType() { var before = @" class Program { void Method() { [|var|] x = new int[0]; } }"; var after = @" class Program { void Method() { int[] x = new int[0]; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InNullableIntrinsicType() { var before = @" class Program { void Method(int? x) { [|var|] y = x; } }"; var after = @" class Program { void Method(int? x) { int? y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task InNativeIntIntrinsicType() { var before = @" class Program { void Method(nint x) { [|var|] y = x; } }"; var after = @" class Program { void Method(nint x) { nint y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task InNativeUnsignedIntIntrinsicType() { var before = @" class Program { void Method(nuint x) { [|var|] y = x; } }"; var after = @" class Program { void Method(nuint x) { nuint y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task WithRefIntrinsicType() { var before = @" class Program { void Method() { ref [|var|] y = Ref(); } ref int Ref() => throw null; }"; var after = @" class Program { void Method() { ref int y = Ref(); } ref int Ref() => throw null; }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task WithRefIntrinsicTypeInForeach() { var before = @" class E { public ref int Current => throw null; public bool MoveNext() => throw null; public E GetEnumerator() => throw null; void M() { foreach (ref [|var|] x in this) { } } }"; var after = @" class E { public ref int Current => throw null; public bool MoveNext() => throw null; public E GetEnumerator() => throw null; void M() { foreach (ref int x in this) { } } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayOfNullableIntrinsicType() { var before = @" class Program { void Method(int?[] x) { [|var|] y = x; } }"; var after = @" class Program { void Method(int?[] x) { int?[] y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InNullableCustomType() { var before = @" struct Program { void Method(Program? x) { [|var|] y = x; } }"; var after = @" struct Program { void Method(Program? x) { Program? y = x; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType() { var before = @" #nullable enable class Program { void Method(Program x) { [|var|] y = x; y = null; } }"; var after = @" #nullable enable class Program { void Method(Program x) { Program? y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType() { var before = @" #nullable enable class Program { void Method(Program x) { #nullable disable [|var|] y = x; y = null; } }"; var after = @" #nullable enable class Program { void Method(Program x) { #nullable disable Program y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType() { var before = @" class Program { void Method(Program x) { #nullable enable [|var|] y = x; y = null; } }"; var after = @" class Program { void Method(Program x) { #nullable enable Program? y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_OutVar() { var before = @" #nullable enable class Program { void Method(out Program? x) { Method(out [|var|] y1); throw null!; } }"; var after = @" #nullable enable class Program { void Method(out Program? x) { Method(out Program? y1); throw null!; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_OutVar() { var before = @" #nullable enable class Program { void Method(out Program x) { Method(out [|var|] y1); throw null!; } }"; var after = @" #nullable enable class Program { void Method(out Program x) { Method(out Program? y1); throw null!; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_OutVar() { var before = @" class Program { void Method(out Program x) { Method(out [|var|] y1); throw null; } }"; var after = @" class Program { void Method(out Program x) { Method(out Program y1); throw null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40925"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] [WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")] public async Task NullableTypeAndNotNullableType_VarDeconstruction() { var before = @" #nullable enable class Program2 { } class Program { void Method(Program? x, Program2 x2) { [|var|] (y1, y2) = (x, x2); } }"; var after = @" #nullable enable class Program2 { } class Program { void Method(Program? x, Program2 x2) { (Program? y1, Program2? y2) = (x, x2); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_VarDeconstruction() { var before = @" #nullable enable class Program2 { } class Program { void Method(Program x, Program2 x2) { #nullable disable [|var|] (y1, y2) = (x, x2); } }"; var after = @" #nullable enable class Program2 { } class Program { void Method(Program x, Program2 x2) { #nullable disable (Program y1, Program2 y2) = (x, x2); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_Deconstruction() { var before = @" #nullable enable class Program { void Method(Program x) { #nullable disable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" #nullable enable class Program { void Method(Program x) { #nullable disable (Program y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_Deconstruction() { var before = @" class Program { void Method(Program x) { #nullable enable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" class Program { void Method(Program x) { #nullable enable (Program? y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_Deconstruction() { var before = @" class Program { void Method(Program? x) { #nullable enable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" class Program { void Method(Program? x) { #nullable enable (Program? y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_Foreach() { var before = @" #nullable enable class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable disable foreach ([|var|] y in x) { } } }"; var after = @" #nullable enable class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable disable foreach ([|Program|] y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_Foreach() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach ([|var|] y in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach (Program? y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_Foreach() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach ([|var|] y in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach (Program? y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37491"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_ForeachVarDeconstruction() { // Semantic model doesn't yet handle var deconstruction foreach // https://github.com/dotnet/roslyn/issues/37491 // https://github.com/dotnet/roslyn/issues/35010 var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ([|var|] (y1, y2) in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ((Program? y1, Program? y2) in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_ForeachDeconstruction() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach (([|var|] y1, var y2) in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ((Program? y1, var y2) in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InPointerTypeWithIntrinsicType() { var before = @" unsafe class Program { void Method(int* y) { [|var|] x = y; } }"; var after = @" unsafe class Program { void Method(int* y) { int* x = y; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InPointerTypeWithCustomType() { var before = @" unsafe class Program { void Method(Program* y) { [|var|] x = y; } }"; var after = @" unsafe class Program { void Method(Program* y) { Program* x = y; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23893, "https://github.com/dotnet/roslyn/issues/23893")] public async Task InOutParameter() { var before = @" class Program { void Method(out int x) { Method(out [|var|] x); } }"; var after = @" class Program { void Method(out int x) { Method(out int x); } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnForEachVarWithAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5).Select(i => new { Value = i }); foreach ([|var|] value in values) { Console.WriteLine(value.Value); } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarParens() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, string y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { ([|var|] x, var y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, var y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, (y, z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, (int y, Program z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnBadlyFormattedNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|](x,(y,z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, (int y, Program z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnForeachNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { foreach ([|var|] (x, (y, z)) in new[] { new Program() } { } } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { foreach ((int x, (int y, Program z)) in new[] { new Program() } { } } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnNestedDeconstructionVarWithTrivia() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { /*before*/[|var|]/*after*/ (/*x1*/x/*x2*/, /*yz1*/(/*y1*/y/*y2*/, /*z1*/z/*z2*/)/*yz2*/) /*end*/ = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { /*before*//*after*/(/*x1*/int x/*x2*/, /*yz1*/(/*y1*/int y/*y2*/, /*z1*/Program z/*z2*/)/*yz2*/) /*end*/ = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarWithDiscard() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, _) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, string _) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarWithErrorType() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, y) = new Program(); } void Deconstruct(out int i, out Error s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, Error y) = new Program(); } void Deconstruct(out int i, out Error s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnForEachVarWithExplicitType() { await TestInRegularAndScriptAsync( @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5); foreach ([|var|] value in values) { Console.WriteLine(value.Value); } } }", @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5); foreach (int value in values) { Console.WriteLine(value.Value); } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new { Amount = 108, Message = ""Hello"" }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnArrayOfAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { void Method() { var products = new List<Product>(); [|var|] productQuery = from prod in products select new { prod.Color, prod.Price }; } } class Product { public ConsoleColor Color { get; set; } public int Price { get; set; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] s = ""hello""; } }", @"using System; class C { static void M() { string s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnIntrinsicType() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] s = 5; } }", @"using System; class C { static void M() { int s = 5; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnFrameworkType() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { static void M() { [|var|] c = new List<int>(); } }", @"using System.Collections.Generic; class C { static void M() { List<int> c = new List<int>(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnUserDefinedType() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { [|var|] c = new C(); } }", @"using System; class C { void M() { C c = new C(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnGenericType() { await TestInRegularAndScriptAsync( @"using System; class C<T> { static void M() { [|var|] c = new C<int>(); } }", @"using System; class C<T> { static void M() { C<int> c = new C<int>(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] n1 = new int[4] { 2, 4, 6, 8 }; } }", @"using System; class C { static void M() { int[] n1 = new int[4] { 2, 4, 6, 8 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] n1 = new[] { 2, 4, 6, 8 }; } }", @"using System; class C { static void M() { int[] n1 = new[] { 2, 4, 6, 8 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] cs = new[] { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 } }; } }", @"using System; class C { static void M() { int[][] cs = new[] { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 } }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] cc = new Customer { City = ""Chennai"" }; } private class Customer { public string City { get; set; } } }", @"using System; class C { static void M() { Customer cc = new Customer { City = ""Chennai"" }; } private class Customer { public string City { get; set; } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { [|var|] digits = new List<int> { 1, 2, 3 }; } }", @"using System; using System.Collections.Generic; class C { static void M() { List<int> digits = new List<int> { 1, 2, 3 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { [|var|] cs = new List<Customer> { new Customer { City = ""Chennai"" } }; } private class Customer { public string City { get; set; } } }", @"using System; using System.Collections.Generic; class C { static void M() { List<Customer> cs = new List<Customer> { new Customer { City = ""Chennai"" } }; } private class Customer { public string City { get; set; } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnForStatement() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { for ([|var|] i = 0; i < 5; i++) { } } }", @"using System; class C { static void M() { for (int i = 0; i < 5; i++) { } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnForeachStatement() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { var l = new List<int> { 1, 3, 5 }; foreach ([|var|] item in l) { } } }", @"using System; using System.Collections.Generic; class C { static void M() { var l = new List<int> { 1, 3, 5 }; foreach (int item in l) { } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnQueryExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class C { static void M() { var customers = new List<Customer>(); [|var|] expr = from c in customers where c.City == ""London"" select c; } private class Customer { public string City { get; set; } } } }", @"using System; using System.Collections.Generic; using System.Linq; class C { static void M() { var customers = new List<Customer>(); IEnumerable<Customer> expr = from c in customers where c.City == ""London"" select c; } private class Customer { public string City { get; set; } } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInUsingStatement() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { using ([|var|] r = new Res()) { } } private class Res : IDisposable { public void Dispose() { throw new NotImplementedException(); } } }", @"using System; class C { static void M() { using (Res r = new Res()) { } } private class Res : IDisposable { public void Dispose() { throw new NotImplementedException(); } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnInterpolatedString() { await TestInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] s = $""Hello, {name}"" } }", @"using System; class Program { void Method() { string s = $""Hello, {name}"" } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnExplicitConversion() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { double x = 1234.7; [|var|] a = (int)x; } }", @"using System; class C { static void M() { double x = 1234.7; int a = (int)x; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { C obj = new C(); [|var|] anotherObj = obj?.Test(); } C Test() { return this; } }", @"using System; class C { static void M() { C obj = new C(); C anotherObj = obj?.Test(); } C Test() { return this; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInCheckedExpression() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { long number1 = int.MaxValue + 20L; [|var|] intNumber = checked((int)number1); } }", @"using System; class C { static void M() { long number1 = int.MaxValue + 20L; int intNumber = checked((int)number1); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInAwaitExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { [|var|] text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return string.Empty; } }", @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { string text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return string.Empty; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInNumericType() { await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = 1; } }", @"using System; class C { public void ProcessRead() { int text = 1; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInCharType() { await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = GetChar(); } public char GetChar() => 'c'; }", @"using System; class C { public void ProcessRead() { char text = GetChar(); } public char GetChar() => 'c'; }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInType_string() { // though string isn't an intrinsic type per the compiler // we in the IDE treat it as an intrinsic type for this feature. await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = string.Empty; } }", @"using System; class C { public void ProcessRead() { string text = string.Empty; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInType_object() { // object isn't an intrinsic type per the compiler // we in the IDE treat it as an intrinsic type for this feature. await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { object j = new C(); [|var|] text = j; } }", @"using System; class C { public void ProcessRead() { object j = new C(); object text = j; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelSilent() { var source = @"using System; class C { static void M() { [|var|] n1 = new C(); } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeSilentEnforcement(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Hidden); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelInfo() { var source = @"using System; class C { static void M() { [|var|] s = 5; } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Info); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task SuggestExplicitTypeNotificationLevelWarning() { var source = @"using System; class C { static void M() { [|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelError() { var source = @"using System; class C { static void M() { [|var|] n1 = new C(); } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Error); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (1, ""hello""); } }", @"class C { static void M() { (int, string) s = (1, ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (a: 1, b: ""hello""); } }", @"class C { static void M() { (int a, string b) s = (a: 1, b: ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (a: 1, ""hello""); } }", @"class C { static void M() { (int a, string) s = (a: 1, ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20437, "https://github.com/dotnet/roslyn/issues/20437")] public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { DateTime.TryParse(string.Empty, [|out var|] date); } }", @"using System; class C { static void M() { DateTime.TryParse(string.Empty, out DateTime date); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|String|] test = new String(' ', 4); } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { foreach ([|String|] test in new String[] { ""test1"", ""test2"" }) { } } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { [|Int32[]|] array = new[] { 1, 2, 3 }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { [|Int32[][]|] a = new Int32[][] { new[] { 1, 2 }, new[] { 3, 4 } }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Main() { [|IEnumerable<Int32>|] a = new List<Int32> { 1, 2 }.Where(x => x > 1); } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { String name = ""name""; [|String|] s = $""Hello, {name}"" } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { Object name = ""name""; [|String|] s = (String) name; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { [|String|] text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return String.Empty; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { String number = ""12""; Int32.TryParse(name, out [|Int32|] number) } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { for ([|Int32|] i = 0; i < 5; i++) { } } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Main() { [|List<Int32>|] a = new List<Int32> { 1, 2 }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Method(List<int> var) { foreach (int value in [|var|]) { Console.WriteLine(value.Value); } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnConstVar() { // This error case is handled by a separate code fix (UseExplicitTypeForConst). await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = 0; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task WithNormalFuncSynthesizedLambdaType() { var before = @" class Program { void Method() { [|var|] x = (int i) => i.ToString(); } }"; var after = @" class Program { void Method() { System.Func<int, string> x = (int i) => i.ToString(); } }"; // The type is not apparent and not intrinsic await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task WithAnonymousSynthesizedLambdaType() { var before = @" class Program { void Method() { [|var|] x = (ref int i) => i.ToString(); } }"; // The type is apparent and not intrinsic await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeEverywhere())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType { public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning); private readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error); // specify all options explicitly to override defaults. private OptionsCollection ExplicitTypeEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeExceptWhereApparent() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeForBuiltInTypesOnly() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeEnforcements() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithWarning }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeSilentEnforcement() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent }, }; #region Error Cases [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnFieldDeclaration() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|var|] _myfield = 5; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnFieldLikeEvents() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { public event [|var|] _myevent; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnAnonymousMethodExpression() { var before = @"using System; class Program { void Method() { [|var|] comparer = delegate (string value) { return value != ""0""; }; } }"; var after = @"using System; class Program { void Method() { Func<string, bool> comparer = delegate (string value) { return value != ""0""; }; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnLambdaExpression() { var before = @"using System; class Program { void Method() { [|var|] x = (int y) => y * y; } }"; var after = @"using System; class Program { void Method() { Func<int, int> x = (int y) => y * y; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDeclarationWithMultipleDeclarators() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = 5, y = x; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDeclarationWithoutInitializer() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotDuringConflicts() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] p = new var(); } class var { } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotIfAlreadyExplicitlyTyped() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p = new Program(); } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task NotIfRefTypeAlreadyExplicitlyTyped() { await TestMissingInRegularAndScriptAsync( @"using System; struct Program { void Method() { ref [|Program|] p = Ref(); } ref Program Ref() => throw null; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnRHS() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { var c = new [|var|](); } } class var { }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorSymbol() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new Goo(); } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorConvertedType_ForEachVariableStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { void M() { // Error CS1061: 'KeyValuePair<int, int>' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair<int, int>' could be found (are you missing a using directive or an assembly reference?) // Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair<int, int>', with 2 out parameters and a void return type. foreach ([|var|] (key, value) in new Dictionary<int, int>()) { } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorConvertedType_AssignmentExpressionStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { void M(C c) { // Error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. [|var|] (key, value) = c; } }", new TestParameters(options: ExplicitTypeEverywhere())); } #endregion [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayType() { var before = @" class Program { void Method() { [|var|] x = new Program[0]; } }"; var after = @" class Program { void Method() { Program[] x = new Program[0]; } }"; // The type is apparent and not intrinsic await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayTypeWithIntrinsicType() { var before = @" class Program { void Method() { [|var|] x = new int[0]; } }"; var after = @" class Program { void Method() { int[] x = new int[0]; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InNullableIntrinsicType() { var before = @" class Program { void Method(int? x) { [|var|] y = x; } }"; var after = @" class Program { void Method(int? x) { int? y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task InNativeIntIntrinsicType() { var before = @" class Program { void Method(nint x) { [|var|] y = x; } }"; var after = @" class Program { void Method(nint x) { nint y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task InNativeUnsignedIntIntrinsicType() { var before = @" class Program { void Method(nuint x) { [|var|] y = x; } }"; var after = @" class Program { void Method(nuint x) { nuint y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task WithRefIntrinsicType() { var before = @" class Program { void Method() { ref [|var|] y = Ref(); } ref int Ref() => throw null; }"; var after = @" class Program { void Method() { ref int y = Ref(); } ref int Ref() => throw null; }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task WithRefIntrinsicTypeInForeach() { var before = @" class E { public ref int Current => throw null; public bool MoveNext() => throw null; public E GetEnumerator() => throw null; void M() { foreach (ref [|var|] x in this) { } } }"; var after = @" class E { public ref int Current => throw null; public bool MoveNext() => throw null; public E GetEnumerator() => throw null; void M() { foreach (ref int x in this) { } } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayOfNullableIntrinsicType() { var before = @" class Program { void Method(int?[] x) { [|var|] y = x; } }"; var after = @" class Program { void Method(int?[] x) { int?[] y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InNullableCustomType() { var before = @" struct Program { void Method(Program? x) { [|var|] y = x; } }"; var after = @" struct Program { void Method(Program? x) { Program? y = x; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType() { var before = @" #nullable enable class Program { void Method(Program x) { [|var|] y = x; y = null; } }"; var after = @" #nullable enable class Program { void Method(Program x) { Program? y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType() { var before = @" #nullable enable class Program { void Method(Program x) { #nullable disable [|var|] y = x; y = null; } }"; var after = @" #nullable enable class Program { void Method(Program x) { #nullable disable Program y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType() { var before = @" class Program { void Method(Program x) { #nullable enable [|var|] y = x; y = null; } }"; var after = @" class Program { void Method(Program x) { #nullable enable Program? y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_OutVar() { var before = @" #nullable enable class Program { void Method(out Program? x) { Method(out [|var|] y1); throw null!; } }"; var after = @" #nullable enable class Program { void Method(out Program? x) { Method(out Program? y1); throw null!; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_OutVar() { var before = @" #nullable enable class Program { void Method(out Program x) { Method(out [|var|] y1); throw null!; } }"; var after = @" #nullable enable class Program { void Method(out Program x) { Method(out Program? y1); throw null!; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_OutVar() { var before = @" class Program { void Method(out Program x) { Method(out [|var|] y1); throw null; } }"; var after = @" class Program { void Method(out Program x) { Method(out Program y1); throw null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40925"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] [WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")] public async Task NullableTypeAndNotNullableType_VarDeconstruction() { var before = @" #nullable enable class Program2 { } class Program { void Method(Program? x, Program2 x2) { [|var|] (y1, y2) = (x, x2); } }"; var after = @" #nullable enable class Program2 { } class Program { void Method(Program? x, Program2 x2) { (Program? y1, Program2? y2) = (x, x2); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_VarDeconstruction() { var before = @" #nullable enable class Program2 { } class Program { void Method(Program x, Program2 x2) { #nullable disable [|var|] (y1, y2) = (x, x2); } }"; var after = @" #nullable enable class Program2 { } class Program { void Method(Program x, Program2 x2) { #nullable disable (Program y1, Program2 y2) = (x, x2); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_Deconstruction() { var before = @" #nullable enable class Program { void Method(Program x) { #nullable disable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" #nullable enable class Program { void Method(Program x) { #nullable disable (Program y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_Deconstruction() { var before = @" class Program { void Method(Program x) { #nullable enable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" class Program { void Method(Program x) { #nullable enable (Program? y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_Deconstruction() { var before = @" class Program { void Method(Program? x) { #nullable enable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" class Program { void Method(Program? x) { #nullable enable (Program? y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_Foreach() { var before = @" #nullable enable class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable disable foreach ([|var|] y in x) { } } }"; var after = @" #nullable enable class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable disable foreach ([|Program|] y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_Foreach() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach ([|var|] y in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach (Program? y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_Foreach() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach ([|var|] y in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach (Program? y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37491"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_ForeachVarDeconstruction() { // Semantic model doesn't yet handle var deconstruction foreach // https://github.com/dotnet/roslyn/issues/37491 // https://github.com/dotnet/roslyn/issues/35010 var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ([|var|] (y1, y2) in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ((Program? y1, Program? y2) in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_ForeachDeconstruction() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach (([|var|] y1, var y2) in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ((Program? y1, var y2) in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InPointerTypeWithIntrinsicType() { var before = @" unsafe class Program { void Method(int* y) { [|var|] x = y; } }"; var after = @" unsafe class Program { void Method(int* y) { int* x = y; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InPointerTypeWithCustomType() { var before = @" unsafe class Program { void Method(Program* y) { [|var|] x = y; } }"; var after = @" unsafe class Program { void Method(Program* y) { Program* x = y; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23893, "https://github.com/dotnet/roslyn/issues/23893")] public async Task InOutParameter() { var before = @" class Program { void Method(out int x) { Method(out [|var|] x); } }"; var after = @" class Program { void Method(out int x) { Method(out int x); } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnForEachVarWithAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5).Select(i => new { Value = i }); foreach ([|var|] value in values) { Console.WriteLine(value.Value); } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarParens() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, string y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { ([|var|] x, var y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, var y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, (y, z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, (int y, Program z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnBadlyFormattedNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|](x,(y,z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, (int y, Program z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnForeachNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { foreach ([|var|] (x, (y, z)) in new[] { new Program() } { } } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { foreach ((int x, (int y, Program z)) in new[] { new Program() } { } } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnNestedDeconstructionVarWithTrivia() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { /*before*/[|var|]/*after*/ (/*x1*/x/*x2*/, /*yz1*/(/*y1*/y/*y2*/, /*z1*/z/*z2*/)/*yz2*/) /*end*/ = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { /*before*//*after*/(/*x1*/int x/*x2*/, /*yz1*/(/*y1*/int y/*y2*/, /*z1*/Program z/*z2*/)/*yz2*/) /*end*/ = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarWithDiscard() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, _) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, string _) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarWithErrorType() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, y) = new Program(); } void Deconstruct(out int i, out Error s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, Error y) = new Program(); } void Deconstruct(out int i, out Error s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnForEachVarWithExplicitType() { await TestInRegularAndScriptAsync( @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5); foreach ([|var|] value in values) { Console.WriteLine(value.Value); } } }", @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5); foreach (int value in values) { Console.WriteLine(value.Value); } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new { Amount = 108, Message = ""Hello"" }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnArrayOfAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { void Method() { var products = new List<Product>(); [|var|] productQuery = from prod in products select new { prod.Color, prod.Price }; } } class Product { public ConsoleColor Color { get; set; } public int Price { get; set; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] s = ""hello""; } }", @"using System; class C { static void M() { string s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnIntrinsicType() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] s = 5; } }", @"using System; class C { static void M() { int s = 5; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnFrameworkType() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { static void M() { [|var|] c = new List<int>(); } }", @"using System.Collections.Generic; class C { static void M() { List<int> c = new List<int>(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnUserDefinedType() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { [|var|] c = new C(); } }", @"using System; class C { void M() { C c = new C(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnGenericType() { await TestInRegularAndScriptAsync( @"using System; class C<T> { static void M() { [|var|] c = new C<int>(); } }", @"using System; class C<T> { static void M() { C<int> c = new C<int>(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] n1 = new int[4] { 2, 4, 6, 8 }; } }", @"using System; class C { static void M() { int[] n1 = new int[4] { 2, 4, 6, 8 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] n1 = new[] { 2, 4, 6, 8 }; } }", @"using System; class C { static void M() { int[] n1 = new[] { 2, 4, 6, 8 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] cs = new[] { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 } }; } }", @"using System; class C { static void M() { int[][] cs = new[] { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 } }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] cc = new Customer { City = ""Chennai"" }; } private class Customer { public string City { get; set; } } }", @"using System; class C { static void M() { Customer cc = new Customer { City = ""Chennai"" }; } private class Customer { public string City { get; set; } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { [|var|] digits = new List<int> { 1, 2, 3 }; } }", @"using System; using System.Collections.Generic; class C { static void M() { List<int> digits = new List<int> { 1, 2, 3 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { [|var|] cs = new List<Customer> { new Customer { City = ""Chennai"" } }; } private class Customer { public string City { get; set; } } }", @"using System; using System.Collections.Generic; class C { static void M() { List<Customer> cs = new List<Customer> { new Customer { City = ""Chennai"" } }; } private class Customer { public string City { get; set; } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnForStatement() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { for ([|var|] i = 0; i < 5; i++) { } } }", @"using System; class C { static void M() { for (int i = 0; i < 5; i++) { } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnForeachStatement() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { var l = new List<int> { 1, 3, 5 }; foreach ([|var|] item in l) { } } }", @"using System; using System.Collections.Generic; class C { static void M() { var l = new List<int> { 1, 3, 5 }; foreach (int item in l) { } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnQueryExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class C { static void M() { var customers = new List<Customer>(); [|var|] expr = from c in customers where c.City == ""London"" select c; } private class Customer { public string City { get; set; } } } }", @"using System; using System.Collections.Generic; using System.Linq; class C { static void M() { var customers = new List<Customer>(); IEnumerable<Customer> expr = from c in customers where c.City == ""London"" select c; } private class Customer { public string City { get; set; } } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInUsingStatement() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { using ([|var|] r = new Res()) { } } private class Res : IDisposable { public void Dispose() { throw new NotImplementedException(); } } }", @"using System; class C { static void M() { using (Res r = new Res()) { } } private class Res : IDisposable { public void Dispose() { throw new NotImplementedException(); } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnInterpolatedString() { await TestInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] s = $""Hello, {name}"" } }", @"using System; class Program { void Method() { string s = $""Hello, {name}"" } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnExplicitConversion() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { double x = 1234.7; [|var|] a = (int)x; } }", @"using System; class C { static void M() { double x = 1234.7; int a = (int)x; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { C obj = new C(); [|var|] anotherObj = obj?.Test(); } C Test() { return this; } }", @"using System; class C { static void M() { C obj = new C(); C anotherObj = obj?.Test(); } C Test() { return this; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInCheckedExpression() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { long number1 = int.MaxValue + 20L; [|var|] intNumber = checked((int)number1); } }", @"using System; class C { static void M() { long number1 = int.MaxValue + 20L; int intNumber = checked((int)number1); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInAwaitExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { [|var|] text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return string.Empty; } }", @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { string text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return string.Empty; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInNumericType() { await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = 1; } }", @"using System; class C { public void ProcessRead() { int text = 1; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInCharType() { await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = GetChar(); } public char GetChar() => 'c'; }", @"using System; class C { public void ProcessRead() { char text = GetChar(); } public char GetChar() => 'c'; }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInType_string() { // though string isn't an intrinsic type per the compiler // we in the IDE treat it as an intrinsic type for this feature. await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = string.Empty; } }", @"using System; class C { public void ProcessRead() { string text = string.Empty; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInType_object() { // object isn't an intrinsic type per the compiler // we in the IDE treat it as an intrinsic type for this feature. await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { object j = new C(); [|var|] text = j; } }", @"using System; class C { public void ProcessRead() { object j = new C(); object text = j; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelSilent() { var source = @"using System; class C { static void M() { [|var|] n1 = new C(); } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeSilentEnforcement(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Hidden); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelInfo() { var source = @"using System; class C { static void M() { [|var|] s = 5; } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Info); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task SuggestExplicitTypeNotificationLevelWarning() { var source = @"using System; class C { static void M() { [|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelError() { var source = @"using System; class C { static void M() { [|var|] n1 = new C(); } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Error); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (1, ""hello""); } }", @"class C { static void M() { (int, string) s = (1, ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (a: 1, b: ""hello""); } }", @"class C { static void M() { (int a, string b) s = (a: 1, b: ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (a: 1, ""hello""); } }", @"class C { static void M() { (int a, string) s = (a: 1, ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20437, "https://github.com/dotnet/roslyn/issues/20437")] public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { DateTime.TryParse(string.Empty, [|out var|] date); } }", @"using System; class C { static void M() { DateTime.TryParse(string.Empty, out DateTime date); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|String|] test = new String(' ', 4); } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { foreach ([|String|] test in new String[] { ""test1"", ""test2"" }) { } } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { [|Int32[]|] array = new[] { 1, 2, 3 }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { [|Int32[][]|] a = new Int32[][] { new[] { 1, 2 }, new[] { 3, 4 } }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Main() { [|IEnumerable<Int32>|] a = new List<Int32> { 1, 2 }.Where(x => x > 1); } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { String name = ""name""; [|String|] s = $""Hello, {name}"" } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { Object name = ""name""; [|String|] s = (String) name; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { [|String|] text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return String.Empty; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { String number = ""12""; Int32.TryParse(name, out [|Int32|] number) } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { for ([|Int32|] i = 0; i < 5; i++) { } } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Main() { [|List<Int32>|] a = new List<Int32> { 1, 2 }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Method(List<int> var) { foreach (int value in [|var|]) { Console.WriteLine(value.Value); } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnConstVar() { // This error case is handled by a separate code fix (UseExplicitTypeForConst). await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = 0; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task WithNormalFuncSynthesizedLambdaType() { var before = @" class Program { void Method() { [|var|] x = (int i) => i.ToString(); } }"; var after = @" class Program { void Method() { System.Func<int, string> x = (int i) => i.ToString(); } }"; // The type is not apparent and not intrinsic await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task WithAnonymousSynthesizedLambdaType() { var before = @" class Program { void Method() { [|var|] x = (ref int i) => i.ToString(); } }"; // The type is apparent and not intrinsic await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeEverywhere())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent())); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/UsingDirectiveSyntaxClassifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers { internal class UsingDirectiveSyntaxClassifier : AbstractSyntaxClassifier { public override void AddClassifications( Workspace workspace, SyntaxNode syntax, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (syntax is UsingDirectiveSyntax usingDirective) { ClassifyUsingDirectiveSyntax(usingDirective, semanticModel, result, cancellationToken); } } public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create(typeof(UsingDirectiveSyntax)); private static void ClassifyUsingDirectiveSyntax( UsingDirectiveSyntax usingDirective, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { // For using aliases, we bind the target on the right of the equals and use that // binding to classify the alias. if (usingDirective.Alias != null) { var token = usingDirective.Alias.Name; var symbolInfo = semanticModel.GetSymbolInfo(usingDirective.Name, cancellationToken); if (symbolInfo.Symbol is ITypeSymbol typeSymbol) { var classification = GetClassificationForType(typeSymbol); if (classification != null) { result.Add(new ClassifiedSpan(token.Span, classification)); } } else if (symbolInfo.Symbol?.Kind == SymbolKind.Namespace) { result.Add(new ClassifiedSpan(token.Span, ClassificationTypeNames.NamespaceName)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers { internal class UsingDirectiveSyntaxClassifier : AbstractSyntaxClassifier { public override void AddClassifications( Workspace workspace, SyntaxNode syntax, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (syntax is UsingDirectiveSyntax usingDirective) { ClassifyUsingDirectiveSyntax(usingDirective, semanticModel, result, cancellationToken); } } public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create(typeof(UsingDirectiveSyntax)); private static void ClassifyUsingDirectiveSyntax( UsingDirectiveSyntax usingDirective, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { // For using aliases, we bind the target on the right of the equals and use that // binding to classify the alias. if (usingDirective.Alias != null) { var token = usingDirective.Alias.Name; var symbolInfo = semanticModel.GetSymbolInfo(usingDirective.Name, cancellationToken); if (symbolInfo.Symbol is ITypeSymbol typeSymbol) { var classification = GetClassificationForType(typeSymbol); if (classification != null) { result.Add(new ClassifiedSpan(token.Span, classification)); } } else if (symbolInfo.Symbol?.Kind == SymbolKind.Namespace) { result.Add(new ClassifiedSpan(token.Span, ClassificationTypeNames.NamespaceName)); } } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/CodeGen/RawSequencePoint.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Represents a sequence point before translation by #line/ExternalSource directives. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal readonly struct RawSequencePoint { internal readonly SyntaxTree SyntaxTree; internal readonly int ILMarker; internal readonly TextSpan Span; // Special text span indicating a hidden sequence point. internal static readonly TextSpan HiddenSequencePointSpan = new TextSpan(0x7FFFFFFF, 0); internal RawSequencePoint(SyntaxTree syntaxTree, int ilMarker, TextSpan span) { this.SyntaxTree = syntaxTree; this.ILMarker = ilMarker; this.Span = span; } private string GetDebuggerDisplay() { return string.Format("#{0}: {1}", ILMarker, Span == HiddenSequencePointSpan ? "hidden" : Span.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Represents a sequence point before translation by #line/ExternalSource directives. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal readonly struct RawSequencePoint { internal readonly SyntaxTree SyntaxTree; internal readonly int ILMarker; internal readonly TextSpan Span; // Special text span indicating a hidden sequence point. internal static readonly TextSpan HiddenSequencePointSpan = new TextSpan(0x7FFFFFFF, 0); internal RawSequencePoint(SyntaxTree syntaxTree, int ilMarker, TextSpan span) { this.SyntaxTree = syntaxTree; this.ILMarker = ilMarker; this.Span = span; } private string GetDebuggerDisplay() { return string.Format("#{0}: {1}", ILMarker, Span == HiddenSequencePointSpan ? "hidden" : Span.ToString()); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/Implementation/TableDataSource/VisualStudioBaseDiagnosticListTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { internal abstract partial class VisualStudioBaseDiagnosticListTable : AbstractTable { protected VisualStudioBaseDiagnosticListTable(Workspace workspace, ITableManagerProvider provider) : base(workspace, provider, StandardTables.ErrorsTable) { } internal override ImmutableArray<string> Columns { get; } = ImmutableArray.Create( StandardTableColumnDefinitions.ErrorSeverity, StandardTableColumnDefinitions.ErrorCode, StandardTableColumnDefinitions.Text, StandardTableColumnDefinitions.ErrorCategory, StandardTableColumnDefinitions.ProjectName, StandardTableColumnDefinitions.DocumentName, StandardTableColumnDefinitions.Line, StandardTableColumnDefinitions.Column, StandardTableColumnDefinitions.BuildTool, StandardTableColumnDefinitions.ErrorSource, StandardTableColumnDefinitions.DetailsExpander, StandardTableColumnDefinitions.SuppressionState); public static __VSERRORCATEGORY GetErrorCategory(DiagnosticSeverity severity) { // REVIEW: why is it using old interface for new API? return severity switch { DiagnosticSeverity.Error => __VSERRORCATEGORY.EC_ERROR, DiagnosticSeverity.Warning => __VSERRORCATEGORY.EC_WARNING, DiagnosticSeverity.Info => __VSERRORCATEGORY.EC_MESSAGE, _ => throw ExceptionUtilities.UnexpectedValue(severity) }; } protected abstract class DiagnosticTableEntriesSource : AbstractTableEntriesSource<DiagnosticTableItem> { public abstract string BuildTool { get; } public abstract bool SupportSpanTracking { get; } public abstract DocumentId TrackingDocumentId { get; } } protected class AggregatedKey { public readonly ImmutableArray<DocumentId> DocumentIds; public readonly DiagnosticAnalyzer Analyzer; public readonly int Kind; public AggregatedKey(ImmutableArray<DocumentId> documentIds, DiagnosticAnalyzer analyzer, int kind) { DocumentIds = documentIds; Analyzer = analyzer; Kind = kind; } public override bool Equals(object obj) { if (obj is not AggregatedKey other) { return false; } return this.DocumentIds == other.DocumentIds && this.Analyzer == other.Analyzer && this.Kind == other.Kind; } public override int GetHashCode() => Hash.Combine(Analyzer.GetHashCode(), Hash.Combine(DocumentIds.GetHashCode(), Kind)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { internal abstract partial class VisualStudioBaseDiagnosticListTable : AbstractTable { protected VisualStudioBaseDiagnosticListTable(Workspace workspace, ITableManagerProvider provider) : base(workspace, provider, StandardTables.ErrorsTable) { } internal override ImmutableArray<string> Columns { get; } = ImmutableArray.Create( StandardTableColumnDefinitions.ErrorSeverity, StandardTableColumnDefinitions.ErrorCode, StandardTableColumnDefinitions.Text, StandardTableColumnDefinitions.ErrorCategory, StandardTableColumnDefinitions.ProjectName, StandardTableColumnDefinitions.DocumentName, StandardTableColumnDefinitions.Line, StandardTableColumnDefinitions.Column, StandardTableColumnDefinitions.BuildTool, StandardTableColumnDefinitions.ErrorSource, StandardTableColumnDefinitions.DetailsExpander, StandardTableColumnDefinitions.SuppressionState); public static __VSERRORCATEGORY GetErrorCategory(DiagnosticSeverity severity) { // REVIEW: why is it using old interface for new API? return severity switch { DiagnosticSeverity.Error => __VSERRORCATEGORY.EC_ERROR, DiagnosticSeverity.Warning => __VSERRORCATEGORY.EC_WARNING, DiagnosticSeverity.Info => __VSERRORCATEGORY.EC_MESSAGE, _ => throw ExceptionUtilities.UnexpectedValue(severity) }; } protected abstract class DiagnosticTableEntriesSource : AbstractTableEntriesSource<DiagnosticTableItem> { public abstract string BuildTool { get; } public abstract bool SupportSpanTracking { get; } public abstract DocumentId TrackingDocumentId { get; } } protected class AggregatedKey { public readonly ImmutableArray<DocumentId> DocumentIds; public readonly DiagnosticAnalyzer Analyzer; public readonly int Kind; public AggregatedKey(ImmutableArray<DocumentId> documentIds, DiagnosticAnalyzer analyzer, int kind) { DocumentIds = documentIds; Analyzer = analyzer; Kind = kind; } public override bool Equals(object obj) { if (obj is not AggregatedKey other) { return false; } return this.DocumentIds == other.DocumentIds && this.Analyzer == other.Analyzer && this.Kind == other.Kind; } public override int GetHashCode() => Hash.Combine(Analyzer.GetHashCode(), Hash.Combine(DocumentIds.GetHashCode(), Kind)); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ObjectExtensions.TypeSwitch.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ObjectExtensions { public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType where TDerivedType17 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), TDerivedType17 d => matchFunc17(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType where TDerivedType17 : TBaseType where TDerivedType18 : TBaseType where TDerivedType19 : TBaseType where TDerivedType20 : TBaseType where TDerivedType21 : TBaseType where TDerivedType22 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), TDerivedType17 d => matchFunc17(d), TDerivedType18 d => matchFunc18(d), TDerivedType19 d => matchFunc19(d), TDerivedType20 d => matchFunc20(d), TDerivedType21 d => matchFunc21(d), TDerivedType22 d => matchFunc22(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TDerivedType37, TDerivedType38, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TDerivedType37, TResult> matchFunc37, Func<TDerivedType38, TResult> matchFunc38, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType where TDerivedType17 : TBaseType where TDerivedType18 : TBaseType where TDerivedType19 : TBaseType where TDerivedType20 : TBaseType where TDerivedType21 : TBaseType where TDerivedType22 : TBaseType where TDerivedType23 : TBaseType where TDerivedType24 : TBaseType where TDerivedType25 : TBaseType where TDerivedType26 : TBaseType where TDerivedType27 : TBaseType where TDerivedType28 : TBaseType where TDerivedType29 : TBaseType where TDerivedType30 : TBaseType where TDerivedType31 : TBaseType where TDerivedType32 : TBaseType where TDerivedType33 : TBaseType where TDerivedType34 : TBaseType where TDerivedType35 : TBaseType where TDerivedType36 : TBaseType where TDerivedType37 : TBaseType where TDerivedType38 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), TDerivedType17 d => matchFunc17(d), TDerivedType18 d => matchFunc18(d), TDerivedType19 d => matchFunc19(d), TDerivedType20 d => matchFunc20(d), TDerivedType21 d => matchFunc21(d), TDerivedType22 d => matchFunc22(d), TDerivedType23 d => matchFunc23(d), TDerivedType24 d => matchFunc24(d), TDerivedType25 d => matchFunc25(d), TDerivedType26 d => matchFunc26(d), TDerivedType27 d => matchFunc27(d), TDerivedType28 d => matchFunc28(d), TDerivedType29 d => matchFunc29(d), TDerivedType30 d => matchFunc30(d), TDerivedType31 d => matchFunc31(d), TDerivedType32 d => matchFunc32(d), TDerivedType33 d => matchFunc33(d), TDerivedType34 d => matchFunc34(d), TDerivedType35 d => matchFunc35(d), TDerivedType36 d => matchFunc36(d), TDerivedType37 d => matchFunc37(d), TDerivedType38 d => matchFunc38(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TDerivedType37, TDerivedType38, TDerivedType39, TDerivedType40, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TDerivedType37, TResult> matchFunc37, Func<TDerivedType38, TResult> matchFunc38, Func<TDerivedType39, TResult> matchFunc39, Func<TDerivedType40, TResult> matchFunc40, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType where TDerivedType17 : TBaseType where TDerivedType18 : TBaseType where TDerivedType19 : TBaseType where TDerivedType20 : TBaseType where TDerivedType21 : TBaseType where TDerivedType22 : TBaseType where TDerivedType23 : TBaseType where TDerivedType24 : TBaseType where TDerivedType25 : TBaseType where TDerivedType26 : TBaseType where TDerivedType27 : TBaseType where TDerivedType28 : TBaseType where TDerivedType29 : TBaseType where TDerivedType30 : TBaseType where TDerivedType31 : TBaseType where TDerivedType32 : TBaseType where TDerivedType33 : TBaseType where TDerivedType34 : TBaseType where TDerivedType35 : TBaseType where TDerivedType36 : TBaseType where TDerivedType37 : TBaseType where TDerivedType38 : TBaseType where TDerivedType39 : TBaseType where TDerivedType40 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), TDerivedType17 d => matchFunc17(d), TDerivedType18 d => matchFunc18(d), TDerivedType19 d => matchFunc19(d), TDerivedType20 d => matchFunc20(d), TDerivedType21 d => matchFunc21(d), TDerivedType22 d => matchFunc22(d), TDerivedType23 d => matchFunc23(d), TDerivedType24 d => matchFunc24(d), TDerivedType25 d => matchFunc25(d), TDerivedType26 d => matchFunc26(d), TDerivedType27 d => matchFunc27(d), TDerivedType28 d => matchFunc28(d), TDerivedType29 d => matchFunc29(d), TDerivedType30 d => matchFunc30(d), TDerivedType31 d => matchFunc31(d), TDerivedType32 d => matchFunc32(d), TDerivedType33 d => matchFunc33(d), TDerivedType34 d => matchFunc34(d), TDerivedType35 d => matchFunc35(d), TDerivedType36 d => matchFunc36(d), TDerivedType37 d => matchFunc37(d), TDerivedType38 d => matchFunc38(d), TDerivedType39 d => matchFunc39(d), TDerivedType40 d => matchFunc40(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ObjectExtensions { public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType where TDerivedType17 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), TDerivedType17 d => matchFunc17(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType where TDerivedType17 : TBaseType where TDerivedType18 : TBaseType where TDerivedType19 : TBaseType where TDerivedType20 : TBaseType where TDerivedType21 : TBaseType where TDerivedType22 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), TDerivedType17 d => matchFunc17(d), TDerivedType18 d => matchFunc18(d), TDerivedType19 d => matchFunc19(d), TDerivedType20 d => matchFunc20(d), TDerivedType21 d => matchFunc21(d), TDerivedType22 d => matchFunc22(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TDerivedType37, TDerivedType38, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TDerivedType37, TResult> matchFunc37, Func<TDerivedType38, TResult> matchFunc38, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType where TDerivedType17 : TBaseType where TDerivedType18 : TBaseType where TDerivedType19 : TBaseType where TDerivedType20 : TBaseType where TDerivedType21 : TBaseType where TDerivedType22 : TBaseType where TDerivedType23 : TBaseType where TDerivedType24 : TBaseType where TDerivedType25 : TBaseType where TDerivedType26 : TBaseType where TDerivedType27 : TBaseType where TDerivedType28 : TBaseType where TDerivedType29 : TBaseType where TDerivedType30 : TBaseType where TDerivedType31 : TBaseType where TDerivedType32 : TBaseType where TDerivedType33 : TBaseType where TDerivedType34 : TBaseType where TDerivedType35 : TBaseType where TDerivedType36 : TBaseType where TDerivedType37 : TBaseType where TDerivedType38 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), TDerivedType17 d => matchFunc17(d), TDerivedType18 d => matchFunc18(d), TDerivedType19 d => matchFunc19(d), TDerivedType20 d => matchFunc20(d), TDerivedType21 d => matchFunc21(d), TDerivedType22 d => matchFunc22(d), TDerivedType23 d => matchFunc23(d), TDerivedType24 d => matchFunc24(d), TDerivedType25 d => matchFunc25(d), TDerivedType26 d => matchFunc26(d), TDerivedType27 d => matchFunc27(d), TDerivedType28 d => matchFunc28(d), TDerivedType29 d => matchFunc29(d), TDerivedType30 d => matchFunc30(d), TDerivedType31 d => matchFunc31(d), TDerivedType32 d => matchFunc32(d), TDerivedType33 d => matchFunc33(d), TDerivedType34 d => matchFunc34(d), TDerivedType35 d => matchFunc35(d), TDerivedType36 d => matchFunc36(d), TDerivedType37 d => matchFunc37(d), TDerivedType38 d => matchFunc38(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } public static TResult? TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TDerivedType37, TDerivedType38, TDerivedType39, TDerivedType40, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TDerivedType37, TResult> matchFunc37, Func<TDerivedType38, TResult> matchFunc38, Func<TDerivedType39, TResult> matchFunc39, Func<TDerivedType40, TResult> matchFunc40, Func<TBaseType, TResult>? defaultFunc = null) where TDerivedType1 : TBaseType where TDerivedType2 : TBaseType where TDerivedType3 : TBaseType where TDerivedType4 : TBaseType where TDerivedType5 : TBaseType where TDerivedType6 : TBaseType where TDerivedType7 : TBaseType where TDerivedType8 : TBaseType where TDerivedType9 : TBaseType where TDerivedType10 : TBaseType where TDerivedType11 : TBaseType where TDerivedType12 : TBaseType where TDerivedType13 : TBaseType where TDerivedType14 : TBaseType where TDerivedType15 : TBaseType where TDerivedType16 : TBaseType where TDerivedType17 : TBaseType where TDerivedType18 : TBaseType where TDerivedType19 : TBaseType where TDerivedType20 : TBaseType where TDerivedType21 : TBaseType where TDerivedType22 : TBaseType where TDerivedType23 : TBaseType where TDerivedType24 : TBaseType where TDerivedType25 : TBaseType where TDerivedType26 : TBaseType where TDerivedType27 : TBaseType where TDerivedType28 : TBaseType where TDerivedType29 : TBaseType where TDerivedType30 : TBaseType where TDerivedType31 : TBaseType where TDerivedType32 : TBaseType where TDerivedType33 : TBaseType where TDerivedType34 : TBaseType where TDerivedType35 : TBaseType where TDerivedType36 : TBaseType where TDerivedType37 : TBaseType where TDerivedType38 : TBaseType where TDerivedType39 : TBaseType where TDerivedType40 : TBaseType { return obj switch { TDerivedType1 d => matchFunc1(d), TDerivedType2 d => matchFunc2(d), TDerivedType3 d => matchFunc3(d), TDerivedType4 d => matchFunc4(d), TDerivedType5 d => matchFunc5(d), TDerivedType6 d => matchFunc6(d), TDerivedType7 d => matchFunc7(d), TDerivedType8 d => matchFunc8(d), TDerivedType9 d => matchFunc9(d), TDerivedType10 d => matchFunc10(d), TDerivedType11 d => matchFunc11(d), TDerivedType12 d => matchFunc12(d), TDerivedType13 d => matchFunc13(d), TDerivedType14 d => matchFunc14(d), TDerivedType15 d => matchFunc15(d), TDerivedType16 d => matchFunc16(d), TDerivedType17 d => matchFunc17(d), TDerivedType18 d => matchFunc18(d), TDerivedType19 d => matchFunc19(d), TDerivedType20 d => matchFunc20(d), TDerivedType21 d => matchFunc21(d), TDerivedType22 d => matchFunc22(d), TDerivedType23 d => matchFunc23(d), TDerivedType24 d => matchFunc24(d), TDerivedType25 d => matchFunc25(d), TDerivedType26 d => matchFunc26(d), TDerivedType27 d => matchFunc27(d), TDerivedType28 d => matchFunc28(d), TDerivedType29 d => matchFunc29(d), TDerivedType30 d => matchFunc30(d), TDerivedType31 d => matchFunc31(d), TDerivedType32 d => matchFunc32(d), TDerivedType33 d => matchFunc33(d), TDerivedType34 d => matchFunc34(d), TDerivedType35 d => matchFunc35(d), TDerivedType36 d => matchFunc36(d), TDerivedType37 d => matchFunc37(d), TDerivedType38 d => matchFunc38(d), TDerivedType39 d => matchFunc39(d), TDerivedType40 d => matchFunc40(d), _ => defaultFunc == null ? default : defaultFunc.Invoke(obj), }; } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed class VisualStudioProject { private static readonly ImmutableArray<MetadataReferenceProperties> s_defaultMetadataReferenceProperties = ImmutableArray.Create(default(MetadataReferenceProperties)); private readonly VisualStudioWorkspaceImpl _workspace; private readonly HostDiagnosticUpdateSource _hostDiagnosticUpdateSource; private readonly IWorkspaceTelemetryService? _telemetryService; private readonly IWorkspaceStatusService? _workspaceStatusService; /// <summary> /// Provides dynamic source files for files added through <see cref="AddDynamicSourceFile" />. /// </summary> private readonly ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> _dynamicFileInfoProviders; /// <summary> /// A gate taken for all mutation of any mutable field in this type. /// </summary> /// <remarks>This is, for now, intentionally pessimistic. There are no doubt ways that we could allow more to run in parallel, /// but the current tradeoff is for simplicity of code and "obvious correctness" than something that is subtle, fast, and wrong.</remarks> private readonly object _gate = new(); /// <summary> /// The number of active batch scopes. If this is zero, we are not batching, non-zero means we are batching. /// </summary> private int _activeBatchScopes = 0; private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesAddedInBatch = new(); private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesRemovedInBatch = new(); private readonly List<ProjectReference> _projectReferencesAddedInBatch = new(); private readonly List<ProjectReference> _projectReferencesRemovedInBatch = new(); private readonly Dictionary<string, VisualStudioAnalyzer> _analyzerPathsToAnalyzers = new(); private readonly List<VisualStudioAnalyzer> _analyzersAddedInBatch = new(); private readonly List<VisualStudioAnalyzer> _analyzersRemovedInBatch = new(); private readonly List<Func<Solution, Solution>> _projectPropertyModificationsInBatch = new(); private string _assemblyName; private string _displayName; private string? _filePath; private CompilationOptions? _compilationOptions; private ParseOptions? _parseOptions; private bool _hasAllInformation = true; private string? _compilationOutputAssemblyFilePath; private string? _outputFilePath; private string? _outputRefFilePath; private string? _defaultNamespace; /// <summary> /// If this project is the 'primary' project the project system cares about for a group of Roslyn projects that /// correspond to different configurations of a single project system project. <see langword="true"/> by /// default. /// </summary> internal bool IsPrimary { get; set; } = true; // Actual property values for 'RunAnalyzers' and 'RunAnalyzersDuringLiveAnalysis' properties from the project file. // Both these properties can be used to configure running analyzers, with RunAnalyzers overriding RunAnalyzersDuringLiveAnalysis. private bool? _runAnalyzersPropertyValue; private bool? _runAnalyzersDuringLiveAnalysisPropertyValue; // Effective boolean value to determine if analyzers should be executed based on _runAnalyzersPropertyValue and _runAnalyzersDuringLiveAnalysisPropertyValue. private bool _runAnalyzers = true; /// <summary> /// The full list of all metadata references this project has. References that have internally been converted to project references /// will still be in this. /// </summary> private readonly Dictionary<string, ImmutableArray<MetadataReferenceProperties>> _allMetadataReferences = new(); /// <summary> /// The file watching tokens for the documents in this project. We get the tokens even when we're in a batch, so the files here /// may not be in the actual workspace yet. /// </summary> private readonly Dictionary<DocumentId, FileChangeWatcher.IFileWatchingToken> _documentFileWatchingTokens = new(); /// <summary> /// A file change context used to watch source files, additional files, and analyzer config files for this project. It's automatically set to watch the user's project /// directory so we avoid file-by-file watching. /// </summary> private readonly FileChangeWatcher.IContext _documentFileChangeContext; /// <summary> /// track whether we have been subscribed to <see cref="IDynamicFileInfoProvider.Updated"/> event /// </summary> private readonly HashSet<IDynamicFileInfoProvider> _eventSubscriptionTracker = new(); /// <summary> /// Map of the original dynamic file path to the <see cref="DynamicFileInfo.FilePath"/> that was associated with it. /// /// For example, the key is something like Page.cshtml which is given to us from the project system calling /// <see cref="AddDynamicSourceFile(string, ImmutableArray{string})"/>. The value of the map is a generated file that /// corresponds to the original path, say Page.g.cs. If we were given a file by the project system but no /// <see cref="IDynamicFileInfoProvider"/> provided a file for it, we will record the value as null so we still can track /// the addition of the .cshtml file for a later call to <see cref="RemoveDynamicSourceFile(string)"/>. /// /// The workspace snapshot will only have a document with <see cref="DynamicFileInfo.FilePath"/> (the value) but not the /// original dynamic file path (the key). /// </summary> /// <remarks> /// We use the same string comparer as in the <see cref="BatchingDocumentCollection"/> used by _sourceFiles, below, as these /// files are added to that collection too. /// </remarks> private readonly Dictionary<string, string?> _dynamicFilePathMaps = new(StringComparer.OrdinalIgnoreCase); private readonly BatchingDocumentCollection _sourceFiles; private readonly BatchingDocumentCollection _additionalFiles; private readonly BatchingDocumentCollection _analyzerConfigFiles; public ProjectId Id { get; } public string Language { get; } internal VisualStudioProject( VisualStudioWorkspaceImpl workspace, ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> dynamicFileInfoProviders, HostDiagnosticUpdateSource hostDiagnosticUpdateSource, ProjectId id, string displayName, string language, string assemblyName, CompilationOptions? compilationOptions, string? filePath, ParseOptions? parseOptions) { _workspace = workspace; _dynamicFileInfoProviders = dynamicFileInfoProviders; _hostDiagnosticUpdateSource = hostDiagnosticUpdateSource; _telemetryService = _workspace.Services.GetService<IWorkspaceTelemetryService>(); _workspaceStatusService = _workspace.Services.GetService<IWorkspaceStatusService>(); Id = id; Language = language; _displayName = displayName; _sourceFiles = new BatchingDocumentCollection( this, documentAlreadyInWorkspace: (s, d) => s.ContainsDocument(d), documentAddAction: (w, d) => w.OnDocumentAdded(d), documentRemoveAction: (w, documentId) => w.OnDocumentRemoved(documentId), documentTextLoaderChangedAction: (w, d, loader) => w.OnDocumentTextLoaderChanged(d, loader)); _additionalFiles = new BatchingDocumentCollection(this, (s, d) => s.ContainsAdditionalDocument(d), (w, d) => w.OnAdditionalDocumentAdded(d), (w, documentId) => w.OnAdditionalDocumentRemoved(documentId), documentTextLoaderChangedAction: (w, d, loader) => w.OnAdditionalDocumentTextLoaderChanged(d, loader)); _analyzerConfigFiles = new BatchingDocumentCollection(this, (s, d) => s.ContainsAnalyzerConfigDocument(d), (w, d) => w.OnAnalyzerConfigDocumentAdded(d), (w, documentId) => w.OnAnalyzerConfigDocumentRemoved(documentId), documentTextLoaderChangedAction: (w, d, loader) => w.OnAnalyzerConfigDocumentTextLoaderChanged(d, loader)); _assemblyName = assemblyName; _compilationOptions = compilationOptions; _filePath = filePath; _parseOptions = parseOptions; var fileExtensionToWatch = language switch { LanguageNames.CSharp => ".cs", LanguageNames.VisualBasic => ".vb", _ => null }; if (filePath != null && fileExtensionToWatch != null) { // Since we have a project directory, we'll just watch all the files under that path; that'll avoid extra overhead of // having to add explicit file watches everywhere. var projectDirectoryToWatch = new FileChangeWatcher.WatchedDirectory(Path.GetDirectoryName(filePath), fileExtensionToWatch); _documentFileChangeContext = _workspace.FileChangeWatcher.CreateContext(projectDirectoryToWatch); } else { _documentFileChangeContext = workspace.FileChangeWatcher.CreateContext(); } _documentFileChangeContext.FileChanged += DocumentFileChangeContext_FileChanged; } private void ChangeProjectProperty<T>(ref T field, T newValue, Func<Solution, Solution> withNewValue, bool logThrowAwayTelemetry = false) { lock (_gate) { // If nothing is changing, we can skip entirely if (object.Equals(field, newValue)) { return; } field = newValue; // Importantly, we do not await/wait on the fullyLoadedStateTask. We do not want to ever be waiting on work // that may end up touching the UI thread (As we can deadlock if GetTagsSynchronous waits on us). Instead, // we only check if the Task is completed. Prior to that we will assume we are still loading. Once this // task is completed, we know that the WaitUntilFullyLoadedAsync call will have actually finished and we're // fully loaded. var isFullyLoadedTask = _workspaceStatusService?.IsFullyLoadedAsync(CancellationToken.None); var isFullyLoaded = isFullyLoadedTask is { IsCompleted: true } && isFullyLoadedTask.GetAwaiter().GetResult(); // We only log telemetry during solution open if (logThrowAwayTelemetry && _telemetryService?.HasActiveSession == true && !isFullyLoaded) { TryReportCompilationThrownAway(_workspace.CurrentSolution.State, Id); } if (_activeBatchScopes > 0) { _projectPropertyModificationsInBatch.Add(withNewValue); } else { _workspace.ApplyChangeToWorkspace(Id, withNewValue); } } } /// <summary> /// Reports a telemetry event if compilation information is being thrown away after being previously computed /// </summary> private static void TryReportCompilationThrownAway(SolutionState solutionState, ProjectId projectId) { // We log the number of syntax trees that have been parsed even if there was no compilation created yet var projectState = solutionState.GetRequiredProjectState(projectId); var parsedTrees = 0; foreach (var (_, documentState) in projectState.DocumentStates.States) { if (documentState.TryGetSyntaxTree(out _)) { parsedTrees++; } } // But we also want to know if a compilation was created var hadCompilation = solutionState.TryGetCompilation(projectId, out _); if (parsedTrees > 0 || hadCompilation) { Logger.Log(FunctionId.Workspace_Project_CompilationThrownAway, KeyValueLogMessage.Create(m => { // Note: Not using our project Id. This is the same ProjectGuid that the project system uses // so data can be correlated m["ProjectGuid"] = projectState.ProjectInfo.Attributes.TelemetryId.ToString("B"); m["SyntaxTreesParsed"] = parsedTrees; m["HadCompilation"] = hadCompilation; })); } } private void ChangeProjectOutputPath(ref string? field, string? newValue, Func<Solution, Solution> withNewValue) { lock (_gate) { // Skip if nothing changing if (field == newValue) { return; } if (field != null) { _workspace.RemoveProjectOutputPath(Id, field); } if (newValue != null) { _workspace.AddProjectOutputPath(Id, newValue); } ChangeProjectProperty(ref field, newValue, withNewValue); } } public string AssemblyName { get => _assemblyName; set => ChangeProjectProperty(ref _assemblyName, value, s => s.WithProjectAssemblyName(Id, value), logThrowAwayTelemetry: true); } // The property could be null if this is a non-C#/VB language and we don't have one for it. But we disallow assigning null, because C#/VB cannot end up null // again once they already had one. [DisallowNull] public CompilationOptions? CompilationOptions { get => _compilationOptions; set => ChangeProjectProperty(ref _compilationOptions, value, s => s.WithProjectCompilationOptions(Id, value), logThrowAwayTelemetry: true); } // The property could be null if this is a non-C#/VB language and we don't have one for it. But we disallow assigning null, because C#/VB cannot end up null // again once they already had one. [DisallowNull] public ParseOptions? ParseOptions { get => _parseOptions; set => ChangeProjectProperty(ref _parseOptions, value, s => s.WithProjectParseOptions(Id, value), logThrowAwayTelemetry: true); } /// <summary> /// The path to the output in obj. /// </summary> internal string? CompilationOutputAssemblyFilePath { get => _compilationOutputAssemblyFilePath; set => ChangeProjectOutputPath( ref _compilationOutputAssemblyFilePath, value, s => s.WithProjectCompilationOutputInfo(Id, s.GetRequiredProject(Id).CompilationOutputInfo.WithAssemblyPath(value))); } public string? OutputFilePath { get => _outputFilePath; set => ChangeProjectOutputPath(ref _outputFilePath, value, s => s.WithProjectOutputFilePath(Id, value)); } public string? OutputRefFilePath { get => _outputRefFilePath; set => ChangeProjectOutputPath(ref _outputRefFilePath, value, s => s.WithProjectOutputRefFilePath(Id, value)); } public string? FilePath { get => _filePath; set => ChangeProjectProperty(ref _filePath, value, s => s.WithProjectFilePath(Id, value)); } public string DisplayName { get => _displayName; set => ChangeProjectProperty(ref _displayName, value, s => s.WithProjectName(Id, value)); } // internal to match the visibility of the Workspace-level API -- this is something // we use but we haven't made officially public yet. internal bool HasAllInformation { get => _hasAllInformation; set => ChangeProjectProperty(ref _hasAllInformation, value, s => s.WithHasAllInformation(Id, value)); } internal bool? RunAnalyzers { get => _runAnalyzersPropertyValue; set { _runAnalyzersPropertyValue = value; UpdateRunAnalyzers(); } } internal bool? RunAnalyzersDuringLiveAnalysis { get => _runAnalyzersDuringLiveAnalysisPropertyValue; set { _runAnalyzersDuringLiveAnalysisPropertyValue = value; UpdateRunAnalyzers(); } } private void UpdateRunAnalyzers() { // Property RunAnalyzers overrides RunAnalyzersDuringLiveAnalysis, and default when both properties are not set is 'true'. var runAnalyzers = _runAnalyzersPropertyValue ?? _runAnalyzersDuringLiveAnalysisPropertyValue ?? true; ChangeProjectProperty(ref _runAnalyzers, runAnalyzers, s => s.WithRunAnalyzers(Id, runAnalyzers)); } /// <summary> /// The default namespace of the project. /// </summary> /// <remarks> /// In C#, this is defined as the value of "rootnamespace" msbuild property. Right now VB doesn't /// have the concept of "default namespace", but we conjure one in workspace by assigning the value /// of the project's root namespace to it. So various features can choose to use it for their own purpose. /// /// In the future, we might consider officially exposing "default namespace" for VB project /// (e.g.through a "defaultnamespace" msbuild property) /// </remarks> internal string? DefaultNamespace { get => _defaultNamespace; set => ChangeProjectProperty(ref _defaultNamespace, value, s => s.WithProjectDefaultNamespace(Id, value)); } /// <summary> /// The max language version supported for this project, if applicable. Useful to help indicate what /// language version features should be suggested to a user, as well as if they can be upgraded. /// </summary> internal string? MaxLangVersion { set => _workspace.SetMaxLanguageVersion(Id, value); } internal string DependencyNodeTargetIdentifier { set => _workspace.SetDependencyNodeTargetIdentifier(Id, value); } #region Batching public BatchScope CreateBatchScope() { lock (_gate) { _activeBatchScopes++; return new BatchScope(this); } } public sealed class BatchScope : IDisposable { private readonly VisualStudioProject _project; /// <summary> /// Flag to control if this has already been disposed. Not a boolean only so it can be used with Interlocked.CompareExchange. /// </summary> private volatile int _disposed = 0; internal BatchScope(VisualStudioProject visualStudioProject) => _project = visualStudioProject; public void Dispose() { if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0) { _project.OnBatchScopeDisposed(); } } } private void OnBatchScopeDisposed() { lock (_gate) { _activeBatchScopes--; if (_activeBatchScopes > 0) { return; } var documentFileNamesAdded = ImmutableArray.CreateBuilder<string>(); var documentsToOpen = new List<(DocumentId documentId, SourceTextContainer textContainer)>(); var additionalDocumentsToOpen = new List<(DocumentId documentId, SourceTextContainer textContainer)>(); var analyzerConfigDocumentsToOpen = new List<(DocumentId documentId, SourceTextContainer textContainer)>(); _workspace.ApplyBatchChangeToWorkspace(solution => { var solutionChanges = new SolutionChangeAccumulator(startingSolution: solution); _sourceFiles.UpdateSolutionForBatch( solutionChanges, documentFileNamesAdded, documentsToOpen, (s, documents) => s.AddDocuments(documents), WorkspaceChangeKind.DocumentAdded, (s, ids) => s.RemoveDocuments(ids), WorkspaceChangeKind.DocumentRemoved); _additionalFiles.UpdateSolutionForBatch( solutionChanges, documentFileNamesAdded, additionalDocumentsToOpen, (s, documents) => { foreach (var document in documents) { s = s.AddAdditionalDocument(document); } return s; }, WorkspaceChangeKind.AdditionalDocumentAdded, (s, ids) => s.RemoveAdditionalDocuments(ids), WorkspaceChangeKind.AdditionalDocumentRemoved); _analyzerConfigFiles.UpdateSolutionForBatch( solutionChanges, documentFileNamesAdded, analyzerConfigDocumentsToOpen, (s, documents) => s.AddAnalyzerConfigDocuments(documents), WorkspaceChangeKind.AnalyzerConfigDocumentAdded, (s, ids) => s.RemoveAnalyzerConfigDocuments(ids), WorkspaceChangeKind.AnalyzerConfigDocumentRemoved); // Metadata reference removing. Do this before adding in case this removes a project reference that // we are also going to add in the same batch. This could happen if case is changing, or we're targeting // a different output path (say bin vs. obj vs. ref). foreach (var (path, properties) in _metadataReferencesRemovedInBatch) { var projectReference = _workspace.TryRemoveConvertedProjectReference_NoLock(Id, path, properties); if (projectReference != null) { solutionChanges.UpdateSolutionForProjectAction( Id, solutionChanges.Solution.RemoveProjectReference(Id, projectReference)); } else { // TODO: find a cleaner way to fetch this var metadataReference = _workspace.CurrentSolution.GetRequiredProject(Id).MetadataReferences.Cast<PortableExecutableReference>() .Single(m => m.FilePath == path && m.Properties == properties); _workspace.FileWatchedReferenceFactory.StopWatchingReference(metadataReference); solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.RemoveMetadataReference(Id, metadataReference)); } } ClearAndZeroCapacity(_metadataReferencesRemovedInBatch); // Metadata reference adding... if (_metadataReferencesAddedInBatch.Count > 0) { var projectReferencesCreated = new List<ProjectReference>(); var metadataReferencesCreated = new List<MetadataReference>(); foreach (var (path, properties) in _metadataReferencesAddedInBatch) { var projectReference = _workspace.TryCreateConvertedProjectReference_NoLock(Id, path, properties); if (projectReference != null) { projectReferencesCreated.Add(projectReference); } else { var metadataReference = _workspace.FileWatchedReferenceFactory.CreateReferenceAndStartWatchingFile(path, properties); metadataReferencesCreated.Add(metadataReference); } } solutionChanges.UpdateSolutionForProjectAction( Id, solutionChanges.Solution.AddProjectReferences(Id, projectReferencesCreated) .AddMetadataReferences(Id, metadataReferencesCreated)); ClearAndZeroCapacity(_metadataReferencesAddedInBatch); } // Project reference adding... solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.AddProjectReferences(Id, _projectReferencesAddedInBatch)); ClearAndZeroCapacity(_projectReferencesAddedInBatch); // Project reference removing... foreach (var projectReference in _projectReferencesRemovedInBatch) { solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.RemoveProjectReference(Id, projectReference)); } ClearAndZeroCapacity(_projectReferencesRemovedInBatch); // Analyzer reference adding... solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.AddAnalyzerReferences(Id, _analyzersAddedInBatch.Select(a => a.GetReference()))); ClearAndZeroCapacity(_analyzersAddedInBatch); // Analyzer reference removing... foreach (var analyzerReference in _analyzersRemovedInBatch) { solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.RemoveAnalyzerReference(Id, analyzerReference.GetReference())); } ClearAndZeroCapacity(_analyzersRemovedInBatch); // Other property modifications... foreach (var propertyModification in _projectPropertyModificationsInBatch) { solutionChanges.UpdateSolutionForProjectAction( Id, propertyModification(solutionChanges.Solution)); } ClearAndZeroCapacity(_projectPropertyModificationsInBatch); return solutionChanges; }); foreach (var (documentId, textContainer) in documentsToOpen) { _workspace.ApplyChangeToWorkspace(w => w.OnDocumentOpened(documentId, textContainer)); } foreach (var (documentId, textContainer) in additionalDocumentsToOpen) { _workspace.ApplyChangeToWorkspace(w => w.OnAdditionalDocumentOpened(documentId, textContainer)); } foreach (var (documentId, textContainer) in analyzerConfigDocumentsToOpen) { _workspace.ApplyChangeToWorkspace(w => w.OnAnalyzerConfigDocumentOpened(documentId, textContainer)); } // Check for those files being opened to start wire-up if necessary _workspace.QueueCheckForFilesBeingOpen(documentFileNamesAdded.ToImmutable()); } } #endregion #region Source File Addition/Removal public void AddSourceFile(string fullPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, ImmutableArray<string> folders = default) => _sourceFiles.AddFile(fullPath, sourceCodeKind, folders); /// <summary> /// Adds a source file to the project from a text container (eg, a Visual Studio Text buffer) /// </summary> /// <param name="textContainer">The text container that contains this file.</param> /// <param name="fullPath">The file path of the document.</param> /// <param name="sourceCodeKind">The kind of the source code.</param> /// <param name="folders">The names of the logical nested folders the document is contained in.</param> /// <param name="designTimeOnly">Whether the document is used only for design time (eg. completion) or also included in a compilation.</param> /// <param name="documentServiceProvider">A <see cref="IDocumentServiceProvider"/> associated with this document</param> public DocumentId AddSourceTextContainer( SourceTextContainer textContainer, string fullPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, ImmutableArray<string> folders = default, bool designTimeOnly = false, IDocumentServiceProvider? documentServiceProvider = null) { return _sourceFiles.AddTextContainer(textContainer, fullPath, sourceCodeKind, folders, designTimeOnly, documentServiceProvider); } public bool ContainsSourceFile(string fullPath) => _sourceFiles.ContainsFile(fullPath); public void RemoveSourceFile(string fullPath) => _sourceFiles.RemoveFile(fullPath); public void RemoveSourceTextContainer(SourceTextContainer textContainer) => _sourceFiles.RemoveTextContainer(textContainer); #endregion #region Additional File Addition/Removal // TODO: should AdditionalFiles have source code kinds? public void AddAdditionalFile(string fullPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular) => _additionalFiles.AddFile(fullPath, sourceCodeKind, folders: default); public bool ContainsAdditionalFile(string fullPath) => _additionalFiles.ContainsFile(fullPath); public void RemoveAdditionalFile(string fullPath) => _additionalFiles.RemoveFile(fullPath); #endregion #region Analyzer Config File Addition/Removal public void AddAnalyzerConfigFile(string fullPath) { // TODO: do we need folders for analyzer config files? _analyzerConfigFiles.AddFile(fullPath, SourceCodeKind.Regular, folders: default); } public bool ContainsAnalyzerConfigFile(string fullPath) => _analyzerConfigFiles.ContainsFile(fullPath); public void RemoveAnalyzerConfigFile(string fullPath) => _analyzerConfigFiles.RemoveFile(fullPath); #endregion #region Non Source File Addition/Removal public void AddDynamicSourceFile(string dynamicFilePath, ImmutableArray<string> folders) { DynamicFileInfo? fileInfo = null; IDynamicFileInfoProvider? providerForFileInfo = null; var extension = FileNameUtilities.GetExtension(dynamicFilePath)?.TrimStart('.'); if (extension?.Length == 0) { fileInfo = null; } else { foreach (var provider in _dynamicFileInfoProviders) { // skip unrelated providers if (!provider.Metadata.Extensions.Any(e => string.Equals(e, extension, StringComparison.OrdinalIgnoreCase))) { continue; } // Don't get confused by _filePath and filePath. // VisualStudioProject._filePath points to csproj/vbproj of the project // and the parameter filePath points to dynamic file such as ASP.NET .g.cs files. // // Also, provider is free-threaded. so fine to call Wait rather than JTF. fileInfo = provider.Value.GetDynamicFileInfoAsync( projectId: Id, projectFilePath: _filePath, filePath: dynamicFilePath, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); if (fileInfo != null) { fileInfo = FixUpDynamicFileInfo(fileInfo, dynamicFilePath); providerForFileInfo = provider.Value; break; } } } lock (_gate) { if (_dynamicFilePathMaps.ContainsKey(dynamicFilePath)) { // TODO: if we have a duplicate, we are not calling RemoveDynamicFileInfoAsync since we // don't want to call with that under a lock. If we are getting duplicates we have bigger problems // at that point since our workspace is generally out of sync with the project system. // Given we're taking this as a late fix prior to a release, I don't think it's worth the added // risk to handle a case that wasn't handled before either. throw new ArgumentException($"{dynamicFilePath} has already been added to this project."); } // Record the mapping from the dynamic file path to the source file it generated. We will record // 'null' if no provider was able to produce a source file for this input file. That could happen // if the provider (say ASP.NET Razor) doesn't recognize the file, or the wrong type of file // got passed through the system. That's not a failure from the project system's perspective: // adding dynamic files is a hint at best that doesn't impact it. _dynamicFilePathMaps.Add(dynamicFilePath, fileInfo?.FilePath); if (fileInfo != null) { // If fileInfo is not null, that means we found a provider so this should be not-null as well // since we had to go through the earlier assignment. Contract.ThrowIfNull(providerForFileInfo); _sourceFiles.AddDynamicFile(providerForFileInfo, fileInfo, folders); } } } private static DynamicFileInfo FixUpDynamicFileInfo(DynamicFileInfo fileInfo, string filePath) { // we might change contract and just throw here. but for now, we keep existing contract where one can return null for DynamicFileInfo.FilePath. // In this case we substitute the file being generated from so we still have some path. if (string.IsNullOrEmpty(fileInfo.FilePath)) { return new DynamicFileInfo(filePath, fileInfo.SourceCodeKind, fileInfo.TextLoader, fileInfo.DesignTimeOnly, fileInfo.DocumentServiceProvider); } return fileInfo; } public void RemoveDynamicSourceFile(string dynamicFilePath) { IDynamicFileInfoProvider provider; lock (_gate) { if (!_dynamicFilePathMaps.TryGetValue(dynamicFilePath, out var sourceFilePath)) { throw new ArgumentException($"{dynamicFilePath} wasn't added by a previous call to {nameof(AddDynamicSourceFile)}"); } _dynamicFilePathMaps.Remove(dynamicFilePath); // If we got a null path back, it means we never had a source file to add. In that case, // we're done if (sourceFilePath == null) { return; } provider = _sourceFiles.RemoveDynamicFile(sourceFilePath); } // provider is free-threaded. so fine to call Wait rather than JTF provider.RemoveDynamicFileInfoAsync( projectId: Id, projectFilePath: _filePath, filePath: dynamicFilePath, CancellationToken.None).Wait(CancellationToken.None); } private void OnDynamicFileInfoUpdated(object sender, string dynamicFilePath) { string? fileInfoPath; lock (_gate) { if (!_dynamicFilePathMaps.TryGetValue(dynamicFilePath, out fileInfoPath)) { // given file doesn't belong to this project. // this happen since the event this is handling is shared between all projects return; } } if (fileInfoPath != null) { _sourceFiles.ProcessFileChange(dynamicFilePath, fileInfoPath); } } #endregion #region Analyzer Addition/Removal public void AddAnalyzerReference(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); var visualStudioAnalyzer = new VisualStudioAnalyzer( fullPath, _hostDiagnosticUpdateSource, Id, Language); lock (_gate) { if (_analyzerPathsToAnalyzers.ContainsKey(fullPath)) { throw new ArgumentException($"'{fullPath}' has already been added to this project.", nameof(fullPath)); } _analyzerPathsToAnalyzers.Add(fullPath, visualStudioAnalyzer); if (_activeBatchScopes > 0) { _analyzersAddedInBatch.Add(visualStudioAnalyzer); } else { _workspace.ApplyChangeToWorkspace(w => w.OnAnalyzerReferenceAdded(Id, visualStudioAnalyzer.GetReference())); } } } public void RemoveAnalyzerReference(string fullPath) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException("message", nameof(fullPath)); } lock (_gate) { if (!_analyzerPathsToAnalyzers.TryGetValue(fullPath, out var visualStudioAnalyzer)) { throw new ArgumentException($"'{fullPath}' is not an analyzer of this project.", nameof(fullPath)); } _analyzerPathsToAnalyzers.Remove(fullPath); if (_activeBatchScopes > 0) { _analyzersRemovedInBatch.Add(visualStudioAnalyzer); } else { _workspace.ApplyChangeToWorkspace(w => w.OnAnalyzerReferenceRemoved(Id, visualStudioAnalyzer.GetReference())); } } } #endregion private void DocumentFileChangeContext_FileChanged(object sender, string fullFilePath) { _sourceFiles.ProcessFileChange(fullFilePath); _additionalFiles.ProcessFileChange(fullFilePath); _analyzerConfigFiles.ProcessFileChange(fullFilePath); } #region Metadata Reference Addition/Removal public void AddMetadataReference(string fullPath, MetadataReferenceProperties properties) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_gate) { if (ContainsMetadataReference(fullPath, properties)) { throw new InvalidOperationException("The metadata reference has already been added to the project."); } _allMetadataReferences.MultiAdd(fullPath, properties, s_defaultMetadataReferenceProperties); if (_activeBatchScopes > 0) { if (!_metadataReferencesRemovedInBatch.Remove((fullPath, properties))) { _metadataReferencesAddedInBatch.Add((fullPath, properties)); } } else { _workspace.ApplyChangeToWorkspace(w => { var projectReference = _workspace.TryCreateConvertedProjectReference_NoLock(Id, fullPath, properties); if (projectReference != null) { w.OnProjectReferenceAdded(Id, projectReference); } else { var metadataReference = _workspace.FileWatchedReferenceFactory.CreateReferenceAndStartWatchingFile(fullPath, properties); w.OnMetadataReferenceAdded(Id, metadataReference); } }); } } } public bool ContainsMetadataReference(string fullPath, MetadataReferenceProperties properties) { lock (_gate) { return GetPropertiesForMetadataReference(fullPath).Contains(properties); } } /// <summary> /// Returns the properties being used for the current metadata reference added to this project. May return multiple properties if /// the reference has been added multiple times with different properties. /// </summary> public ImmutableArray<MetadataReferenceProperties> GetPropertiesForMetadataReference(string fullPath) { lock (_gate) { return _allMetadataReferences.TryGetValue(fullPath, out var list) ? list : ImmutableArray<MetadataReferenceProperties>.Empty; } } public void RemoveMetadataReference(string fullPath, MetadataReferenceProperties properties) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_gate) { if (!ContainsMetadataReference(fullPath, properties)) { throw new InvalidOperationException("The metadata reference does not exist in this project."); } _allMetadataReferences.MultiRemove(fullPath, properties); if (_activeBatchScopes > 0) { if (!_metadataReferencesAddedInBatch.Remove((fullPath, properties))) { _metadataReferencesRemovedInBatch.Add((fullPath, properties)); } } else { _workspace.ApplyChangeToWorkspace(w => { var projectReference = _workspace.TryRemoveConvertedProjectReference_NoLock(Id, fullPath, properties); // If this was converted to a project reference, we have now recorded the removal -- let's remove it here too if (projectReference != null) { w.OnProjectReferenceRemoved(Id, projectReference); } else { // TODO: find a cleaner way to fetch this var metadataReference = w.CurrentSolution.GetRequiredProject(Id).MetadataReferences.Cast<PortableExecutableReference>() .Single(m => m.FilePath == fullPath && m.Properties == properties); _workspace.FileWatchedReferenceFactory.StopWatchingReference(metadataReference); w.OnMetadataReferenceRemoved(Id, metadataReference); } }); } } } #endregion #region Project Reference Addition/Removal public void AddProjectReference(ProjectReference projectReference) { if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } lock (_gate) { if (ContainsProjectReference(projectReference)) { throw new ArgumentException("The project reference has already been added to the project."); } if (_activeBatchScopes > 0) { if (!_projectReferencesRemovedInBatch.Remove(projectReference)) { _projectReferencesAddedInBatch.Add(projectReference); } } else { _workspace.ApplyChangeToWorkspace(w => w.OnProjectReferenceAdded(Id, projectReference)); } } } public bool ContainsProjectReference(ProjectReference projectReference) { if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } lock (_gate) { if (_projectReferencesRemovedInBatch.Contains(projectReference)) { return false; } if (_projectReferencesAddedInBatch.Contains(projectReference)) { return true; } return _workspace.CurrentSolution.GetRequiredProject(Id).AllProjectReferences.Contains(projectReference); } } public IReadOnlyList<ProjectReference> GetProjectReferences() { lock (_gate) { // If we're not batching, then this is cheap: just fetch from the workspace and we're done var projectReferencesInWorkspace = _workspace.CurrentSolution.GetRequiredProject(Id).AllProjectReferences; if (_activeBatchScopes == 0) { return projectReferencesInWorkspace; } // Not, so we get to compute a new list instead var newList = projectReferencesInWorkspace.ToList(); newList.AddRange(_projectReferencesAddedInBatch); newList.RemoveAll(p => _projectReferencesRemovedInBatch.Contains(p)); return newList; } } public void RemoveProjectReference(ProjectReference projectReference) { if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } lock (_gate) { if (_activeBatchScopes > 0) { if (!_projectReferencesAddedInBatch.Remove(projectReference)) { _projectReferencesRemovedInBatch.Add(projectReference); } } else { _workspace.ApplyChangeToWorkspace(w => w.OnProjectReferenceRemoved(Id, projectReference)); } } } #endregion public void RemoveFromWorkspace() { _documentFileChangeContext.Dispose(); lock (_gate) { // clear tracking to external components foreach (var provider in _eventSubscriptionTracker) { provider.Updated -= OnDynamicFileInfoUpdated; } _eventSubscriptionTracker.Clear(); } IReadOnlyList<MetadataReference>? remainingMetadataReferences = null; _workspace.ApplyChangeToWorkspace(w => { // Acquire the remaining metadata references inside the workspace lock. This is critical // as another project being removed at the same time could result in project to project // references being converted to metadata references (or vice versa) and we might either // miss stopping a file watcher or might end up double-stopping a file watcher. remainingMetadataReferences = w.CurrentSolution.GetRequiredProject(Id).MetadataReferences; w.OnProjectRemoved(Id); }); Contract.ThrowIfNull(remainingMetadataReferences); foreach (PortableExecutableReference reference in remainingMetadataReferences) { _workspace.FileWatchedReferenceFactory.StopWatchingReference(reference); } } /// <summary> /// Adds an additional output path that can be used for automatic conversion of metadata references to P2P references. /// Any projects with metadata references to the path given here will be converted to project-to-project references. /// </summary> public void AddOutputPath(string outputPath) { if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException($"{nameof(outputPath)} isn't a valid path.", nameof(outputPath)); } _workspace.AddProjectOutputPath(Id, outputPath); } /// <summary> /// Removes an additional output path that was added by <see cref="AddOutputPath(string)"/>. /// </summary> public void RemoveOutputPath(string outputPath) { if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException($"{nameof(outputPath)} isn't a valid path.", nameof(outputPath)); } _workspace.RemoveProjectOutputPath(Id, outputPath); } public void ReorderSourceFiles(ImmutableArray<string> filePaths) => _sourceFiles.ReorderFiles(filePaths); /// <summary> /// Clears a list and zeros out the capacity. The lists we use for batching are likely to get large during an initial load, but after /// that point should never get that large again. /// </summary> private static void ClearAndZeroCapacity<T>(List<T> list) { list.Clear(); list.Capacity = 0; } /// <summary> /// Clears a list and zeros out the capacity. The lists we use for batching are likely to get large during an initial load, but after /// that point should never get that large again. /// </summary> private static void ClearAndZeroCapacity<T>(ImmutableArray<T>.Builder list) { list.Clear(); list.Capacity = 0; } /// <summary> /// Helper class to manage collections of source-file like things; this exists just to avoid duplicating all the logic for regular source files /// and additional files. /// </summary> /// <remarks>This class should be free-threaded, and any synchronization is done via <see cref="VisualStudioProject._gate"/>. /// This class is otehrwise free to operate on private members of <see cref="_project"/> if needed.</remarks> private sealed class BatchingDocumentCollection { private readonly VisualStudioProject _project; /// <summary> /// The map of file paths to the underlying <see cref="DocumentId"/>. This document may exist in <see cref="_documentsAddedInBatch"/> or has been /// pushed to the actual workspace. /// </summary> private readonly Dictionary<string, DocumentId> _documentPathsToDocumentIds = new(StringComparer.OrdinalIgnoreCase); /// <summary> /// A map of explicitly-added "always open" <see cref="SourceTextContainer"/> and their associated <see cref="DocumentId"/>. This does not contain /// any regular files that have been open. /// </summary> private IBidirectionalMap<SourceTextContainer, DocumentId> _sourceTextContainersToDocumentIds = BidirectionalMap<SourceTextContainer, DocumentId>.Empty; /// <summary> /// The map of <see cref="DocumentId"/> to <see cref="IDynamicFileInfoProvider"/> whose <see cref="DynamicFileInfo"/> got added into <see cref="Workspace"/> /// </summary> private readonly Dictionary<DocumentId, IDynamicFileInfoProvider> _documentIdToDynamicFileInfoProvider = new(); /// <summary> /// The current list of documents that are to be added in this batch. /// </summary> private readonly ImmutableArray<DocumentInfo>.Builder _documentsAddedInBatch = ImmutableArray.CreateBuilder<DocumentInfo>(); /// <summary> /// The current list of documents that are being removed in this batch. Once the document is in this list, it is no longer in <see cref="_documentPathsToDocumentIds"/>. /// </summary> private readonly List<DocumentId> _documentsRemovedInBatch = new(); /// <summary> /// The current list of document file paths that will be ordered in a batch. /// </summary> private ImmutableList<DocumentId>? _orderedDocumentsInBatch = null; private readonly Func<Solution, DocumentId, bool> _documentAlreadyInWorkspace; private readonly Action<Workspace, DocumentInfo> _documentAddAction; private readonly Action<Workspace, DocumentId> _documentRemoveAction; private readonly Action<Workspace, DocumentId, TextLoader> _documentTextLoaderChangedAction; public BatchingDocumentCollection(VisualStudioProject project, Func<Solution, DocumentId, bool> documentAlreadyInWorkspace, Action<Workspace, DocumentInfo> documentAddAction, Action<Workspace, DocumentId> documentRemoveAction, Action<Workspace, DocumentId, TextLoader> documentTextLoaderChangedAction) { _project = project; _documentAlreadyInWorkspace = documentAlreadyInWorkspace; _documentAddAction = documentAddAction; _documentRemoveAction = documentRemoveAction; _documentTextLoaderChangedAction = documentTextLoaderChangedAction; } public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray<string> folders) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } var documentId = DocumentId.CreateNewId(_project.Id, fullPath); var textLoader = new FileTextLoader(fullPath, defaultEncoding: null); var documentInfo = DocumentInfo.Create( documentId, FileNameUtilities.GetFileName(fullPath), folders: folders.IsDefault ? null : folders, sourceCodeKind: sourceCodeKind, loader: textLoader, filePath: fullPath, isGenerated: false); lock (_project._gate) { if (_documentPathsToDocumentIds.ContainsKey(fullPath)) { throw new ArgumentException($"'{fullPath}' has already been added to this project.", nameof(fullPath)); } // If we have an ordered document ids batch, we need to add the document id to the end of it as well. _orderedDocumentsInBatch = _orderedDocumentsInBatch?.Add(documentId); _documentPathsToDocumentIds.Add(fullPath, documentId); _project._documentFileWatchingTokens.Add(documentId, _project._documentFileChangeContext.EnqueueWatchingFile(fullPath)); if (_project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { _project._workspace.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo)); _project._workspace.QueueCheckForFilesBeingOpen(ImmutableArray.Create(fullPath)); } } return documentId; } public DocumentId AddTextContainer(SourceTextContainer textContainer, string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray<string> folders, bool designTimeOnly, IDocumentServiceProvider? documentServiceProvider) { if (textContainer == null) { throw new ArgumentNullException(nameof(textContainer)); } var documentId = DocumentId.CreateNewId(_project.Id, fullPath); var textLoader = new SourceTextLoader(textContainer, fullPath); var documentInfo = DocumentInfo.Create( documentId, FileNameUtilities.GetFileName(fullPath), folders: folders.NullToEmpty(), sourceCodeKind: sourceCodeKind, loader: textLoader, filePath: fullPath, isGenerated: false, designTimeOnly: designTimeOnly, documentServiceProvider: documentServiceProvider); lock (_project._gate) { if (_sourceTextContainersToDocumentIds.ContainsKey(textContainer)) { throw new ArgumentException($"{nameof(textContainer)} is already added to this project.", nameof(textContainer)); } if (fullPath != null) { if (_documentPathsToDocumentIds.ContainsKey(fullPath)) { throw new ArgumentException($"'{fullPath}' has already been added to this project."); } _documentPathsToDocumentIds.Add(fullPath, documentId); } _sourceTextContainersToDocumentIds = _sourceTextContainersToDocumentIds.Add(textContainer, documentInfo.Id); if (_project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { _project._workspace.ApplyChangeToWorkspace(w => { _project._workspace.AddDocumentToDocumentsNotFromFiles(documentInfo.Id); _documentAddAction(w, documentInfo); w.OnDocumentOpened(documentInfo.Id, textContainer); }); } } return documentId; } public void AddDynamicFile(IDynamicFileInfoProvider fileInfoProvider, DynamicFileInfo fileInfo, ImmutableArray<string> folders) { var documentInfo = CreateDocumentInfoFromFileInfo(fileInfo, folders.NullToEmpty()); // Generally, DocumentInfo.FilePath can be null, but we always have file paths for dynamic files. Contract.ThrowIfNull(documentInfo.FilePath); var documentId = documentInfo.Id; lock (_project._gate) { var filePath = documentInfo.FilePath; if (_documentPathsToDocumentIds.ContainsKey(filePath)) { throw new ArgumentException($"'{filePath}' has already been added to this project.", nameof(filePath)); } // If we have an ordered document ids batch, we need to add the document id to the end of it as well. _orderedDocumentsInBatch = _orderedDocumentsInBatch?.Add(documentId); _documentPathsToDocumentIds.Add(filePath, documentId); _documentIdToDynamicFileInfoProvider.Add(documentId, fileInfoProvider); if (_project._eventSubscriptionTracker.Add(fileInfoProvider)) { // subscribe to the event when we use this provider the first time fileInfoProvider.Updated += _project.OnDynamicFileInfoUpdated; } if (_project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { // right now, assumption is dynamically generated file can never be opened in editor _project._workspace.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo)); } } } public IDynamicFileInfoProvider RemoveDynamicFile(string fullPath) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_project._gate) { if (!_documentPathsToDocumentIds.TryGetValue(fullPath, out var documentId) || !_documentIdToDynamicFileInfoProvider.TryGetValue(documentId, out var fileInfoProvider)) { throw new ArgumentException($"'{fullPath}' is not a dynamic file of this project."); } _documentIdToDynamicFileInfoProvider.Remove(documentId); RemoveFileInternal(documentId, fullPath); return fileInfoProvider; } } public void RemoveFile(string fullPath) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_project._gate) { if (!_documentPathsToDocumentIds.TryGetValue(fullPath, out var documentId)) { throw new ArgumentException($"'{fullPath}' is not a source file of this project."); } _project._documentFileChangeContext.StopWatchingFile(_project._documentFileWatchingTokens[documentId]); _project._documentFileWatchingTokens.Remove(documentId); RemoveFileInternal(documentId, fullPath); } } private void RemoveFileInternal(DocumentId documentId, string fullPath) { _orderedDocumentsInBatch = _orderedDocumentsInBatch?.Remove(documentId); _documentPathsToDocumentIds.Remove(fullPath); // There are two cases: // // 1. This file is actually been pushed to the workspace, and we need to remove it (either // as a part of the active batch or immediately) // 2. It hasn't been pushed yet, but is contained in _documentsAddedInBatch if (_documentAlreadyInWorkspace(_project._workspace.CurrentSolution, documentId)) { if (_project._activeBatchScopes > 0) { _documentsRemovedInBatch.Add(documentId); } else { _project._workspace.ApplyChangeToWorkspace(w => _documentRemoveAction(w, documentId)); } } else { for (var i = 0; i < _documentsAddedInBatch.Count; i++) { if (_documentsAddedInBatch[i].Id == documentId) { _documentsAddedInBatch.RemoveAt(i); break; } } } } public void RemoveTextContainer(SourceTextContainer textContainer) { if (textContainer == null) { throw new ArgumentNullException(nameof(textContainer)); } lock (_project._gate) { if (!_sourceTextContainersToDocumentIds.TryGetValue(textContainer, out var documentId)) { throw new ArgumentException($"{nameof(textContainer)} is not a text container added to this project."); } _sourceTextContainersToDocumentIds = _sourceTextContainersToDocumentIds.RemoveKey(textContainer); // if the TextContainer had a full path provided, remove it from the map. var entry = _documentPathsToDocumentIds.Where(kv => kv.Value == documentId).FirstOrDefault(); if (entry.Key != null) { _documentPathsToDocumentIds.Remove(entry.Key); } // There are two cases: // // 1. This file is actually been pushed to the workspace, and we need to remove it (either // as a part of the active batch or immediately) // 2. It hasn't been pushed yet, but is contained in _documentsAddedInBatch if (_project._workspace.CurrentSolution.GetDocument(documentId) != null) { if (_project._activeBatchScopes > 0) { _documentsRemovedInBatch.Add(documentId); } else { _project._workspace.ApplyChangeToWorkspace(w => { // Just pass null for the filePath, since this document is immediately being removed // anyways -- whatever we set won't really be read since the next change will // come through. // TODO: Can't we just remove the document without closing it? w.OnDocumentClosed(documentId, new SourceTextLoader(textContainer, filePath: null)); _documentRemoveAction(w, documentId); _project._workspace.RemoveDocumentToDocumentsNotFromFiles(documentId); }); } } else { for (var i = 0; i < _documentsAddedInBatch.Count; i++) { if (_documentsAddedInBatch[i].Id == documentId) { _documentsAddedInBatch.RemoveAt(i); break; } } } } } public bool ContainsFile(string fullPath) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_project._gate) { return _documentPathsToDocumentIds.ContainsKey(fullPath); } } public void ProcessFileChange(string filePath) => ProcessFileChange(filePath, filePath); /// <summary> /// Process file content changes /// </summary> /// <param name="projectSystemFilePath">filepath given from project system</param> /// <param name="workspaceFilePath">filepath used in workspace. it might be different than projectSystemFilePath. ex) dynamic file</param> public void ProcessFileChange(string projectSystemFilePath, string workspaceFilePath) { lock (_project._gate) { if (_documentPathsToDocumentIds.TryGetValue(workspaceFilePath, out var documentId)) { // We create file watching prior to pushing the file to the workspace in batching, so it's // possible we might see a file change notification early. In this case, toss it out. Since // all adds/removals of documents for this project happen under our lock, it's safe to do this // check without taking the main workspace lock if (_documentsAddedInBatch.Any(d => d.Id == documentId)) { return; } _documentIdToDynamicFileInfoProvider.TryGetValue(documentId, out var fileInfoProvider); _project._workspace.ApplyChangeToWorkspace(w => { if (w.IsDocumentOpen(documentId)) { return; } if (fileInfoProvider == null) { var textLoader = new FileTextLoader(projectSystemFilePath, defaultEncoding: null); _documentTextLoaderChangedAction(w, documentId, textLoader); } else { // we do not expect JTF to be used around this code path. and contract of fileInfoProvider is it being real free-threaded // meaning it can't use JTF to go back to UI thread. // so, it is okay for us to call regular ".Result" on a task here. var fileInfo = fileInfoProvider.GetDynamicFileInfoAsync( _project.Id, _project._filePath, projectSystemFilePath, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); // Right now we're only supporting dynamic files as actual source files, so it's OK to call GetDocument here var document = w.CurrentSolution.GetRequiredDocument(documentId); var documentInfo = DocumentInfo.Create( document.Id, document.Name, document.Folders, document.SourceCodeKind, loader: fileInfo.TextLoader, document.FilePath, document.State.Attributes.IsGenerated, document.State.Attributes.DesignTimeOnly, documentServiceProvider: fileInfo.DocumentServiceProvider); w.OnDocumentReloaded(documentInfo); } }); } } } public void ReorderFiles(ImmutableArray<string> filePaths) { if (filePaths.IsEmpty) { throw new ArgumentOutOfRangeException("The specified files are empty.", nameof(filePaths)); } lock (_project._gate) { if (_documentPathsToDocumentIds.Count != filePaths.Length) { throw new ArgumentException("The specified files do not equal the project document count.", nameof(filePaths)); } var documentIds = ImmutableList.CreateBuilder<DocumentId>(); foreach (var filePath in filePaths) { if (_documentPathsToDocumentIds.TryGetValue(filePath, out var documentId)) { documentIds.Add(documentId); } else { throw new InvalidOperationException($"The file '{filePath}' does not exist in the project."); } } if (_project._activeBatchScopes > 0) { _orderedDocumentsInBatch = documentIds.ToImmutable(); } else { _project._workspace.ApplyBatchChangeToWorkspace(solution => { var solutionChanges = new SolutionChangeAccumulator(solution); solutionChanges.UpdateSolutionForProjectAction( _project.Id, solutionChanges.Solution.WithProjectDocumentsOrder(_project.Id, documentIds.ToImmutable())); return solutionChanges; }); } } } internal void UpdateSolutionForBatch( SolutionChangeAccumulator solutionChanges, ImmutableArray<string>.Builder documentFileNamesAdded, List<(DocumentId documentId, SourceTextContainer textContainer)> documentsToOpen, Func<Solution, ImmutableArray<DocumentInfo>, Solution> addDocuments, WorkspaceChangeKind addDocumentChangeKind, Func<Solution, ImmutableArray<DocumentId>, Solution> removeDocuments, WorkspaceChangeKind removeDocumentChangeKind) { // Document adding... solutionChanges.UpdateSolutionForDocumentAction( newSolution: addDocuments(solutionChanges.Solution, _documentsAddedInBatch.ToImmutable()), changeKind: addDocumentChangeKind, documentIds: _documentsAddedInBatch.Select(d => d.Id)); foreach (var documentInfo in _documentsAddedInBatch) { Contract.ThrowIfNull(documentInfo.FilePath, "We shouldn't be adding documents without file paths."); documentFileNamesAdded.Add(documentInfo.FilePath); if (_sourceTextContainersToDocumentIds.TryGetKey(documentInfo.Id, out var textContainer)) { documentsToOpen.Add((documentInfo.Id, textContainer)); } } ClearAndZeroCapacity(_documentsAddedInBatch); // Document removing... solutionChanges.UpdateSolutionForRemovedDocumentAction(removeDocuments(solutionChanges.Solution, _documentsRemovedInBatch.ToImmutableArray()), removeDocumentChangeKind, _documentsRemovedInBatch); ClearAndZeroCapacity(_documentsRemovedInBatch); // Update project's order of documents. if (_orderedDocumentsInBatch != null) { solutionChanges.UpdateSolutionForProjectAction( _project.Id, solutionChanges.Solution.WithProjectDocumentsOrder(_project.Id, _orderedDocumentsInBatch)); _orderedDocumentsInBatch = null; } } private DocumentInfo CreateDocumentInfoFromFileInfo(DynamicFileInfo fileInfo, ImmutableArray<string> folders) { Contract.ThrowIfTrue(folders.IsDefault); // we use this file path for editorconfig. var filePath = fileInfo.FilePath; var name = FileNameUtilities.GetFileName(filePath); var documentId = DocumentId.CreateNewId(_project.Id, filePath); var textLoader = fileInfo.TextLoader; var documentServiceProvider = fileInfo.DocumentServiceProvider; return DocumentInfo.Create( documentId, name, folders: folders, sourceCodeKind: fileInfo.SourceCodeKind, loader: textLoader, filePath: filePath, isGenerated: false, designTimeOnly: true, documentServiceProvider: documentServiceProvider); } private sealed class SourceTextLoader : TextLoader { private readonly SourceTextContainer _textContainer; private readonly string? _filePath; public SourceTextLoader(SourceTextContainer textContainer, string? filePath) { _textContainer = textContainer; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(TextAndVersion.Create(_textContainer.CurrentText, VersionStamp.Create(), _filePath)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed class VisualStudioProject { private static readonly ImmutableArray<MetadataReferenceProperties> s_defaultMetadataReferenceProperties = ImmutableArray.Create(default(MetadataReferenceProperties)); private readonly VisualStudioWorkspaceImpl _workspace; private readonly HostDiagnosticUpdateSource _hostDiagnosticUpdateSource; private readonly IWorkspaceTelemetryService? _telemetryService; private readonly IWorkspaceStatusService? _workspaceStatusService; /// <summary> /// Provides dynamic source files for files added through <see cref="AddDynamicSourceFile" />. /// </summary> private readonly ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> _dynamicFileInfoProviders; /// <summary> /// A gate taken for all mutation of any mutable field in this type. /// </summary> /// <remarks>This is, for now, intentionally pessimistic. There are no doubt ways that we could allow more to run in parallel, /// but the current tradeoff is for simplicity of code and "obvious correctness" than something that is subtle, fast, and wrong.</remarks> private readonly object _gate = new(); /// <summary> /// The number of active batch scopes. If this is zero, we are not batching, non-zero means we are batching. /// </summary> private int _activeBatchScopes = 0; private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesAddedInBatch = new(); private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesRemovedInBatch = new(); private readonly List<ProjectReference> _projectReferencesAddedInBatch = new(); private readonly List<ProjectReference> _projectReferencesRemovedInBatch = new(); private readonly Dictionary<string, VisualStudioAnalyzer> _analyzerPathsToAnalyzers = new(); private readonly List<VisualStudioAnalyzer> _analyzersAddedInBatch = new(); private readonly List<VisualStudioAnalyzer> _analyzersRemovedInBatch = new(); private readonly List<Func<Solution, Solution>> _projectPropertyModificationsInBatch = new(); private string _assemblyName; private string _displayName; private string? _filePath; private CompilationOptions? _compilationOptions; private ParseOptions? _parseOptions; private bool _hasAllInformation = true; private string? _compilationOutputAssemblyFilePath; private string? _outputFilePath; private string? _outputRefFilePath; private string? _defaultNamespace; /// <summary> /// If this project is the 'primary' project the project system cares about for a group of Roslyn projects that /// correspond to different configurations of a single project system project. <see langword="true"/> by /// default. /// </summary> internal bool IsPrimary { get; set; } = true; // Actual property values for 'RunAnalyzers' and 'RunAnalyzersDuringLiveAnalysis' properties from the project file. // Both these properties can be used to configure running analyzers, with RunAnalyzers overriding RunAnalyzersDuringLiveAnalysis. private bool? _runAnalyzersPropertyValue; private bool? _runAnalyzersDuringLiveAnalysisPropertyValue; // Effective boolean value to determine if analyzers should be executed based on _runAnalyzersPropertyValue and _runAnalyzersDuringLiveAnalysisPropertyValue. private bool _runAnalyzers = true; /// <summary> /// The full list of all metadata references this project has. References that have internally been converted to project references /// will still be in this. /// </summary> private readonly Dictionary<string, ImmutableArray<MetadataReferenceProperties>> _allMetadataReferences = new(); /// <summary> /// The file watching tokens for the documents in this project. We get the tokens even when we're in a batch, so the files here /// may not be in the actual workspace yet. /// </summary> private readonly Dictionary<DocumentId, FileChangeWatcher.IFileWatchingToken> _documentFileWatchingTokens = new(); /// <summary> /// A file change context used to watch source files, additional files, and analyzer config files for this project. It's automatically set to watch the user's project /// directory so we avoid file-by-file watching. /// </summary> private readonly FileChangeWatcher.IContext _documentFileChangeContext; /// <summary> /// track whether we have been subscribed to <see cref="IDynamicFileInfoProvider.Updated"/> event /// </summary> private readonly HashSet<IDynamicFileInfoProvider> _eventSubscriptionTracker = new(); /// <summary> /// Map of the original dynamic file path to the <see cref="DynamicFileInfo.FilePath"/> that was associated with it. /// /// For example, the key is something like Page.cshtml which is given to us from the project system calling /// <see cref="AddDynamicSourceFile(string, ImmutableArray{string})"/>. The value of the map is a generated file that /// corresponds to the original path, say Page.g.cs. If we were given a file by the project system but no /// <see cref="IDynamicFileInfoProvider"/> provided a file for it, we will record the value as null so we still can track /// the addition of the .cshtml file for a later call to <see cref="RemoveDynamicSourceFile(string)"/>. /// /// The workspace snapshot will only have a document with <see cref="DynamicFileInfo.FilePath"/> (the value) but not the /// original dynamic file path (the key). /// </summary> /// <remarks> /// We use the same string comparer as in the <see cref="BatchingDocumentCollection"/> used by _sourceFiles, below, as these /// files are added to that collection too. /// </remarks> private readonly Dictionary<string, string?> _dynamicFilePathMaps = new(StringComparer.OrdinalIgnoreCase); private readonly BatchingDocumentCollection _sourceFiles; private readonly BatchingDocumentCollection _additionalFiles; private readonly BatchingDocumentCollection _analyzerConfigFiles; public ProjectId Id { get; } public string Language { get; } internal VisualStudioProject( VisualStudioWorkspaceImpl workspace, ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> dynamicFileInfoProviders, HostDiagnosticUpdateSource hostDiagnosticUpdateSource, ProjectId id, string displayName, string language, string assemblyName, CompilationOptions? compilationOptions, string? filePath, ParseOptions? parseOptions) { _workspace = workspace; _dynamicFileInfoProviders = dynamicFileInfoProviders; _hostDiagnosticUpdateSource = hostDiagnosticUpdateSource; _telemetryService = _workspace.Services.GetService<IWorkspaceTelemetryService>(); _workspaceStatusService = _workspace.Services.GetService<IWorkspaceStatusService>(); Id = id; Language = language; _displayName = displayName; _sourceFiles = new BatchingDocumentCollection( this, documentAlreadyInWorkspace: (s, d) => s.ContainsDocument(d), documentAddAction: (w, d) => w.OnDocumentAdded(d), documentRemoveAction: (w, documentId) => w.OnDocumentRemoved(documentId), documentTextLoaderChangedAction: (w, d, loader) => w.OnDocumentTextLoaderChanged(d, loader)); _additionalFiles = new BatchingDocumentCollection(this, (s, d) => s.ContainsAdditionalDocument(d), (w, d) => w.OnAdditionalDocumentAdded(d), (w, documentId) => w.OnAdditionalDocumentRemoved(documentId), documentTextLoaderChangedAction: (w, d, loader) => w.OnAdditionalDocumentTextLoaderChanged(d, loader)); _analyzerConfigFiles = new BatchingDocumentCollection(this, (s, d) => s.ContainsAnalyzerConfigDocument(d), (w, d) => w.OnAnalyzerConfigDocumentAdded(d), (w, documentId) => w.OnAnalyzerConfigDocumentRemoved(documentId), documentTextLoaderChangedAction: (w, d, loader) => w.OnAnalyzerConfigDocumentTextLoaderChanged(d, loader)); _assemblyName = assemblyName; _compilationOptions = compilationOptions; _filePath = filePath; _parseOptions = parseOptions; var fileExtensionToWatch = language switch { LanguageNames.CSharp => ".cs", LanguageNames.VisualBasic => ".vb", _ => null }; if (filePath != null && fileExtensionToWatch != null) { // Since we have a project directory, we'll just watch all the files under that path; that'll avoid extra overhead of // having to add explicit file watches everywhere. var projectDirectoryToWatch = new FileChangeWatcher.WatchedDirectory(Path.GetDirectoryName(filePath), fileExtensionToWatch); _documentFileChangeContext = _workspace.FileChangeWatcher.CreateContext(projectDirectoryToWatch); } else { _documentFileChangeContext = workspace.FileChangeWatcher.CreateContext(); } _documentFileChangeContext.FileChanged += DocumentFileChangeContext_FileChanged; } private void ChangeProjectProperty<T>(ref T field, T newValue, Func<Solution, Solution> withNewValue, bool logThrowAwayTelemetry = false) { lock (_gate) { // If nothing is changing, we can skip entirely if (object.Equals(field, newValue)) { return; } field = newValue; // Importantly, we do not await/wait on the fullyLoadedStateTask. We do not want to ever be waiting on work // that may end up touching the UI thread (As we can deadlock if GetTagsSynchronous waits on us). Instead, // we only check if the Task is completed. Prior to that we will assume we are still loading. Once this // task is completed, we know that the WaitUntilFullyLoadedAsync call will have actually finished and we're // fully loaded. var isFullyLoadedTask = _workspaceStatusService?.IsFullyLoadedAsync(CancellationToken.None); var isFullyLoaded = isFullyLoadedTask is { IsCompleted: true } && isFullyLoadedTask.GetAwaiter().GetResult(); // We only log telemetry during solution open if (logThrowAwayTelemetry && _telemetryService?.HasActiveSession == true && !isFullyLoaded) { TryReportCompilationThrownAway(_workspace.CurrentSolution.State, Id); } if (_activeBatchScopes > 0) { _projectPropertyModificationsInBatch.Add(withNewValue); } else { _workspace.ApplyChangeToWorkspace(Id, withNewValue); } } } /// <summary> /// Reports a telemetry event if compilation information is being thrown away after being previously computed /// </summary> private static void TryReportCompilationThrownAway(SolutionState solutionState, ProjectId projectId) { // We log the number of syntax trees that have been parsed even if there was no compilation created yet var projectState = solutionState.GetRequiredProjectState(projectId); var parsedTrees = 0; foreach (var (_, documentState) in projectState.DocumentStates.States) { if (documentState.TryGetSyntaxTree(out _)) { parsedTrees++; } } // But we also want to know if a compilation was created var hadCompilation = solutionState.TryGetCompilation(projectId, out _); if (parsedTrees > 0 || hadCompilation) { Logger.Log(FunctionId.Workspace_Project_CompilationThrownAway, KeyValueLogMessage.Create(m => { // Note: Not using our project Id. This is the same ProjectGuid that the project system uses // so data can be correlated m["ProjectGuid"] = projectState.ProjectInfo.Attributes.TelemetryId.ToString("B"); m["SyntaxTreesParsed"] = parsedTrees; m["HadCompilation"] = hadCompilation; })); } } private void ChangeProjectOutputPath(ref string? field, string? newValue, Func<Solution, Solution> withNewValue) { lock (_gate) { // Skip if nothing changing if (field == newValue) { return; } if (field != null) { _workspace.RemoveProjectOutputPath(Id, field); } if (newValue != null) { _workspace.AddProjectOutputPath(Id, newValue); } ChangeProjectProperty(ref field, newValue, withNewValue); } } public string AssemblyName { get => _assemblyName; set => ChangeProjectProperty(ref _assemblyName, value, s => s.WithProjectAssemblyName(Id, value), logThrowAwayTelemetry: true); } // The property could be null if this is a non-C#/VB language and we don't have one for it. But we disallow assigning null, because C#/VB cannot end up null // again once they already had one. [DisallowNull] public CompilationOptions? CompilationOptions { get => _compilationOptions; set => ChangeProjectProperty(ref _compilationOptions, value, s => s.WithProjectCompilationOptions(Id, value), logThrowAwayTelemetry: true); } // The property could be null if this is a non-C#/VB language and we don't have one for it. But we disallow assigning null, because C#/VB cannot end up null // again once they already had one. [DisallowNull] public ParseOptions? ParseOptions { get => _parseOptions; set => ChangeProjectProperty(ref _parseOptions, value, s => s.WithProjectParseOptions(Id, value), logThrowAwayTelemetry: true); } /// <summary> /// The path to the output in obj. /// </summary> internal string? CompilationOutputAssemblyFilePath { get => _compilationOutputAssemblyFilePath; set => ChangeProjectOutputPath( ref _compilationOutputAssemblyFilePath, value, s => s.WithProjectCompilationOutputInfo(Id, s.GetRequiredProject(Id).CompilationOutputInfo.WithAssemblyPath(value))); } public string? OutputFilePath { get => _outputFilePath; set => ChangeProjectOutputPath(ref _outputFilePath, value, s => s.WithProjectOutputFilePath(Id, value)); } public string? OutputRefFilePath { get => _outputRefFilePath; set => ChangeProjectOutputPath(ref _outputRefFilePath, value, s => s.WithProjectOutputRefFilePath(Id, value)); } public string? FilePath { get => _filePath; set => ChangeProjectProperty(ref _filePath, value, s => s.WithProjectFilePath(Id, value)); } public string DisplayName { get => _displayName; set => ChangeProjectProperty(ref _displayName, value, s => s.WithProjectName(Id, value)); } // internal to match the visibility of the Workspace-level API -- this is something // we use but we haven't made officially public yet. internal bool HasAllInformation { get => _hasAllInformation; set => ChangeProjectProperty(ref _hasAllInformation, value, s => s.WithHasAllInformation(Id, value)); } internal bool? RunAnalyzers { get => _runAnalyzersPropertyValue; set { _runAnalyzersPropertyValue = value; UpdateRunAnalyzers(); } } internal bool? RunAnalyzersDuringLiveAnalysis { get => _runAnalyzersDuringLiveAnalysisPropertyValue; set { _runAnalyzersDuringLiveAnalysisPropertyValue = value; UpdateRunAnalyzers(); } } private void UpdateRunAnalyzers() { // Property RunAnalyzers overrides RunAnalyzersDuringLiveAnalysis, and default when both properties are not set is 'true'. var runAnalyzers = _runAnalyzersPropertyValue ?? _runAnalyzersDuringLiveAnalysisPropertyValue ?? true; ChangeProjectProperty(ref _runAnalyzers, runAnalyzers, s => s.WithRunAnalyzers(Id, runAnalyzers)); } /// <summary> /// The default namespace of the project. /// </summary> /// <remarks> /// In C#, this is defined as the value of "rootnamespace" msbuild property. Right now VB doesn't /// have the concept of "default namespace", but we conjure one in workspace by assigning the value /// of the project's root namespace to it. So various features can choose to use it for their own purpose. /// /// In the future, we might consider officially exposing "default namespace" for VB project /// (e.g.through a "defaultnamespace" msbuild property) /// </remarks> internal string? DefaultNamespace { get => _defaultNamespace; set => ChangeProjectProperty(ref _defaultNamespace, value, s => s.WithProjectDefaultNamespace(Id, value)); } /// <summary> /// The max language version supported for this project, if applicable. Useful to help indicate what /// language version features should be suggested to a user, as well as if they can be upgraded. /// </summary> internal string? MaxLangVersion { set => _workspace.SetMaxLanguageVersion(Id, value); } internal string DependencyNodeTargetIdentifier { set => _workspace.SetDependencyNodeTargetIdentifier(Id, value); } #region Batching public BatchScope CreateBatchScope() { lock (_gate) { _activeBatchScopes++; return new BatchScope(this); } } public sealed class BatchScope : IDisposable { private readonly VisualStudioProject _project; /// <summary> /// Flag to control if this has already been disposed. Not a boolean only so it can be used with Interlocked.CompareExchange. /// </summary> private volatile int _disposed = 0; internal BatchScope(VisualStudioProject visualStudioProject) => _project = visualStudioProject; public void Dispose() { if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0) { _project.OnBatchScopeDisposed(); } } } private void OnBatchScopeDisposed() { lock (_gate) { _activeBatchScopes--; if (_activeBatchScopes > 0) { return; } var documentFileNamesAdded = ImmutableArray.CreateBuilder<string>(); var documentsToOpen = new List<(DocumentId documentId, SourceTextContainer textContainer)>(); var additionalDocumentsToOpen = new List<(DocumentId documentId, SourceTextContainer textContainer)>(); var analyzerConfigDocumentsToOpen = new List<(DocumentId documentId, SourceTextContainer textContainer)>(); _workspace.ApplyBatchChangeToWorkspace(solution => { var solutionChanges = new SolutionChangeAccumulator(startingSolution: solution); _sourceFiles.UpdateSolutionForBatch( solutionChanges, documentFileNamesAdded, documentsToOpen, (s, documents) => s.AddDocuments(documents), WorkspaceChangeKind.DocumentAdded, (s, ids) => s.RemoveDocuments(ids), WorkspaceChangeKind.DocumentRemoved); _additionalFiles.UpdateSolutionForBatch( solutionChanges, documentFileNamesAdded, additionalDocumentsToOpen, (s, documents) => { foreach (var document in documents) { s = s.AddAdditionalDocument(document); } return s; }, WorkspaceChangeKind.AdditionalDocumentAdded, (s, ids) => s.RemoveAdditionalDocuments(ids), WorkspaceChangeKind.AdditionalDocumentRemoved); _analyzerConfigFiles.UpdateSolutionForBatch( solutionChanges, documentFileNamesAdded, analyzerConfigDocumentsToOpen, (s, documents) => s.AddAnalyzerConfigDocuments(documents), WorkspaceChangeKind.AnalyzerConfigDocumentAdded, (s, ids) => s.RemoveAnalyzerConfigDocuments(ids), WorkspaceChangeKind.AnalyzerConfigDocumentRemoved); // Metadata reference removing. Do this before adding in case this removes a project reference that // we are also going to add in the same batch. This could happen if case is changing, or we're targeting // a different output path (say bin vs. obj vs. ref). foreach (var (path, properties) in _metadataReferencesRemovedInBatch) { var projectReference = _workspace.TryRemoveConvertedProjectReference_NoLock(Id, path, properties); if (projectReference != null) { solutionChanges.UpdateSolutionForProjectAction( Id, solutionChanges.Solution.RemoveProjectReference(Id, projectReference)); } else { // TODO: find a cleaner way to fetch this var metadataReference = _workspace.CurrentSolution.GetRequiredProject(Id).MetadataReferences.Cast<PortableExecutableReference>() .Single(m => m.FilePath == path && m.Properties == properties); _workspace.FileWatchedReferenceFactory.StopWatchingReference(metadataReference); solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.RemoveMetadataReference(Id, metadataReference)); } } ClearAndZeroCapacity(_metadataReferencesRemovedInBatch); // Metadata reference adding... if (_metadataReferencesAddedInBatch.Count > 0) { var projectReferencesCreated = new List<ProjectReference>(); var metadataReferencesCreated = new List<MetadataReference>(); foreach (var (path, properties) in _metadataReferencesAddedInBatch) { var projectReference = _workspace.TryCreateConvertedProjectReference_NoLock(Id, path, properties); if (projectReference != null) { projectReferencesCreated.Add(projectReference); } else { var metadataReference = _workspace.FileWatchedReferenceFactory.CreateReferenceAndStartWatchingFile(path, properties); metadataReferencesCreated.Add(metadataReference); } } solutionChanges.UpdateSolutionForProjectAction( Id, solutionChanges.Solution.AddProjectReferences(Id, projectReferencesCreated) .AddMetadataReferences(Id, metadataReferencesCreated)); ClearAndZeroCapacity(_metadataReferencesAddedInBatch); } // Project reference adding... solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.AddProjectReferences(Id, _projectReferencesAddedInBatch)); ClearAndZeroCapacity(_projectReferencesAddedInBatch); // Project reference removing... foreach (var projectReference in _projectReferencesRemovedInBatch) { solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.RemoveProjectReference(Id, projectReference)); } ClearAndZeroCapacity(_projectReferencesRemovedInBatch); // Analyzer reference adding... solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.AddAnalyzerReferences(Id, _analyzersAddedInBatch.Select(a => a.GetReference()))); ClearAndZeroCapacity(_analyzersAddedInBatch); // Analyzer reference removing... foreach (var analyzerReference in _analyzersRemovedInBatch) { solutionChanges.UpdateSolutionForProjectAction( Id, newSolution: solutionChanges.Solution.RemoveAnalyzerReference(Id, analyzerReference.GetReference())); } ClearAndZeroCapacity(_analyzersRemovedInBatch); // Other property modifications... foreach (var propertyModification in _projectPropertyModificationsInBatch) { solutionChanges.UpdateSolutionForProjectAction( Id, propertyModification(solutionChanges.Solution)); } ClearAndZeroCapacity(_projectPropertyModificationsInBatch); return solutionChanges; }); foreach (var (documentId, textContainer) in documentsToOpen) { _workspace.ApplyChangeToWorkspace(w => w.OnDocumentOpened(documentId, textContainer)); } foreach (var (documentId, textContainer) in additionalDocumentsToOpen) { _workspace.ApplyChangeToWorkspace(w => w.OnAdditionalDocumentOpened(documentId, textContainer)); } foreach (var (documentId, textContainer) in analyzerConfigDocumentsToOpen) { _workspace.ApplyChangeToWorkspace(w => w.OnAnalyzerConfigDocumentOpened(documentId, textContainer)); } // Check for those files being opened to start wire-up if necessary _workspace.QueueCheckForFilesBeingOpen(documentFileNamesAdded.ToImmutable()); } } #endregion #region Source File Addition/Removal public void AddSourceFile(string fullPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, ImmutableArray<string> folders = default) => _sourceFiles.AddFile(fullPath, sourceCodeKind, folders); /// <summary> /// Adds a source file to the project from a text container (eg, a Visual Studio Text buffer) /// </summary> /// <param name="textContainer">The text container that contains this file.</param> /// <param name="fullPath">The file path of the document.</param> /// <param name="sourceCodeKind">The kind of the source code.</param> /// <param name="folders">The names of the logical nested folders the document is contained in.</param> /// <param name="designTimeOnly">Whether the document is used only for design time (eg. completion) or also included in a compilation.</param> /// <param name="documentServiceProvider">A <see cref="IDocumentServiceProvider"/> associated with this document</param> public DocumentId AddSourceTextContainer( SourceTextContainer textContainer, string fullPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, ImmutableArray<string> folders = default, bool designTimeOnly = false, IDocumentServiceProvider? documentServiceProvider = null) { return _sourceFiles.AddTextContainer(textContainer, fullPath, sourceCodeKind, folders, designTimeOnly, documentServiceProvider); } public bool ContainsSourceFile(string fullPath) => _sourceFiles.ContainsFile(fullPath); public void RemoveSourceFile(string fullPath) => _sourceFiles.RemoveFile(fullPath); public void RemoveSourceTextContainer(SourceTextContainer textContainer) => _sourceFiles.RemoveTextContainer(textContainer); #endregion #region Additional File Addition/Removal // TODO: should AdditionalFiles have source code kinds? public void AddAdditionalFile(string fullPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular) => _additionalFiles.AddFile(fullPath, sourceCodeKind, folders: default); public bool ContainsAdditionalFile(string fullPath) => _additionalFiles.ContainsFile(fullPath); public void RemoveAdditionalFile(string fullPath) => _additionalFiles.RemoveFile(fullPath); #endregion #region Analyzer Config File Addition/Removal public void AddAnalyzerConfigFile(string fullPath) { // TODO: do we need folders for analyzer config files? _analyzerConfigFiles.AddFile(fullPath, SourceCodeKind.Regular, folders: default); } public bool ContainsAnalyzerConfigFile(string fullPath) => _analyzerConfigFiles.ContainsFile(fullPath); public void RemoveAnalyzerConfigFile(string fullPath) => _analyzerConfigFiles.RemoveFile(fullPath); #endregion #region Non Source File Addition/Removal public void AddDynamicSourceFile(string dynamicFilePath, ImmutableArray<string> folders) { DynamicFileInfo? fileInfo = null; IDynamicFileInfoProvider? providerForFileInfo = null; var extension = FileNameUtilities.GetExtension(dynamicFilePath)?.TrimStart('.'); if (extension?.Length == 0) { fileInfo = null; } else { foreach (var provider in _dynamicFileInfoProviders) { // skip unrelated providers if (!provider.Metadata.Extensions.Any(e => string.Equals(e, extension, StringComparison.OrdinalIgnoreCase))) { continue; } // Don't get confused by _filePath and filePath. // VisualStudioProject._filePath points to csproj/vbproj of the project // and the parameter filePath points to dynamic file such as ASP.NET .g.cs files. // // Also, provider is free-threaded. so fine to call Wait rather than JTF. fileInfo = provider.Value.GetDynamicFileInfoAsync( projectId: Id, projectFilePath: _filePath, filePath: dynamicFilePath, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); if (fileInfo != null) { fileInfo = FixUpDynamicFileInfo(fileInfo, dynamicFilePath); providerForFileInfo = provider.Value; break; } } } lock (_gate) { if (_dynamicFilePathMaps.ContainsKey(dynamicFilePath)) { // TODO: if we have a duplicate, we are not calling RemoveDynamicFileInfoAsync since we // don't want to call with that under a lock. If we are getting duplicates we have bigger problems // at that point since our workspace is generally out of sync with the project system. // Given we're taking this as a late fix prior to a release, I don't think it's worth the added // risk to handle a case that wasn't handled before either. throw new ArgumentException($"{dynamicFilePath} has already been added to this project."); } // Record the mapping from the dynamic file path to the source file it generated. We will record // 'null' if no provider was able to produce a source file for this input file. That could happen // if the provider (say ASP.NET Razor) doesn't recognize the file, or the wrong type of file // got passed through the system. That's not a failure from the project system's perspective: // adding dynamic files is a hint at best that doesn't impact it. _dynamicFilePathMaps.Add(dynamicFilePath, fileInfo?.FilePath); if (fileInfo != null) { // If fileInfo is not null, that means we found a provider so this should be not-null as well // since we had to go through the earlier assignment. Contract.ThrowIfNull(providerForFileInfo); _sourceFiles.AddDynamicFile(providerForFileInfo, fileInfo, folders); } } } private static DynamicFileInfo FixUpDynamicFileInfo(DynamicFileInfo fileInfo, string filePath) { // we might change contract and just throw here. but for now, we keep existing contract where one can return null for DynamicFileInfo.FilePath. // In this case we substitute the file being generated from so we still have some path. if (string.IsNullOrEmpty(fileInfo.FilePath)) { return new DynamicFileInfo(filePath, fileInfo.SourceCodeKind, fileInfo.TextLoader, fileInfo.DesignTimeOnly, fileInfo.DocumentServiceProvider); } return fileInfo; } public void RemoveDynamicSourceFile(string dynamicFilePath) { IDynamicFileInfoProvider provider; lock (_gate) { if (!_dynamicFilePathMaps.TryGetValue(dynamicFilePath, out var sourceFilePath)) { throw new ArgumentException($"{dynamicFilePath} wasn't added by a previous call to {nameof(AddDynamicSourceFile)}"); } _dynamicFilePathMaps.Remove(dynamicFilePath); // If we got a null path back, it means we never had a source file to add. In that case, // we're done if (sourceFilePath == null) { return; } provider = _sourceFiles.RemoveDynamicFile(sourceFilePath); } // provider is free-threaded. so fine to call Wait rather than JTF provider.RemoveDynamicFileInfoAsync( projectId: Id, projectFilePath: _filePath, filePath: dynamicFilePath, CancellationToken.None).Wait(CancellationToken.None); } private void OnDynamicFileInfoUpdated(object sender, string dynamicFilePath) { string? fileInfoPath; lock (_gate) { if (!_dynamicFilePathMaps.TryGetValue(dynamicFilePath, out fileInfoPath)) { // given file doesn't belong to this project. // this happen since the event this is handling is shared between all projects return; } } if (fileInfoPath != null) { _sourceFiles.ProcessFileChange(dynamicFilePath, fileInfoPath); } } #endregion #region Analyzer Addition/Removal public void AddAnalyzerReference(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); var visualStudioAnalyzer = new VisualStudioAnalyzer( fullPath, _hostDiagnosticUpdateSource, Id, Language); lock (_gate) { if (_analyzerPathsToAnalyzers.ContainsKey(fullPath)) { throw new ArgumentException($"'{fullPath}' has already been added to this project.", nameof(fullPath)); } _analyzerPathsToAnalyzers.Add(fullPath, visualStudioAnalyzer); if (_activeBatchScopes > 0) { _analyzersAddedInBatch.Add(visualStudioAnalyzer); } else { _workspace.ApplyChangeToWorkspace(w => w.OnAnalyzerReferenceAdded(Id, visualStudioAnalyzer.GetReference())); } } } public void RemoveAnalyzerReference(string fullPath) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException("message", nameof(fullPath)); } lock (_gate) { if (!_analyzerPathsToAnalyzers.TryGetValue(fullPath, out var visualStudioAnalyzer)) { throw new ArgumentException($"'{fullPath}' is not an analyzer of this project.", nameof(fullPath)); } _analyzerPathsToAnalyzers.Remove(fullPath); if (_activeBatchScopes > 0) { _analyzersRemovedInBatch.Add(visualStudioAnalyzer); } else { _workspace.ApplyChangeToWorkspace(w => w.OnAnalyzerReferenceRemoved(Id, visualStudioAnalyzer.GetReference())); } } } #endregion private void DocumentFileChangeContext_FileChanged(object sender, string fullFilePath) { _sourceFiles.ProcessFileChange(fullFilePath); _additionalFiles.ProcessFileChange(fullFilePath); _analyzerConfigFiles.ProcessFileChange(fullFilePath); } #region Metadata Reference Addition/Removal public void AddMetadataReference(string fullPath, MetadataReferenceProperties properties) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_gate) { if (ContainsMetadataReference(fullPath, properties)) { throw new InvalidOperationException("The metadata reference has already been added to the project."); } _allMetadataReferences.MultiAdd(fullPath, properties, s_defaultMetadataReferenceProperties); if (_activeBatchScopes > 0) { if (!_metadataReferencesRemovedInBatch.Remove((fullPath, properties))) { _metadataReferencesAddedInBatch.Add((fullPath, properties)); } } else { _workspace.ApplyChangeToWorkspace(w => { var projectReference = _workspace.TryCreateConvertedProjectReference_NoLock(Id, fullPath, properties); if (projectReference != null) { w.OnProjectReferenceAdded(Id, projectReference); } else { var metadataReference = _workspace.FileWatchedReferenceFactory.CreateReferenceAndStartWatchingFile(fullPath, properties); w.OnMetadataReferenceAdded(Id, metadataReference); } }); } } } public bool ContainsMetadataReference(string fullPath, MetadataReferenceProperties properties) { lock (_gate) { return GetPropertiesForMetadataReference(fullPath).Contains(properties); } } /// <summary> /// Returns the properties being used for the current metadata reference added to this project. May return multiple properties if /// the reference has been added multiple times with different properties. /// </summary> public ImmutableArray<MetadataReferenceProperties> GetPropertiesForMetadataReference(string fullPath) { lock (_gate) { return _allMetadataReferences.TryGetValue(fullPath, out var list) ? list : ImmutableArray<MetadataReferenceProperties>.Empty; } } public void RemoveMetadataReference(string fullPath, MetadataReferenceProperties properties) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_gate) { if (!ContainsMetadataReference(fullPath, properties)) { throw new InvalidOperationException("The metadata reference does not exist in this project."); } _allMetadataReferences.MultiRemove(fullPath, properties); if (_activeBatchScopes > 0) { if (!_metadataReferencesAddedInBatch.Remove((fullPath, properties))) { _metadataReferencesRemovedInBatch.Add((fullPath, properties)); } } else { _workspace.ApplyChangeToWorkspace(w => { var projectReference = _workspace.TryRemoveConvertedProjectReference_NoLock(Id, fullPath, properties); // If this was converted to a project reference, we have now recorded the removal -- let's remove it here too if (projectReference != null) { w.OnProjectReferenceRemoved(Id, projectReference); } else { // TODO: find a cleaner way to fetch this var metadataReference = w.CurrentSolution.GetRequiredProject(Id).MetadataReferences.Cast<PortableExecutableReference>() .Single(m => m.FilePath == fullPath && m.Properties == properties); _workspace.FileWatchedReferenceFactory.StopWatchingReference(metadataReference); w.OnMetadataReferenceRemoved(Id, metadataReference); } }); } } } #endregion #region Project Reference Addition/Removal public void AddProjectReference(ProjectReference projectReference) { if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } lock (_gate) { if (ContainsProjectReference(projectReference)) { throw new ArgumentException("The project reference has already been added to the project."); } if (_activeBatchScopes > 0) { if (!_projectReferencesRemovedInBatch.Remove(projectReference)) { _projectReferencesAddedInBatch.Add(projectReference); } } else { _workspace.ApplyChangeToWorkspace(w => w.OnProjectReferenceAdded(Id, projectReference)); } } } public bool ContainsProjectReference(ProjectReference projectReference) { if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } lock (_gate) { if (_projectReferencesRemovedInBatch.Contains(projectReference)) { return false; } if (_projectReferencesAddedInBatch.Contains(projectReference)) { return true; } return _workspace.CurrentSolution.GetRequiredProject(Id).AllProjectReferences.Contains(projectReference); } } public IReadOnlyList<ProjectReference> GetProjectReferences() { lock (_gate) { // If we're not batching, then this is cheap: just fetch from the workspace and we're done var projectReferencesInWorkspace = _workspace.CurrentSolution.GetRequiredProject(Id).AllProjectReferences; if (_activeBatchScopes == 0) { return projectReferencesInWorkspace; } // Not, so we get to compute a new list instead var newList = projectReferencesInWorkspace.ToList(); newList.AddRange(_projectReferencesAddedInBatch); newList.RemoveAll(p => _projectReferencesRemovedInBatch.Contains(p)); return newList; } } public void RemoveProjectReference(ProjectReference projectReference) { if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } lock (_gate) { if (_activeBatchScopes > 0) { if (!_projectReferencesAddedInBatch.Remove(projectReference)) { _projectReferencesRemovedInBatch.Add(projectReference); } } else { _workspace.ApplyChangeToWorkspace(w => w.OnProjectReferenceRemoved(Id, projectReference)); } } } #endregion public void RemoveFromWorkspace() { _documentFileChangeContext.Dispose(); lock (_gate) { // clear tracking to external components foreach (var provider in _eventSubscriptionTracker) { provider.Updated -= OnDynamicFileInfoUpdated; } _eventSubscriptionTracker.Clear(); } IReadOnlyList<MetadataReference>? remainingMetadataReferences = null; _workspace.ApplyChangeToWorkspace(w => { // Acquire the remaining metadata references inside the workspace lock. This is critical // as another project being removed at the same time could result in project to project // references being converted to metadata references (or vice versa) and we might either // miss stopping a file watcher or might end up double-stopping a file watcher. remainingMetadataReferences = w.CurrentSolution.GetRequiredProject(Id).MetadataReferences; w.OnProjectRemoved(Id); }); Contract.ThrowIfNull(remainingMetadataReferences); foreach (PortableExecutableReference reference in remainingMetadataReferences) { _workspace.FileWatchedReferenceFactory.StopWatchingReference(reference); } } /// <summary> /// Adds an additional output path that can be used for automatic conversion of metadata references to P2P references. /// Any projects with metadata references to the path given here will be converted to project-to-project references. /// </summary> public void AddOutputPath(string outputPath) { if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException($"{nameof(outputPath)} isn't a valid path.", nameof(outputPath)); } _workspace.AddProjectOutputPath(Id, outputPath); } /// <summary> /// Removes an additional output path that was added by <see cref="AddOutputPath(string)"/>. /// </summary> public void RemoveOutputPath(string outputPath) { if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException($"{nameof(outputPath)} isn't a valid path.", nameof(outputPath)); } _workspace.RemoveProjectOutputPath(Id, outputPath); } public void ReorderSourceFiles(ImmutableArray<string> filePaths) => _sourceFiles.ReorderFiles(filePaths); /// <summary> /// Clears a list and zeros out the capacity. The lists we use for batching are likely to get large during an initial load, but after /// that point should never get that large again. /// </summary> private static void ClearAndZeroCapacity<T>(List<T> list) { list.Clear(); list.Capacity = 0; } /// <summary> /// Clears a list and zeros out the capacity. The lists we use for batching are likely to get large during an initial load, but after /// that point should never get that large again. /// </summary> private static void ClearAndZeroCapacity<T>(ImmutableArray<T>.Builder list) { list.Clear(); list.Capacity = 0; } /// <summary> /// Helper class to manage collections of source-file like things; this exists just to avoid duplicating all the logic for regular source files /// and additional files. /// </summary> /// <remarks>This class should be free-threaded, and any synchronization is done via <see cref="VisualStudioProject._gate"/>. /// This class is otehrwise free to operate on private members of <see cref="_project"/> if needed.</remarks> private sealed class BatchingDocumentCollection { private readonly VisualStudioProject _project; /// <summary> /// The map of file paths to the underlying <see cref="DocumentId"/>. This document may exist in <see cref="_documentsAddedInBatch"/> or has been /// pushed to the actual workspace. /// </summary> private readonly Dictionary<string, DocumentId> _documentPathsToDocumentIds = new(StringComparer.OrdinalIgnoreCase); /// <summary> /// A map of explicitly-added "always open" <see cref="SourceTextContainer"/> and their associated <see cref="DocumentId"/>. This does not contain /// any regular files that have been open. /// </summary> private IBidirectionalMap<SourceTextContainer, DocumentId> _sourceTextContainersToDocumentIds = BidirectionalMap<SourceTextContainer, DocumentId>.Empty; /// <summary> /// The map of <see cref="DocumentId"/> to <see cref="IDynamicFileInfoProvider"/> whose <see cref="DynamicFileInfo"/> got added into <see cref="Workspace"/> /// </summary> private readonly Dictionary<DocumentId, IDynamicFileInfoProvider> _documentIdToDynamicFileInfoProvider = new(); /// <summary> /// The current list of documents that are to be added in this batch. /// </summary> private readonly ImmutableArray<DocumentInfo>.Builder _documentsAddedInBatch = ImmutableArray.CreateBuilder<DocumentInfo>(); /// <summary> /// The current list of documents that are being removed in this batch. Once the document is in this list, it is no longer in <see cref="_documentPathsToDocumentIds"/>. /// </summary> private readonly List<DocumentId> _documentsRemovedInBatch = new(); /// <summary> /// The current list of document file paths that will be ordered in a batch. /// </summary> private ImmutableList<DocumentId>? _orderedDocumentsInBatch = null; private readonly Func<Solution, DocumentId, bool> _documentAlreadyInWorkspace; private readonly Action<Workspace, DocumentInfo> _documentAddAction; private readonly Action<Workspace, DocumentId> _documentRemoveAction; private readonly Action<Workspace, DocumentId, TextLoader> _documentTextLoaderChangedAction; public BatchingDocumentCollection(VisualStudioProject project, Func<Solution, DocumentId, bool> documentAlreadyInWorkspace, Action<Workspace, DocumentInfo> documentAddAction, Action<Workspace, DocumentId> documentRemoveAction, Action<Workspace, DocumentId, TextLoader> documentTextLoaderChangedAction) { _project = project; _documentAlreadyInWorkspace = documentAlreadyInWorkspace; _documentAddAction = documentAddAction; _documentRemoveAction = documentRemoveAction; _documentTextLoaderChangedAction = documentTextLoaderChangedAction; } public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray<string> folders) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } var documentId = DocumentId.CreateNewId(_project.Id, fullPath); var textLoader = new FileTextLoader(fullPath, defaultEncoding: null); var documentInfo = DocumentInfo.Create( documentId, FileNameUtilities.GetFileName(fullPath), folders: folders.IsDefault ? null : folders, sourceCodeKind: sourceCodeKind, loader: textLoader, filePath: fullPath, isGenerated: false); lock (_project._gate) { if (_documentPathsToDocumentIds.ContainsKey(fullPath)) { throw new ArgumentException($"'{fullPath}' has already been added to this project.", nameof(fullPath)); } // If we have an ordered document ids batch, we need to add the document id to the end of it as well. _orderedDocumentsInBatch = _orderedDocumentsInBatch?.Add(documentId); _documentPathsToDocumentIds.Add(fullPath, documentId); _project._documentFileWatchingTokens.Add(documentId, _project._documentFileChangeContext.EnqueueWatchingFile(fullPath)); if (_project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { _project._workspace.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo)); _project._workspace.QueueCheckForFilesBeingOpen(ImmutableArray.Create(fullPath)); } } return documentId; } public DocumentId AddTextContainer(SourceTextContainer textContainer, string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray<string> folders, bool designTimeOnly, IDocumentServiceProvider? documentServiceProvider) { if (textContainer == null) { throw new ArgumentNullException(nameof(textContainer)); } var documentId = DocumentId.CreateNewId(_project.Id, fullPath); var textLoader = new SourceTextLoader(textContainer, fullPath); var documentInfo = DocumentInfo.Create( documentId, FileNameUtilities.GetFileName(fullPath), folders: folders.NullToEmpty(), sourceCodeKind: sourceCodeKind, loader: textLoader, filePath: fullPath, isGenerated: false, designTimeOnly: designTimeOnly, documentServiceProvider: documentServiceProvider); lock (_project._gate) { if (_sourceTextContainersToDocumentIds.ContainsKey(textContainer)) { throw new ArgumentException($"{nameof(textContainer)} is already added to this project.", nameof(textContainer)); } if (fullPath != null) { if (_documentPathsToDocumentIds.ContainsKey(fullPath)) { throw new ArgumentException($"'{fullPath}' has already been added to this project."); } _documentPathsToDocumentIds.Add(fullPath, documentId); } _sourceTextContainersToDocumentIds = _sourceTextContainersToDocumentIds.Add(textContainer, documentInfo.Id); if (_project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { _project._workspace.ApplyChangeToWorkspace(w => { _project._workspace.AddDocumentToDocumentsNotFromFiles(documentInfo.Id); _documentAddAction(w, documentInfo); w.OnDocumentOpened(documentInfo.Id, textContainer); }); } } return documentId; } public void AddDynamicFile(IDynamicFileInfoProvider fileInfoProvider, DynamicFileInfo fileInfo, ImmutableArray<string> folders) { var documentInfo = CreateDocumentInfoFromFileInfo(fileInfo, folders.NullToEmpty()); // Generally, DocumentInfo.FilePath can be null, but we always have file paths for dynamic files. Contract.ThrowIfNull(documentInfo.FilePath); var documentId = documentInfo.Id; lock (_project._gate) { var filePath = documentInfo.FilePath; if (_documentPathsToDocumentIds.ContainsKey(filePath)) { throw new ArgumentException($"'{filePath}' has already been added to this project.", nameof(filePath)); } // If we have an ordered document ids batch, we need to add the document id to the end of it as well. _orderedDocumentsInBatch = _orderedDocumentsInBatch?.Add(documentId); _documentPathsToDocumentIds.Add(filePath, documentId); _documentIdToDynamicFileInfoProvider.Add(documentId, fileInfoProvider); if (_project._eventSubscriptionTracker.Add(fileInfoProvider)) { // subscribe to the event when we use this provider the first time fileInfoProvider.Updated += _project.OnDynamicFileInfoUpdated; } if (_project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { // right now, assumption is dynamically generated file can never be opened in editor _project._workspace.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo)); } } } public IDynamicFileInfoProvider RemoveDynamicFile(string fullPath) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_project._gate) { if (!_documentPathsToDocumentIds.TryGetValue(fullPath, out var documentId) || !_documentIdToDynamicFileInfoProvider.TryGetValue(documentId, out var fileInfoProvider)) { throw new ArgumentException($"'{fullPath}' is not a dynamic file of this project."); } _documentIdToDynamicFileInfoProvider.Remove(documentId); RemoveFileInternal(documentId, fullPath); return fileInfoProvider; } } public void RemoveFile(string fullPath) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_project._gate) { if (!_documentPathsToDocumentIds.TryGetValue(fullPath, out var documentId)) { throw new ArgumentException($"'{fullPath}' is not a source file of this project."); } _project._documentFileChangeContext.StopWatchingFile(_project._documentFileWatchingTokens[documentId]); _project._documentFileWatchingTokens.Remove(documentId); RemoveFileInternal(documentId, fullPath); } } private void RemoveFileInternal(DocumentId documentId, string fullPath) { _orderedDocumentsInBatch = _orderedDocumentsInBatch?.Remove(documentId); _documentPathsToDocumentIds.Remove(fullPath); // There are two cases: // // 1. This file is actually been pushed to the workspace, and we need to remove it (either // as a part of the active batch or immediately) // 2. It hasn't been pushed yet, but is contained in _documentsAddedInBatch if (_documentAlreadyInWorkspace(_project._workspace.CurrentSolution, documentId)) { if (_project._activeBatchScopes > 0) { _documentsRemovedInBatch.Add(documentId); } else { _project._workspace.ApplyChangeToWorkspace(w => _documentRemoveAction(w, documentId)); } } else { for (var i = 0; i < _documentsAddedInBatch.Count; i++) { if (_documentsAddedInBatch[i].Id == documentId) { _documentsAddedInBatch.RemoveAt(i); break; } } } } public void RemoveTextContainer(SourceTextContainer textContainer) { if (textContainer == null) { throw new ArgumentNullException(nameof(textContainer)); } lock (_project._gate) { if (!_sourceTextContainersToDocumentIds.TryGetValue(textContainer, out var documentId)) { throw new ArgumentException($"{nameof(textContainer)} is not a text container added to this project."); } _sourceTextContainersToDocumentIds = _sourceTextContainersToDocumentIds.RemoveKey(textContainer); // if the TextContainer had a full path provided, remove it from the map. var entry = _documentPathsToDocumentIds.Where(kv => kv.Value == documentId).FirstOrDefault(); if (entry.Key != null) { _documentPathsToDocumentIds.Remove(entry.Key); } // There are two cases: // // 1. This file is actually been pushed to the workspace, and we need to remove it (either // as a part of the active batch or immediately) // 2. It hasn't been pushed yet, but is contained in _documentsAddedInBatch if (_project._workspace.CurrentSolution.GetDocument(documentId) != null) { if (_project._activeBatchScopes > 0) { _documentsRemovedInBatch.Add(documentId); } else { _project._workspace.ApplyChangeToWorkspace(w => { // Just pass null for the filePath, since this document is immediately being removed // anyways -- whatever we set won't really be read since the next change will // come through. // TODO: Can't we just remove the document without closing it? w.OnDocumentClosed(documentId, new SourceTextLoader(textContainer, filePath: null)); _documentRemoveAction(w, documentId); _project._workspace.RemoveDocumentToDocumentsNotFromFiles(documentId); }); } } else { for (var i = 0; i < _documentsAddedInBatch.Count; i++) { if (_documentsAddedInBatch[i].Id == documentId) { _documentsAddedInBatch.RemoveAt(i); break; } } } } } public bool ContainsFile(string fullPath) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } lock (_project._gate) { return _documentPathsToDocumentIds.ContainsKey(fullPath); } } public void ProcessFileChange(string filePath) => ProcessFileChange(filePath, filePath); /// <summary> /// Process file content changes /// </summary> /// <param name="projectSystemFilePath">filepath given from project system</param> /// <param name="workspaceFilePath">filepath used in workspace. it might be different than projectSystemFilePath. ex) dynamic file</param> public void ProcessFileChange(string projectSystemFilePath, string workspaceFilePath) { lock (_project._gate) { if (_documentPathsToDocumentIds.TryGetValue(workspaceFilePath, out var documentId)) { // We create file watching prior to pushing the file to the workspace in batching, so it's // possible we might see a file change notification early. In this case, toss it out. Since // all adds/removals of documents for this project happen under our lock, it's safe to do this // check without taking the main workspace lock if (_documentsAddedInBatch.Any(d => d.Id == documentId)) { return; } _documentIdToDynamicFileInfoProvider.TryGetValue(documentId, out var fileInfoProvider); _project._workspace.ApplyChangeToWorkspace(w => { if (w.IsDocumentOpen(documentId)) { return; } if (fileInfoProvider == null) { var textLoader = new FileTextLoader(projectSystemFilePath, defaultEncoding: null); _documentTextLoaderChangedAction(w, documentId, textLoader); } else { // we do not expect JTF to be used around this code path. and contract of fileInfoProvider is it being real free-threaded // meaning it can't use JTF to go back to UI thread. // so, it is okay for us to call regular ".Result" on a task here. var fileInfo = fileInfoProvider.GetDynamicFileInfoAsync( _project.Id, _project._filePath, projectSystemFilePath, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); // Right now we're only supporting dynamic files as actual source files, so it's OK to call GetDocument here var document = w.CurrentSolution.GetRequiredDocument(documentId); var documentInfo = DocumentInfo.Create( document.Id, document.Name, document.Folders, document.SourceCodeKind, loader: fileInfo.TextLoader, document.FilePath, document.State.Attributes.IsGenerated, document.State.Attributes.DesignTimeOnly, documentServiceProvider: fileInfo.DocumentServiceProvider); w.OnDocumentReloaded(documentInfo); } }); } } } public void ReorderFiles(ImmutableArray<string> filePaths) { if (filePaths.IsEmpty) { throw new ArgumentOutOfRangeException("The specified files are empty.", nameof(filePaths)); } lock (_project._gate) { if (_documentPathsToDocumentIds.Count != filePaths.Length) { throw new ArgumentException("The specified files do not equal the project document count.", nameof(filePaths)); } var documentIds = ImmutableList.CreateBuilder<DocumentId>(); foreach (var filePath in filePaths) { if (_documentPathsToDocumentIds.TryGetValue(filePath, out var documentId)) { documentIds.Add(documentId); } else { throw new InvalidOperationException($"The file '{filePath}' does not exist in the project."); } } if (_project._activeBatchScopes > 0) { _orderedDocumentsInBatch = documentIds.ToImmutable(); } else { _project._workspace.ApplyBatchChangeToWorkspace(solution => { var solutionChanges = new SolutionChangeAccumulator(solution); solutionChanges.UpdateSolutionForProjectAction( _project.Id, solutionChanges.Solution.WithProjectDocumentsOrder(_project.Id, documentIds.ToImmutable())); return solutionChanges; }); } } } internal void UpdateSolutionForBatch( SolutionChangeAccumulator solutionChanges, ImmutableArray<string>.Builder documentFileNamesAdded, List<(DocumentId documentId, SourceTextContainer textContainer)> documentsToOpen, Func<Solution, ImmutableArray<DocumentInfo>, Solution> addDocuments, WorkspaceChangeKind addDocumentChangeKind, Func<Solution, ImmutableArray<DocumentId>, Solution> removeDocuments, WorkspaceChangeKind removeDocumentChangeKind) { // Document adding... solutionChanges.UpdateSolutionForDocumentAction( newSolution: addDocuments(solutionChanges.Solution, _documentsAddedInBatch.ToImmutable()), changeKind: addDocumentChangeKind, documentIds: _documentsAddedInBatch.Select(d => d.Id)); foreach (var documentInfo in _documentsAddedInBatch) { Contract.ThrowIfNull(documentInfo.FilePath, "We shouldn't be adding documents without file paths."); documentFileNamesAdded.Add(documentInfo.FilePath); if (_sourceTextContainersToDocumentIds.TryGetKey(documentInfo.Id, out var textContainer)) { documentsToOpen.Add((documentInfo.Id, textContainer)); } } ClearAndZeroCapacity(_documentsAddedInBatch); // Document removing... solutionChanges.UpdateSolutionForRemovedDocumentAction(removeDocuments(solutionChanges.Solution, _documentsRemovedInBatch.ToImmutableArray()), removeDocumentChangeKind, _documentsRemovedInBatch); ClearAndZeroCapacity(_documentsRemovedInBatch); // Update project's order of documents. if (_orderedDocumentsInBatch != null) { solutionChanges.UpdateSolutionForProjectAction( _project.Id, solutionChanges.Solution.WithProjectDocumentsOrder(_project.Id, _orderedDocumentsInBatch)); _orderedDocumentsInBatch = null; } } private DocumentInfo CreateDocumentInfoFromFileInfo(DynamicFileInfo fileInfo, ImmutableArray<string> folders) { Contract.ThrowIfTrue(folders.IsDefault); // we use this file path for editorconfig. var filePath = fileInfo.FilePath; var name = FileNameUtilities.GetFileName(filePath); var documentId = DocumentId.CreateNewId(_project.Id, filePath); var textLoader = fileInfo.TextLoader; var documentServiceProvider = fileInfo.DocumentServiceProvider; return DocumentInfo.Create( documentId, name, folders: folders, sourceCodeKind: fileInfo.SourceCodeKind, loader: textLoader, filePath: filePath, isGenerated: false, designTimeOnly: true, documentServiceProvider: documentServiceProvider); } private sealed class SourceTextLoader : TextLoader { private readonly SourceTextContainer _textContainer; private readonly string? _filePath; public SourceTextLoader(SourceTextContainer textContainer, string? filePath) { _textContainer = textContainer; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(TextAndVersion.Create(_textContainer.CurrentText, VersionStamp.Create(), _filePath)); } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/CodeAnalysisTest/XmlDocumentationCommentTextReaderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class XmlDocumentationCommentTextReaderTests { [Fact] public void Reader() { char[] buffer = new char[200]; int charsRead; var s = new XmlDocumentationCommentTextReader.Reader(); Assert.Equal(0, s.Position); s.SetText("abc"); charsRead = s.Read(buffer, 0, 200); Assert.Equal(109, charsRead); Assert.Equal( XmlDocumentationCommentTextReader.Reader.RootStart + XmlDocumentationCommentTextReader.Reader.CurrentStart + "abc" + XmlDocumentationCommentTextReader.Reader.CurrentEnd, new string(buffer, 0, charsRead)); charsRead = s.Read(buffer, 0, 10); Assert.Equal(1, 1); Assert.Equal(" ", new string(buffer, 0, charsRead)); s.SetText("hello"); charsRead = s.Read(buffer, 0, 200); Assert.Equal(76, charsRead); Assert.Equal( XmlDocumentationCommentTextReader.Reader.CurrentStart + "hello" + XmlDocumentationCommentTextReader.Reader.CurrentEnd, new string(buffer, 0, charsRead)); s.SetText(""); charsRead = s.Read(buffer, 0, 200); Assert.Equal(71, charsRead); Assert.Equal( XmlDocumentationCommentTextReader.Reader.CurrentStart + "" + XmlDocumentationCommentTextReader.Reader.CurrentEnd, new string(buffer, 0, charsRead)); s.SetText("xxxxxxxxxxxxxxxxxxxxxxxx"); charsRead = s.Read(buffer, 0, 200); Assert.Equal(95, charsRead); Assert.Equal( XmlDocumentationCommentTextReader.Reader.CurrentStart + "xxxxxxxxxxxxxxxxxxxxxxxx" + XmlDocumentationCommentTextReader.Reader.CurrentEnd, new string(buffer, 0, charsRead)); } [Fact] public void XmlValidation() { var reader = new XmlDocumentationCommentTextReader(); Assert.Null(reader.ParseInternal("<a>aaa</a>")); Assert.Null(reader.ParseInternal("<a><b x='goo'></b></a>")); Assert.NotNull(reader.ParseInternal("<a><b x='goo'></a>")); Assert.NotNull(reader.ParseInternal("<a>/a>")); Assert.NotNull(reader.ParseInternal("<a>")); Assert.Null(reader.ParseInternal("<a></a>")); Assert.Null(reader.ParseInternal("")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class XmlDocumentationCommentTextReaderTests { [Fact] public void Reader() { char[] buffer = new char[200]; int charsRead; var s = new XmlDocumentationCommentTextReader.Reader(); Assert.Equal(0, s.Position); s.SetText("abc"); charsRead = s.Read(buffer, 0, 200); Assert.Equal(109, charsRead); Assert.Equal( XmlDocumentationCommentTextReader.Reader.RootStart + XmlDocumentationCommentTextReader.Reader.CurrentStart + "abc" + XmlDocumentationCommentTextReader.Reader.CurrentEnd, new string(buffer, 0, charsRead)); charsRead = s.Read(buffer, 0, 10); Assert.Equal(1, 1); Assert.Equal(" ", new string(buffer, 0, charsRead)); s.SetText("hello"); charsRead = s.Read(buffer, 0, 200); Assert.Equal(76, charsRead); Assert.Equal( XmlDocumentationCommentTextReader.Reader.CurrentStart + "hello" + XmlDocumentationCommentTextReader.Reader.CurrentEnd, new string(buffer, 0, charsRead)); s.SetText(""); charsRead = s.Read(buffer, 0, 200); Assert.Equal(71, charsRead); Assert.Equal( XmlDocumentationCommentTextReader.Reader.CurrentStart + "" + XmlDocumentationCommentTextReader.Reader.CurrentEnd, new string(buffer, 0, charsRead)); s.SetText("xxxxxxxxxxxxxxxxxxxxxxxx"); charsRead = s.Read(buffer, 0, 200); Assert.Equal(95, charsRead); Assert.Equal( XmlDocumentationCommentTextReader.Reader.CurrentStart + "xxxxxxxxxxxxxxxxxxxxxxxx" + XmlDocumentationCommentTextReader.Reader.CurrentEnd, new string(buffer, 0, charsRead)); } [Fact] public void XmlValidation() { var reader = new XmlDocumentationCommentTextReader(); Assert.Null(reader.ParseInternal("<a>aaa</a>")); Assert.Null(reader.ParseInternal("<a><b x='goo'></b></a>")); Assert.NotNull(reader.ParseInternal("<a><b x='goo'></a>")); Assert.NotNull(reader.ParseInternal("<a>/a>")); Assert.NotNull(reader.ParseInternal("<a>")); Assert.Null(reader.ParseInternal("<a></a>")); Assert.Null(reader.ParseInternal("")); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchStatementCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchStatementCodeFixProvider< TSwitchSyntax, TSwitchArmSyntax, TMemberAccessExpression> : AbstractPopulateSwitchCodeFixProvider< ISwitchOperation, TSwitchSyntax, TSwitchArmSyntax, TMemberAccessExpression> where TSwitchSyntax : SyntaxNode where TSwitchArmSyntax : SyntaxNode where TMemberAccessExpression : SyntaxNode { protected AbstractPopulateSwitchStatementCodeFixProvider() : base(IDEDiagnosticIds.PopulateSwitchStatementDiagnosticId) { } protected sealed override void FixOneDiagnostic( Document document, SyntaxEditor editor, SemanticModel semanticModel, bool addCases, bool addDefaultCase, bool onlyOneDiagnostic, bool hasMissingCases, bool hasMissingDefaultCase, TSwitchSyntax switchNode, ISwitchOperation switchOperation) { var newSwitchNode = UpdateSwitchNode( editor, semanticModel, addCases, addDefaultCase, hasMissingCases, hasMissingDefaultCase, switchNode, switchOperation).WithAdditionalAnnotations(Formatter.Annotation); if (onlyOneDiagnostic) { // If we're only fixing up one issue in this document, then also make sure we // didn't cause any braces to be imbalanced when we added members to the switch. // Note: i'm only doing this for the single case because it feels too complex // to try to support this during fix-all. var root = editor.OriginalRoot; AddMissingBraces(document, ref root, ref switchNode); var newRoot = root.ReplaceNode(switchNode, newSwitchNode); editor.ReplaceNode(editor.OriginalRoot, newRoot); } else { editor.ReplaceNode(switchNode, newSwitchNode); } } protected sealed override ITypeSymbol GetSwitchType(ISwitchOperation switchOperation) => switchOperation.Value.Type ?? throw ExceptionUtilities.Unreachable; protected sealed override ICollection<ISymbol> GetMissingEnumMembers(ISwitchOperation switchOperation) => PopulateSwitchStatementHelpers.GetMissingEnumMembers(switchOperation); protected sealed override TSwitchSyntax InsertSwitchArms(SyntaxGenerator generator, TSwitchSyntax switchNode, int insertLocation, List<TSwitchArmSyntax> newArms) => (TSwitchSyntax)generator.InsertSwitchSections(switchNode, insertLocation, newArms); protected sealed override TSwitchArmSyntax CreateDefaultSwitchArm(SyntaxGenerator generator, Compilation compilation) => (TSwitchArmSyntax)generator.DefaultSwitchSection(new[] { generator.ExitSwitchStatement() }); protected sealed override TSwitchArmSyntax CreateSwitchArm(SyntaxGenerator generator, Compilation compilation, TMemberAccessExpression caseLabel) => (TSwitchArmSyntax)generator.SwitchSection(caseLabel, new[] { generator.ExitSwitchStatement() }); protected sealed override int InsertPosition(ISwitchOperation switchStatement) { // If the last section has a default label, then we want to be above that. // Otherwise, we just get inserted at the end. var cases = switchStatement.Cases; if (cases.Length > 0) { var lastCase = cases.Last(); if (lastCase.Clauses.Any(c => c.CaseKind == CaseKind.Default)) { return cases.Length - 1; } } return cases.Length; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchStatementCodeFixProvider< TSwitchSyntax, TSwitchArmSyntax, TMemberAccessExpression> : AbstractPopulateSwitchCodeFixProvider< ISwitchOperation, TSwitchSyntax, TSwitchArmSyntax, TMemberAccessExpression> where TSwitchSyntax : SyntaxNode where TSwitchArmSyntax : SyntaxNode where TMemberAccessExpression : SyntaxNode { protected AbstractPopulateSwitchStatementCodeFixProvider() : base(IDEDiagnosticIds.PopulateSwitchStatementDiagnosticId) { } protected sealed override void FixOneDiagnostic( Document document, SyntaxEditor editor, SemanticModel semanticModel, bool addCases, bool addDefaultCase, bool onlyOneDiagnostic, bool hasMissingCases, bool hasMissingDefaultCase, TSwitchSyntax switchNode, ISwitchOperation switchOperation) { var newSwitchNode = UpdateSwitchNode( editor, semanticModel, addCases, addDefaultCase, hasMissingCases, hasMissingDefaultCase, switchNode, switchOperation).WithAdditionalAnnotations(Formatter.Annotation); if (onlyOneDiagnostic) { // If we're only fixing up one issue in this document, then also make sure we // didn't cause any braces to be imbalanced when we added members to the switch. // Note: i'm only doing this for the single case because it feels too complex // to try to support this during fix-all. var root = editor.OriginalRoot; AddMissingBraces(document, ref root, ref switchNode); var newRoot = root.ReplaceNode(switchNode, newSwitchNode); editor.ReplaceNode(editor.OriginalRoot, newRoot); } else { editor.ReplaceNode(switchNode, newSwitchNode); } } protected sealed override ITypeSymbol GetSwitchType(ISwitchOperation switchOperation) => switchOperation.Value.Type ?? throw ExceptionUtilities.Unreachable; protected sealed override ICollection<ISymbol> GetMissingEnumMembers(ISwitchOperation switchOperation) => PopulateSwitchStatementHelpers.GetMissingEnumMembers(switchOperation); protected sealed override TSwitchSyntax InsertSwitchArms(SyntaxGenerator generator, TSwitchSyntax switchNode, int insertLocation, List<TSwitchArmSyntax> newArms) => (TSwitchSyntax)generator.InsertSwitchSections(switchNode, insertLocation, newArms); protected sealed override TSwitchArmSyntax CreateDefaultSwitchArm(SyntaxGenerator generator, Compilation compilation) => (TSwitchArmSyntax)generator.DefaultSwitchSection(new[] { generator.ExitSwitchStatement() }); protected sealed override TSwitchArmSyntax CreateSwitchArm(SyntaxGenerator generator, Compilation compilation, TMemberAccessExpression caseLabel) => (TSwitchArmSyntax)generator.SwitchSection(caseLabel, new[] { generator.ExitSwitchStatement() }); protected sealed override int InsertPosition(ISwitchOperation switchStatement) { // If the last section has a default label, then we want to be above that. // Otherwise, we just get inserted at the end. var cases = switchStatement.Cases; if (cases.Length > 0) { var lastCase = cases.Last(); if (lastCase.Clauses.Any(c => c.CaseKind == CaseKind.Default)) { return cases.Length - 1; } } return cases.Length; } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Features/Core/Portable/AddImport/SymbolReferenceFinder_PackageAssemblySearch.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { internal async Task FindNugetOrReferenceAssemblyReferencesAsync( ArrayBuilder<Reference> allReferences, CancellationToken cancellationToken) { if (allReferences.Count > 0) { // Only do this if none of the project or metadata searches produced // any results. We always consider source and local metadata to be // better than any NuGet/assembly-reference results. return; } if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out _, out _); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: cancellationToken)) { return; } await FindNugetOrReferenceAssemblyTypeReferencesAsync( allReferences, nameNode, name, arity, inAttributeContext, cancellationToken).ConfigureAwait(false); } private async Task FindNugetOrReferenceAssemblyTypeReferencesAsync( ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, string name, int arity, bool inAttributeContext, CancellationToken cancellationToken) { if (arity == 0 && inAttributeContext) { await FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync( allReferences, nameNode, name + AttributeSuffix, arity, isAttributeSearch: true, cancellationToken: cancellationToken).ConfigureAwait(false); } await FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync( allReferences, nameNode, name, arity, isAttributeSearch: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync( ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, string name, int arity, bool isAttributeSearch, CancellationToken cancellationToken) { if (_searchReferenceAssemblies) { cancellationToken.ThrowIfCancellationRequested(); await FindReferenceAssemblyTypeReferencesAsync( allReferences, nameNode, name, arity, isAttributeSearch, cancellationToken).ConfigureAwait(false); } var packageSources = PackageSourceHelper.GetPackageSources(_packageSources); foreach (var (sourceName, sourceUrl) in packageSources) { cancellationToken.ThrowIfCancellationRequested(); await FindNugetTypeReferencesAsync( sourceName, sourceUrl, allReferences, nameNode, name, arity, isAttributeSearch, cancellationToken).ConfigureAwait(false); } } private async Task FindReferenceAssemblyTypeReferencesAsync( ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, string name, int arity, bool isAttributeSearch, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var results = await _symbolSearchService.FindReferenceAssembliesWithTypeAsync( name, arity, cancellationToken).ConfigureAwait(false); var project = _document.Project; foreach (var result in results) { cancellationToken.ThrowIfCancellationRequested(); await HandleReferenceAssemblyReferenceAsync( allReferences, nameNode, project, isAttributeSearch, result, weight: allReferences.Count, cancellationToken: cancellationToken).ConfigureAwait(false); } } private async Task FindNugetTypeReferencesAsync( string sourceName, string sourceUrl, ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, string name, int arity, bool isAttributeSearch, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var results = await _symbolSearchService.FindPackagesWithTypeAsync( sourceName, name, arity, cancellationToken).ConfigureAwait(false); foreach (var result in results) { cancellationToken.ThrowIfCancellationRequested(); HandleNugetReference( sourceUrl, allReferences, nameNode, isAttributeSearch, result, weight: allReferences.Count); } } private async Task HandleReferenceAssemblyReferenceAsync( ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, Project project, bool isAttributeSearch, ReferenceAssemblyWithTypeResult result, int weight, CancellationToken cancellationToken) { foreach (var reference in project.MetadataReferences) { cancellationToken.ThrowIfCancellationRequested(); var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var assemblySymbol = compilation.GetAssemblyOrModuleSymbol(reference) as IAssemblySymbol; if (assemblySymbol?.Name == result.AssemblyName) { // Project already has a reference to an assembly with this name. return; } } var desiredName = GetDesiredName(isAttributeSearch, result.TypeName); allReferences.Add(new AssemblyReference( _owner, new SearchResult(desiredName, nameNode, result.ContainingNamespaceNames.ToReadOnlyList(), weight), result)); } private void HandleNugetReference( string source, ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, bool isAttributeSearch, PackageWithTypeResult result, int weight) { var desiredName = GetDesiredName(isAttributeSearch, result.TypeName); allReferences.Add(new PackageReference(_owner, new SearchResult(desiredName, nameNode, result.ContainingNamespaceNames.ToReadOnlyList(), weight), source, result.PackageName, result.Version)); } private static string? GetDesiredName(bool isAttributeSearch, string typeName) => isAttributeSearch ? typeName.GetWithoutAttributeSuffix(isCaseSensitive: false) : typeName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { internal async Task FindNugetOrReferenceAssemblyReferencesAsync( ArrayBuilder<Reference> allReferences, CancellationToken cancellationToken) { if (allReferences.Count > 0) { // Only do this if none of the project or metadata searches produced // any results. We always consider source and local metadata to be // better than any NuGet/assembly-reference results. return; } if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out _, out _); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: cancellationToken)) { return; } await FindNugetOrReferenceAssemblyTypeReferencesAsync( allReferences, nameNode, name, arity, inAttributeContext, cancellationToken).ConfigureAwait(false); } private async Task FindNugetOrReferenceAssemblyTypeReferencesAsync( ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, string name, int arity, bool inAttributeContext, CancellationToken cancellationToken) { if (arity == 0 && inAttributeContext) { await FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync( allReferences, nameNode, name + AttributeSuffix, arity, isAttributeSearch: true, cancellationToken: cancellationToken).ConfigureAwait(false); } await FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync( allReferences, nameNode, name, arity, isAttributeSearch: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync( ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, string name, int arity, bool isAttributeSearch, CancellationToken cancellationToken) { if (_searchReferenceAssemblies) { cancellationToken.ThrowIfCancellationRequested(); await FindReferenceAssemblyTypeReferencesAsync( allReferences, nameNode, name, arity, isAttributeSearch, cancellationToken).ConfigureAwait(false); } var packageSources = PackageSourceHelper.GetPackageSources(_packageSources); foreach (var (sourceName, sourceUrl) in packageSources) { cancellationToken.ThrowIfCancellationRequested(); await FindNugetTypeReferencesAsync( sourceName, sourceUrl, allReferences, nameNode, name, arity, isAttributeSearch, cancellationToken).ConfigureAwait(false); } } private async Task FindReferenceAssemblyTypeReferencesAsync( ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, string name, int arity, bool isAttributeSearch, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var results = await _symbolSearchService.FindReferenceAssembliesWithTypeAsync( name, arity, cancellationToken).ConfigureAwait(false); var project = _document.Project; foreach (var result in results) { cancellationToken.ThrowIfCancellationRequested(); await HandleReferenceAssemblyReferenceAsync( allReferences, nameNode, project, isAttributeSearch, result, weight: allReferences.Count, cancellationToken: cancellationToken).ConfigureAwait(false); } } private async Task FindNugetTypeReferencesAsync( string sourceName, string sourceUrl, ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, string name, int arity, bool isAttributeSearch, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var results = await _symbolSearchService.FindPackagesWithTypeAsync( sourceName, name, arity, cancellationToken).ConfigureAwait(false); foreach (var result in results) { cancellationToken.ThrowIfCancellationRequested(); HandleNugetReference( sourceUrl, allReferences, nameNode, isAttributeSearch, result, weight: allReferences.Count); } } private async Task HandleReferenceAssemblyReferenceAsync( ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, Project project, bool isAttributeSearch, ReferenceAssemblyWithTypeResult result, int weight, CancellationToken cancellationToken) { foreach (var reference in project.MetadataReferences) { cancellationToken.ThrowIfCancellationRequested(); var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var assemblySymbol = compilation.GetAssemblyOrModuleSymbol(reference) as IAssemblySymbol; if (assemblySymbol?.Name == result.AssemblyName) { // Project already has a reference to an assembly with this name. return; } } var desiredName = GetDesiredName(isAttributeSearch, result.TypeName); allReferences.Add(new AssemblyReference( _owner, new SearchResult(desiredName, nameNode, result.ContainingNamespaceNames.ToReadOnlyList(), weight), result)); } private void HandleNugetReference( string source, ArrayBuilder<Reference> allReferences, TSimpleNameSyntax nameNode, bool isAttributeSearch, PackageWithTypeResult result, int weight) { var desiredName = GetDesiredName(isAttributeSearch, result.TypeName); allReferences.Add(new PackageReference(_owner, new SearchResult(desiredName, nameNode, result.ContainingNamespaceNames.ToReadOnlyList(), weight), source, result.PackageName, result.Version)); } private static string? GetDesiredName(bool isAttributeSearch, string typeName) => isAttributeSearch ? typeName.GetWithoutAttributeSuffix(isCaseSensitive: false) : typeName; } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Features/Core/Portable/RQName/Nodes/RQArrayType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQArrayType : RQArrayOrPointerType { public readonly int Rank; public RQArrayType(int rank, RQType elementType) : base(elementType) { Rank = rank; } public override SimpleTreeNode ToSimpleTree() { var rankNode = new SimpleLeafNode(Rank.ToString()); return new SimpleGroupNode(RQNameStrings.Array, rankNode, ElementType.ToSimpleTree()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQArrayType : RQArrayOrPointerType { public readonly int Rank; public RQArrayType(int rank, RQType elementType) : base(elementType) { Rank = rank; } public override SimpleTreeNode ToSimpleTree() { var rankNode = new SimpleLeafNode(Rank.ToString()); return new SimpleGroupNode(RQNameStrings.Array, rankNode, ElementType.ToSimpleTree()); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/Core/Portable/InternalUtilities/SharedStopwatch.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Roslyn.Utilities { internal readonly struct SharedStopwatch { private static readonly Stopwatch s_stopwatch = Stopwatch.StartNew(); private readonly TimeSpan _started; private SharedStopwatch(TimeSpan started) { _started = started; } public TimeSpan Elapsed => s_stopwatch.Elapsed - _started; public static SharedStopwatch StartNew() => new SharedStopwatch(s_stopwatch.Elapsed); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Roslyn.Utilities { internal readonly struct SharedStopwatch { private static readonly Stopwatch s_stopwatch = Stopwatch.StartNew(); private readonly TimeSpan _started; private SharedStopwatch(TimeSpan started) { _started = started; } public TimeSpan Elapsed => s_stopwatch.Elapsed - _started; public static SharedStopwatch StartNew() => new SharedStopwatch(s_stopwatch.Elapsed); } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis.CodeStyle; namespace Microsoft.CodeAnalysis.Options { internal static class EditorConfigStorageLocation { public static EditorConfigStorageLocation<bool> ForBoolOption(string keyName) => new(keyName, s_parseBool, s_getBoolEditorConfigStringForValue); public static EditorConfigStorageLocation<int> ForInt32Option(string keyName) => new(keyName, s_parseInt32, s_getInt32EditorConfigStringForValue); public static EditorConfigStorageLocation<string> ForStringOption(string keyName, string emptyStringRepresentation) => new(keyName, s_parseString, (string value) => string.IsNullOrEmpty(value) ? emptyStringRepresentation : s_getStringEditorConfigStringForValue(value)); public static EditorConfigStorageLocation<CodeStyleOption2<bool>> ForBoolCodeStyleOption(string keyName, CodeStyleOption2<bool> defaultValue) => new(keyName, str => ParseBoolCodeStyleOption(str, defaultValue), value => GetBoolCodeStyleOptionEditorConfigStringForValue(value, defaultValue)); public static EditorConfigStorageLocation<CodeStyleOption2<string>> ForStringCodeStyleOption(string keyName, CodeStyleOption2<string> defaultValue) => new(keyName, str => ParseStringCodeStyleOption(str, defaultValue), value => GetStringCodeStyleOptionEditorConfigStringForValue(value, defaultValue)); private static readonly Func<string, Optional<bool>> s_parseBool = ParseBool; private static Optional<bool> ParseBool(string str) => bool.TryParse(str, out var result) ? result : new Optional<bool>(); private static readonly Func<bool, string> s_getBoolEditorConfigStringForValue = GetBoolEditorConfigStringForValue; private static string GetBoolEditorConfigStringForValue(bool value) => value.ToString().ToLowerInvariant(); private static readonly Func<string, Optional<int>> s_parseInt32 = ParseInt32; private static Optional<int> ParseInt32(string str) => int.TryParse(str, out var result) ? result : new Optional<int>(); private static readonly Func<string, Optional<string>> s_parseString = ParseString; private static Optional<string> ParseString(string str) { if (str.Equals("unset", StringComparison.Ordinal)) { return default; } str ??= ""; return str.Replace("\\r", "\r").Replace("\\n", "\n"); } private static readonly Func<int, string> s_getInt32EditorConfigStringForValue = GetInt32EditorConfigStringForValue; private static string GetInt32EditorConfigStringForValue(int value) => value.ToString().ToLowerInvariant(); private static readonly Func<string, string> s_getStringEditorConfigStringForValue = GetStringEditorConfigStringForValue; private static string GetStringEditorConfigStringForValue(string value) => value.ToString().Replace("\r", "\\r").Replace("\n", "\\n"); private static Optional<CodeStyleOption2<bool>> ParseBoolCodeStyleOption(string str, CodeStyleOption2<bool> defaultValue) => CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(str, defaultValue, out var result) ? result : new Optional<CodeStyleOption2<bool>>(); private static string GetBoolCodeStyleOptionEditorConfigStringForValue(CodeStyleOption2<bool> value, CodeStyleOption2<bool> defaultValue) => $"{(value.Value ? "true" : "false")}{CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue)}"; private static Optional<CodeStyleOption2<string>> ParseStringCodeStyleOption(string str, CodeStyleOption2<string> defaultValue) => CodeStyleHelpers.TryParseStringEditorConfigCodeStyleOption(str, defaultValue, out var result) ? result : new Optional<CodeStyleOption2<string>>(); private static string GetStringCodeStyleOptionEditorConfigStringForValue(CodeStyleOption2<string> value, CodeStyleOption2<string> defaultValue) => $"{value.Value.ToLowerInvariant()}{CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue)}"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis.CodeStyle; namespace Microsoft.CodeAnalysis.Options { internal static class EditorConfigStorageLocation { public static EditorConfigStorageLocation<bool> ForBoolOption(string keyName) => new(keyName, s_parseBool, s_getBoolEditorConfigStringForValue); public static EditorConfigStorageLocation<int> ForInt32Option(string keyName) => new(keyName, s_parseInt32, s_getInt32EditorConfigStringForValue); public static EditorConfigStorageLocation<string> ForStringOption(string keyName, string emptyStringRepresentation) => new(keyName, s_parseString, (string value) => string.IsNullOrEmpty(value) ? emptyStringRepresentation : s_getStringEditorConfigStringForValue(value)); public static EditorConfigStorageLocation<CodeStyleOption2<bool>> ForBoolCodeStyleOption(string keyName, CodeStyleOption2<bool> defaultValue) => new(keyName, str => ParseBoolCodeStyleOption(str, defaultValue), value => GetBoolCodeStyleOptionEditorConfigStringForValue(value, defaultValue)); public static EditorConfigStorageLocation<CodeStyleOption2<string>> ForStringCodeStyleOption(string keyName, CodeStyleOption2<string> defaultValue) => new(keyName, str => ParseStringCodeStyleOption(str, defaultValue), value => GetStringCodeStyleOptionEditorConfigStringForValue(value, defaultValue)); private static readonly Func<string, Optional<bool>> s_parseBool = ParseBool; private static Optional<bool> ParseBool(string str) => bool.TryParse(str, out var result) ? result : new Optional<bool>(); private static readonly Func<bool, string> s_getBoolEditorConfigStringForValue = GetBoolEditorConfigStringForValue; private static string GetBoolEditorConfigStringForValue(bool value) => value.ToString().ToLowerInvariant(); private static readonly Func<string, Optional<int>> s_parseInt32 = ParseInt32; private static Optional<int> ParseInt32(string str) => int.TryParse(str, out var result) ? result : new Optional<int>(); private static readonly Func<string, Optional<string>> s_parseString = ParseString; private static Optional<string> ParseString(string str) { if (str.Equals("unset", StringComparison.Ordinal)) { return default; } str ??= ""; return str.Replace("\\r", "\r").Replace("\\n", "\n"); } private static readonly Func<int, string> s_getInt32EditorConfigStringForValue = GetInt32EditorConfigStringForValue; private static string GetInt32EditorConfigStringForValue(int value) => value.ToString().ToLowerInvariant(); private static readonly Func<string, string> s_getStringEditorConfigStringForValue = GetStringEditorConfigStringForValue; private static string GetStringEditorConfigStringForValue(string value) => value.ToString().Replace("\r", "\\r").Replace("\n", "\\n"); private static Optional<CodeStyleOption2<bool>> ParseBoolCodeStyleOption(string str, CodeStyleOption2<bool> defaultValue) => CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(str, defaultValue, out var result) ? result : new Optional<CodeStyleOption2<bool>>(); private static string GetBoolCodeStyleOptionEditorConfigStringForValue(CodeStyleOption2<bool> value, CodeStyleOption2<bool> defaultValue) => $"{(value.Value ? "true" : "false")}{CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue)}"; private static Optional<CodeStyleOption2<string>> ParseStringCodeStyleOption(string str, CodeStyleOption2<string> defaultValue) => CodeStyleHelpers.TryParseStringEditorConfigCodeStyleOption(str, defaultValue, out var result) ? result : new Optional<CodeStyleOption2<string>>(); private static string GetStringCodeStyleOptionEditorConfigStringForValue(CodeStyleOption2<string> value, CodeStyleOption2<string> defaultValue) => $"{value.Value.ToLowerInvariant()}{CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue)}"; } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/FileBannerFacts/AbstractFileBannerFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract class AbstractFileBannerFacts : IFileBannerFacts { // Matches the following: // // (whitespace* newline)+ private readonly Matcher<SyntaxTrivia> _oneOrMoreBlankLines; // Matches the following: // // (whitespace* (single-comment|multi-comment) whitespace* newline)+ OneOrMoreBlankLines private readonly Matcher<SyntaxTrivia> _bannerMatcher; // Used to match the following: // // <start-of-file> (whitespace* (single-comment|multi-comment) whitespace* newline)+ blankLine* private readonly Matcher<SyntaxTrivia> _fileBannerMatcher; protected AbstractFileBannerFacts() { var whitespace = Matcher.Repeat( Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsWhitespaceTrivia, "\\b")); var endOfLine = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsEndOfLineTrivia, "\\n"); var singleBlankLine = Matcher.Sequence(whitespace, endOfLine); var shebangComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsShebangDirectiveTrivia, "#!"); var singleLineComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsSingleLineCommentTrivia, "//"); var multiLineComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsMultiLineCommentTrivia, "/**/"); var singleLineDocumentationComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsSingleLineDocCommentTrivia, "///"); var multiLineDocumentationComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsMultiLineDocCommentTrivia, "/** */"); var anyCommentMatcher = Matcher.Choice(shebangComment, singleLineComment, multiLineComment, singleLineDocumentationComment, multiLineDocumentationComment); var commentLine = Matcher.Sequence(whitespace, anyCommentMatcher, whitespace, endOfLine); _oneOrMoreBlankLines = Matcher.OneOrMore(singleBlankLine); _bannerMatcher = Matcher.Sequence( Matcher.OneOrMore(commentLine), _oneOrMoreBlankLines); _fileBannerMatcher = Matcher.Sequence( Matcher.OneOrMore(commentLine), Matcher.Repeat(singleBlankLine)); } protected abstract ISyntaxFacts SyntaxFacts { get; } protected abstract IDocumentationCommentService DocumentationCommentService { get; } public string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int bannerLength, CancellationToken cancellationToken) => DocumentationCommentService.GetBannerText(documentationCommentTriviaSyntax, bannerLength, cancellationToken); public ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node) => GetLeadingBlankLines<SyntaxNode>(node); public ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { GetNodeWithoutLeadingBlankLines(node, out var blankLines); return blankLines; } public TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { return GetNodeWithoutLeadingBlankLines(node, out _); } public TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>( TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode { var leadingTriviaToKeep = new List<SyntaxTrivia>(node.GetLeadingTrivia()); var index = 0; _oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index); strippedTrivia = leadingTriviaToKeep.Take(index).ToImmutableArray(); return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index)); } public ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out var leadingTrivia); return leadingTrivia; } public TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>( TSyntaxNode node) where TSyntaxNode : SyntaxNode { return GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out _); } public TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>( TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode { var leadingTrivia = node.GetLeadingTrivia(); // Rules for stripping trivia: // 1) If there is a pp directive, then it (and all preceding trivia) *must* be stripped. // This rule supersedes all other rules. // 2) If there is a doc comment, it cannot be stripped. Even if there is a doc comment, // followed by 5 new lines, then the doc comment still must stay with the node. This // rule does *not* supersede rule 1. // 3) Single line comments in a group (i.e. with no blank lines between them) belong to // the node *iff* there is no blank line between it and the following trivia. List<SyntaxTrivia> leadingTriviaToStrip, leadingTriviaToKeep; var ppIndex = -1; for (var i = leadingTrivia.Count - 1; i >= 0; i--) { if (this.SyntaxFacts.IsPreprocessorDirective(leadingTrivia[i])) { ppIndex = i; break; } } if (ppIndex != -1) { // We have a pp directive. it (and all previous trivia) must be stripped. leadingTriviaToStrip = new List<SyntaxTrivia>(leadingTrivia.Take(ppIndex + 1)); leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia.Skip(ppIndex + 1)); } else { leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia); leadingTriviaToStrip = new List<SyntaxTrivia>(); } // Now, consume as many banners as we can. s_fileBannerMatcher will only be matched at // the start of the file. var index = 0; while ( _oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index) || _bannerMatcher.TryMatch(leadingTriviaToKeep, ref index) || (node.FullSpan.Start == 0 && _fileBannerMatcher.TryMatch(leadingTriviaToKeep, ref index))) { } leadingTriviaToStrip.AddRange(leadingTriviaToKeep.Take(index)); strippedTrivia = leadingTriviaToStrip.ToImmutableArray(); return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index)); } public ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root) { Debug.Assert(root.FullSpan.Start == 0); return GetFileBanner(root.GetFirstToken(includeZeroWidth: true)); } public ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken) { Debug.Assert(firstToken.FullSpan.Start == 0); var leadingTrivia = firstToken.LeadingTrivia; var index = 0; _fileBannerMatcher.TryMatch(leadingTrivia.ToList(), ref index); return ImmutableArray.CreateRange(leadingTrivia.Take(index)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract class AbstractFileBannerFacts : IFileBannerFacts { // Matches the following: // // (whitespace* newline)+ private readonly Matcher<SyntaxTrivia> _oneOrMoreBlankLines; // Matches the following: // // (whitespace* (single-comment|multi-comment) whitespace* newline)+ OneOrMoreBlankLines private readonly Matcher<SyntaxTrivia> _bannerMatcher; // Used to match the following: // // <start-of-file> (whitespace* (single-comment|multi-comment) whitespace* newline)+ blankLine* private readonly Matcher<SyntaxTrivia> _fileBannerMatcher; protected AbstractFileBannerFacts() { var whitespace = Matcher.Repeat( Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsWhitespaceTrivia, "\\b")); var endOfLine = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsEndOfLineTrivia, "\\n"); var singleBlankLine = Matcher.Sequence(whitespace, endOfLine); var shebangComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsShebangDirectiveTrivia, "#!"); var singleLineComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsSingleLineCommentTrivia, "//"); var multiLineComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsMultiLineCommentTrivia, "/**/"); var singleLineDocumentationComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsSingleLineDocCommentTrivia, "///"); var multiLineDocumentationComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsMultiLineDocCommentTrivia, "/** */"); var anyCommentMatcher = Matcher.Choice(shebangComment, singleLineComment, multiLineComment, singleLineDocumentationComment, multiLineDocumentationComment); var commentLine = Matcher.Sequence(whitespace, anyCommentMatcher, whitespace, endOfLine); _oneOrMoreBlankLines = Matcher.OneOrMore(singleBlankLine); _bannerMatcher = Matcher.Sequence( Matcher.OneOrMore(commentLine), _oneOrMoreBlankLines); _fileBannerMatcher = Matcher.Sequence( Matcher.OneOrMore(commentLine), Matcher.Repeat(singleBlankLine)); } protected abstract ISyntaxFacts SyntaxFacts { get; } protected abstract IDocumentationCommentService DocumentationCommentService { get; } public string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int bannerLength, CancellationToken cancellationToken) => DocumentationCommentService.GetBannerText(documentationCommentTriviaSyntax, bannerLength, cancellationToken); public ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node) => GetLeadingBlankLines<SyntaxNode>(node); public ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { GetNodeWithoutLeadingBlankLines(node, out var blankLines); return blankLines; } public TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { return GetNodeWithoutLeadingBlankLines(node, out _); } public TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>( TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode { var leadingTriviaToKeep = new List<SyntaxTrivia>(node.GetLeadingTrivia()); var index = 0; _oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index); strippedTrivia = leadingTriviaToKeep.Take(index).ToImmutableArray(); return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index)); } public ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out var leadingTrivia); return leadingTrivia; } public TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>( TSyntaxNode node) where TSyntaxNode : SyntaxNode { return GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out _); } public TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>( TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode { var leadingTrivia = node.GetLeadingTrivia(); // Rules for stripping trivia: // 1) If there is a pp directive, then it (and all preceding trivia) *must* be stripped. // This rule supersedes all other rules. // 2) If there is a doc comment, it cannot be stripped. Even if there is a doc comment, // followed by 5 new lines, then the doc comment still must stay with the node. This // rule does *not* supersede rule 1. // 3) Single line comments in a group (i.e. with no blank lines between them) belong to // the node *iff* there is no blank line between it and the following trivia. List<SyntaxTrivia> leadingTriviaToStrip, leadingTriviaToKeep; var ppIndex = -1; for (var i = leadingTrivia.Count - 1; i >= 0; i--) { if (this.SyntaxFacts.IsPreprocessorDirective(leadingTrivia[i])) { ppIndex = i; break; } } if (ppIndex != -1) { // We have a pp directive. it (and all previous trivia) must be stripped. leadingTriviaToStrip = new List<SyntaxTrivia>(leadingTrivia.Take(ppIndex + 1)); leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia.Skip(ppIndex + 1)); } else { leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia); leadingTriviaToStrip = new List<SyntaxTrivia>(); } // Now, consume as many banners as we can. s_fileBannerMatcher will only be matched at // the start of the file. var index = 0; while ( _oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index) || _bannerMatcher.TryMatch(leadingTriviaToKeep, ref index) || (node.FullSpan.Start == 0 && _fileBannerMatcher.TryMatch(leadingTriviaToKeep, ref index))) { } leadingTriviaToStrip.AddRange(leadingTriviaToKeep.Take(index)); strippedTrivia = leadingTriviaToStrip.ToImmutableArray(); return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index)); } public ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root) { Debug.Assert(root.FullSpan.Start == 0); return GetFileBanner(root.GetFirstToken(includeZeroWidth: true)); } public ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken) { Debug.Assert(firstToken.FullSpan.Start == 0); var leadingTrivia = firstToken.LeadingTrivia; var index = 0; _fileBannerMatcher.TryMatch(leadingTrivia.ToList(), ref index); return ImmutableArray.CreateRange(leadingTrivia.Take(index)); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.AddMetadataReferenceUndoUnit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddMetadataReferenceUndoUnit : AbstractAddRemoveUndoUnit { private readonly string _filePath; public AddMetadataReferenceUndoUnit( VisualStudioWorkspaceImpl workspace, ProjectId fromProjectId, string filePath) : base(workspace, fromProjectId) { _filePath = filePath; } public override void Do(IOleUndoManager pUndoManager) { var currentSolution = Workspace.CurrentSolution; var fromProject = currentSolution.GetProject(FromProjectId); if (fromProject != null) { var reference = fromProject.MetadataReferences.OfType<PortableExecutableReference>() .FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(p.FilePath, _filePath)); if (reference == null) { try { reference = MetadataReference.CreateFromFile(_filePath); } catch (IOException) { return; } var updatedProject = fromProject.AddMetadataReference(reference); Workspace.TryApplyChanges(updatedProject.Solution); } } } public override void GetDescription(out string pBstr) { pBstr = string.Format(FeaturesResources.Add_reference_to_0, Path.GetFileName(_filePath)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddMetadataReferenceUndoUnit : AbstractAddRemoveUndoUnit { private readonly string _filePath; public AddMetadataReferenceUndoUnit( VisualStudioWorkspaceImpl workspace, ProjectId fromProjectId, string filePath) : base(workspace, fromProjectId) { _filePath = filePath; } public override void Do(IOleUndoManager pUndoManager) { var currentSolution = Workspace.CurrentSolution; var fromProject = currentSolution.GetProject(FromProjectId); if (fromProject != null) { var reference = fromProject.MetadataReferences.OfType<PortableExecutableReference>() .FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(p.FilePath, _filePath)); if (reference == null) { try { reference = MetadataReference.CreateFromFile(_filePath); } catch (IOException) { return; } var updatedProject = fromProject.AddMetadataReference(reference); Workspace.TryApplyChanges(updatedProject.Solution); } } } public override void GetDescription(out string pBstr) { pBstr = string.Format(FeaturesResources.Add_reference_to_0, Path.GetFileName(_filePath)); } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/TestUtilities/Extensions/XElementExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Xml.Linq; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public static class XElementExtensions { public static string NormalizedValue(this XElement element) => element.Value.Replace("\n", "\r\n"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Xml.Linq; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public static class XElementExtensions { public static string NormalizedValue(this XElement element) => element.Value.Replace("\n", "\r\n"); } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/VisualStudio/Core/Def/Implementation/Venus/CodeBlockEnumerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.VisualStudio; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// An implementation of IVsEnumCodeBlocks used in the implementation of /// IVsContainedCode.EnumOriginalCodeBlocks for each language's Venus interop layer. /// </summary> internal class CodeBlockEnumerator : IVsEnumCodeBlocks { private readonly IList<TextSpanAndCookie> _codeBlocks; private int _currentElement; public CodeBlockEnumerator(IList<TextSpanAndCookie> codeBlocks) { _codeBlocks = codeBlocks; _currentElement = 0; } /// <summary> /// Clones another instance of a CodeBlockEnumerator. /// </summary> private CodeBlockEnumerator(CodeBlockEnumerator previousEnumerator) { _codeBlocks = previousEnumerator._codeBlocks; _currentElement = previousEnumerator._currentElement; } public int Clone(out IVsEnumCodeBlocks ppEnum) { ppEnum = new CodeBlockEnumerator(this); return VSConstants.S_OK; } public int Next(uint celt, TextSpanAndCookie[] rgelt, out uint pceltFetched) { pceltFetched = Math.Min(celt, (uint)(_codeBlocks.Count - _currentElement)); // Copy each element over for (var i = 0; i < pceltFetched; i++) { rgelt[i] = _codeBlocks[_currentElement++]; } // If we returned fewer than the requested number of elements, we return S_FALSE return celt == pceltFetched ? VSConstants.S_OK : VSConstants.S_FALSE; } public int Reset() { _currentElement = 0; return VSConstants.S_OK; } public int Skip(uint celt) { _currentElement += (int)celt; // If we've advanced past the end, move back. We return S_FALSE only in this case. If we simply move *to* // the end, we actually do want to return S_OK. if (_currentElement > _codeBlocks.Count) { _currentElement = _codeBlocks.Count; return VSConstants.S_FALSE; } else { return VSConstants.S_OK; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.VisualStudio; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// An implementation of IVsEnumCodeBlocks used in the implementation of /// IVsContainedCode.EnumOriginalCodeBlocks for each language's Venus interop layer. /// </summary> internal class CodeBlockEnumerator : IVsEnumCodeBlocks { private readonly IList<TextSpanAndCookie> _codeBlocks; private int _currentElement; public CodeBlockEnumerator(IList<TextSpanAndCookie> codeBlocks) { _codeBlocks = codeBlocks; _currentElement = 0; } /// <summary> /// Clones another instance of a CodeBlockEnumerator. /// </summary> private CodeBlockEnumerator(CodeBlockEnumerator previousEnumerator) { _codeBlocks = previousEnumerator._codeBlocks; _currentElement = previousEnumerator._currentElement; } public int Clone(out IVsEnumCodeBlocks ppEnum) { ppEnum = new CodeBlockEnumerator(this); return VSConstants.S_OK; } public int Next(uint celt, TextSpanAndCookie[] rgelt, out uint pceltFetched) { pceltFetched = Math.Min(celt, (uint)(_codeBlocks.Count - _currentElement)); // Copy each element over for (var i = 0; i < pceltFetched; i++) { rgelt[i] = _codeBlocks[_currentElement++]; } // If we returned fewer than the requested number of elements, we return S_FALSE return celt == pceltFetched ? VSConstants.S_OK : VSConstants.S_FALSE; } public int Reset() { _currentElement = 0; return VSConstants.S_OK; } public int Skip(uint celt) { _currentElement += (int)celt; // If we've advanced past the end, move back. We return S_FALSE only in this case. If we simply move *to* // the end, we actually do want to return S_OK. if (_currentElement > _codeBlocks.Count) { _currentElement = _codeBlocks.Count; return VSConstants.S_FALSE; } else { return VSConstants.S_OK; } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Portable/Syntax/ArgumentSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class ArgumentSyntax { /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SyntaxToken RefOrOutKeyword { get => this.RefKindKeyword; } /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ArgumentSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) { return this.Update(this.NameColon, refOrOutKeyword, this.Expression); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class ArgumentSyntax { /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SyntaxToken RefOrOutKeyword { get => this.RefKindKeyword; } /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ArgumentSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) { return this.Update(this.NameColon, refOrOutKeyword, this.Expression); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Compilers/CSharp/Portable/FlowAnalysis/DataFlowsInWalker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A region analysis walker that computes the set of variables whose values flow into (are used /// in) the region. A variable assigned outside is used inside if an analysis that leaves the /// variable unassigned on entry to the region would cause the generation of "unassigned" errors /// within the region. /// </summary> internal class DataFlowsInWalker : AbstractRegionDataFlowPass { // TODO: normalize the result by removing variables that are unassigned in an unmodified // flow analysis. private readonly HashSet<Symbol> _dataFlowsIn = new HashSet<Symbol>(); private DataFlowsInWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<Symbol> unassignedVariables, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes) : base(compilation, member, node, firstInRegion, lastInRegion, unassignedVariables, unassignedVariableAddressOfSyntaxes) { } internal static HashSet<Symbol> Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<Symbol> unassignedVariables, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes, out bool? succeeded) { var walker = new DataFlowsInWalker(compilation, member, node, firstInRegion, lastInRegion, unassignedVariables, unassignedVariableAddressOfSyntaxes); try { bool badRegion = false; var result = walker.Analyze(ref badRegion); succeeded = !badRegion; return badRegion ? new HashSet<Symbol>() : result; } finally { walker.Free(); } } private HashSet<Symbol> Analyze(ref bool badRegion) { base.Analyze(ref badRegion, null); return _dataFlowsIn; } private LocalState ResetState(LocalState state) { bool unreachable = !state.Reachable; state = TopState(); if (unreachable) { state.Assign(0); } return state; } protected override void EnterRegion() { this.State = ResetState(this.State); _dataFlowsIn.Clear(); base.EnterRegion(); } protected override void NoteBranch( PendingBranch pending, BoundNode gotoStmt, BoundStatement targetStmt) { targetStmt.AssertIsLabeledStatement(); if (!gotoStmt.WasCompilerGenerated && !targetStmt.WasCompilerGenerated && !RegionContains(gotoStmt.Syntax.Span) && RegionContains(targetStmt.Syntax.Span)) { pending.State = ResetState(pending.State); } base.NoteBranch(pending, gotoStmt, targetStmt); } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { if (IsInside && !RegionContains(node.RangeVariableSymbol.Locations[0].SourceSpan)) { _dataFlowsIn.Add(node.RangeVariableSymbol); } return null; } protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) { // TODO: how to handle fields of structs? if (RegionContains(node.Span)) { // if the field access is reported as unassigned it should mean the original local // or parameter flows in, so we should get the symbol associated with the expression _dataFlowsIn.Add(symbol.Kind == SymbolKind.Field ? GetNonMemberSymbol(slot) : symbol); } base.ReportUnassigned(symbol, node, slot, skipIfUseBeforeDeclaration); } protected override void ReportUnassignedOutParameter( ParameterSymbol parameter, SyntaxNode node, Location location) { if (node != null && node is ReturnStatementSyntax && RegionContains(node.Span)) { _dataFlowsIn.Add(parameter); } base.ReportUnassignedOutParameter(parameter, node, location); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A region analysis walker that computes the set of variables whose values flow into (are used /// in) the region. A variable assigned outside is used inside if an analysis that leaves the /// variable unassigned on entry to the region would cause the generation of "unassigned" errors /// within the region. /// </summary> internal class DataFlowsInWalker : AbstractRegionDataFlowPass { // TODO: normalize the result by removing variables that are unassigned in an unmodified // flow analysis. private readonly HashSet<Symbol> _dataFlowsIn = new HashSet<Symbol>(); private DataFlowsInWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<Symbol> unassignedVariables, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes) : base(compilation, member, node, firstInRegion, lastInRegion, unassignedVariables, unassignedVariableAddressOfSyntaxes) { } internal static HashSet<Symbol> Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<Symbol> unassignedVariables, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes, out bool? succeeded) { var walker = new DataFlowsInWalker(compilation, member, node, firstInRegion, lastInRegion, unassignedVariables, unassignedVariableAddressOfSyntaxes); try { bool badRegion = false; var result = walker.Analyze(ref badRegion); succeeded = !badRegion; return badRegion ? new HashSet<Symbol>() : result; } finally { walker.Free(); } } private HashSet<Symbol> Analyze(ref bool badRegion) { base.Analyze(ref badRegion, null); return _dataFlowsIn; } private LocalState ResetState(LocalState state) { bool unreachable = !state.Reachable; state = TopState(); if (unreachable) { state.Assign(0); } return state; } protected override void EnterRegion() { this.State = ResetState(this.State); _dataFlowsIn.Clear(); base.EnterRegion(); } protected override void NoteBranch( PendingBranch pending, BoundNode gotoStmt, BoundStatement targetStmt) { targetStmt.AssertIsLabeledStatement(); if (!gotoStmt.WasCompilerGenerated && !targetStmt.WasCompilerGenerated && !RegionContains(gotoStmt.Syntax.Span) && RegionContains(targetStmt.Syntax.Span)) { pending.State = ResetState(pending.State); } base.NoteBranch(pending, gotoStmt, targetStmt); } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { if (IsInside && !RegionContains(node.RangeVariableSymbol.Locations[0].SourceSpan)) { _dataFlowsIn.Add(node.RangeVariableSymbol); } return null; } protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) { // TODO: how to handle fields of structs? if (RegionContains(node.Span)) { // if the field access is reported as unassigned it should mean the original local // or parameter flows in, so we should get the symbol associated with the expression _dataFlowsIn.Add(symbol.Kind == SymbolKind.Field ? GetNonMemberSymbol(slot) : symbol); } base.ReportUnassigned(symbol, node, slot, skipIfUseBeforeDeclaration); } protected override void ReportUnassignedOutParameter( ParameterSymbol parameter, SyntaxNode node, Location location) { if (node != null && node is ReturnStatementSyntax && RegionContains(node.Span)) { _dataFlowsIn.Add(parameter); } base.ReportUnassignedOutParameter(parameter, node, location); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ExternalSourceInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.LanguageServices { internal struct ExternalSourceInfo { public readonly int? StartLine; public readonly bool Ends; public ExternalSourceInfo(int? startLine, bool ends) { this.StartLine = startLine; this.Ends = ends; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.LanguageServices { internal struct ExternalSourceInfo { public readonly int? StartLine; public readonly bool Ends; public ExternalSourceInfo(int? startLine, bool ends) { this.StartLine = startLine; this.Ends = ends; } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/CSharpTest/Formatting/FormattingTriviaTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Formatting; using Roslyn.Test.Utilities; using Xunit; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { public class FormattingEngineTriviaTests : CSharpFormattingTestBase { [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] [WorkItem(31130, "https://github.com/dotnet/roslyn/issues/31130")] public async Task PreprocessorNullable() { var content = @" #nullable class C { #nullable enable void Method() { #nullable disable } }"; var expected = @" #nullable class C { #nullable enable void Method() { #nullable disable } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task PreprocessorInEmptyFile() { var content = @" #line 1000 #error "; var expected = @" #line 1000 #error "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment1() { var content = @" // single line comment class C { }"; var expected = @"// single line comment class C { }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment2() { var content = @"class C { // single line comment int i; }"; var expected = @"class C { // single line comment int i; }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment3() { var content = @"class C { // single line comment }"; var expected = @"class C { // single line comment }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment4() { var content = @"class C { // single line comment // single line comment 2 void Method() { } }"; var expected = @"class C { // single line comment // single line comment 2 void Method() { } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment5() { var content = @"class C { void Method() { // single line comment // single line comment 2 } }"; var expected = @"class C { void Method() { // single line comment // single line comment 2 } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment6() { var content = @"class C { void Method() { // single line comment // single line comment 2 int i = 10; } }"; var expected = @"class C { void Method() { // single line comment // single line comment 2 int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment7() { var content = @"class C { void Method() { // single line comment int i = 10; // single line comment 2 } }"; var expected = @"class C { void Method() { // single line comment int i = 10; // single line comment 2 } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment8() { var content = @"class C { void Method() { /* multiline comment */ int i = 10; } }"; var expected = @"class C { void Method() { /* multiline comment */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment9() { var content = @"class C { void Method() { /* multiline comment */ int i = 10; } }"; var expected = @"class C { void Method() { /* multiline comment */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment10() { var content = @"class C { void Method() { /* multiline comment */ int i = 10; /* multiline comment */ } }"; var expected = @"class C { void Method() { /* multiline comment */ int i = 10; /* multiline comment */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment11() { var content = @"class C { void Method() { /* * multiline comment */ int i = 10; /* * multiline comment */ } }"; var expected = @"class C { void Method() { /* * multiline comment */ int i = 10; /* * multiline comment */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment12() { var content = @"class C { void Method() { /* * multiline comment */ int i = 10; /* * multiline comment */ } }"; var expected = @"class C { void Method() { /* * multiline comment */ int i = 10; /* * multiline comment */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment13() { var content = @"class C { void Method() { // test int i = 10; } }"; var expected = @"class C { void Method() { // test int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment14() { var content = @"class C { void Method() { // test // test 2 // test 3 int i = 10; } }"; var expected = @"class C { void Method() { // test // test 2 // test 3 int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment15() { var content = @"class C { void Method() { /* test */ int i = 10; } }"; var expected = @"class C { void Method() { /* test */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment16() { var content = @"class C { void Method() { /* test * */ int i = 10; } }"; var expected = @"class C { void Method() { /* test * */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment17() { var content = @"class C { void Method() { /* test * */ // test int i = 10; } }"; var expected = @"class C { void Method() { /* test * */ // test int i = 10; } }"; await AssertFormatAsync(expected, content, true); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment18() { var content = @"class C { void Method() { /* test * */ // test // test 2 int i = 10; } }"; var expected = @"class C { void Method() { /* test * */ // test // test 2 int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment19() { var content = @"class C { void Method() { /* test * */ /* test 2 * */ int i = 10; } }"; var expected = @"class C { void Method() { /* test * */ /* test 2 * */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment20() { var content = @"class C { void Method() { int i = 10; /* test * */ /* test 2 * */ } }"; var expected = @"class C { void Method() { int i = 10; /* test * */ /* test 2 * */ } }"; await AssertFormatAsync(expected, content); } // for now, formatting engine doesn't re-indent token if the indentation line contains noisy // chars [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment21() { var content = @"class C { void Method() { /* */ int i = 10; } }"; var expected = @"class C { void Method() { /* */ int i = 10; } }"; await AssertFormatAsync(expected, content); } // for now, formatting engine doesn't re-indent token if the indentation line contains noisy // chars [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment22() { var content = @"class C { void Method() { int i = /* */ 10; } }"; var expected = @"class C { void Method() { int i = /* */ 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment23() { var content = @"class C { void Method() { int /* */ i = /* */ 10; } }"; var expected = @"class C { void Method() { int /* */ i = /* */ 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment24() { var content = @"class C { void Method() { /* */ int i = 10; } }"; var expected = @"class C { void Method() { /* */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment1() { var content = @"class C { void Method() { /** */ int i = 10; } }"; var expected = @"class C { void Method() { /** */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment2() { var content = @"class C { void Method() { /** */ int i = 10; } }"; var expected = @"class C { void Method() { /** */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment3() { var content = @"class C { void Method() { int i = 10; /** */ } }"; var expected = @"class C { void Method() { int i = 10; /** */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment4() { var content = @"class C { void Method() { int i = 10; /** */ } }"; var expected = @"class C { void Method() { int i = 10; /** */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment5() { var content = @"class C { void Method() { int i = 10; /** */ } }"; var expected = @"class C { void Method() { int i = 10; /** */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment6() { var content = @"class C { void Method() { int i /** */ = /** */ 10; } }"; var expected = @"class C { void Method() { int i /** */ = /** */ 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment7() { var content = @"class C { void Method() { /// /// int i = 10; } }"; var expected = @"class C { void Method() { /// /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment8() { var content = @"class C { void Method() { /// /// int i = 10; } }"; var expected = @"class C { void Method() { /// /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment9() { var content = @"class C { void Method() { int i = 10; /// /// } }"; var expected = @"class C { void Method() { int i = 10; /// /// } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment10() { var content = @"class C { void Method() { /// /** */ /// /// int i = 10; } }"; var expected = @"class C { void Method() { /// /** */ /// /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment11() { var content = @"class C { void Method() { /// /** */ /** * */ int i = 10; } }"; var expected = @"class C { void Method() { /// /** */ /** * */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment12() { var content = @"class C { void Method() { /// /** */ /** */ int i = 10; } }"; var expected = @"class C { void Method() { /// /** */ /** */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixCommentAndDocComment1() { var content = @"class C { void Method() { // /** */ /* */ // int i = 10; } }"; var expected = @"class C { void Method() { // /** */ /* */ // int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixCommentAndDocComment2() { var content = @"class C { void Method() { /* * */ /** * */ /* * */ /// /// int i = 10; } }"; var expected = @"class C { void Method() { /* * */ /** * */ /* * */ /// /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixCommentAndDocComment3() { var content = @"class C { void Method() { // test // test 2 /// <text></text> /// test 3 /// int i = 10; } }"; var expected = @"class C { void Method() { // test // test 2 /// <text></text> /// test 3 /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixCommentAndDocComment4() { var content = @"class C { /// <text></text> /// test 3 /// void Method() { // test // test 2 int i = 10; } }"; var expected = @"class C { /// <text></text> /// test 3 /// void Method() { // test // test 2 int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor1() { var content = @"class C { #if true #endif void Method() { int i = 10; } }"; var expected = @"class C { #if true #endif void Method() { int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor2() { var content = @"class C { #if true void Method() { int i = 10; } } #endif "; var expected = @"class C { #if true void Method() { int i = 10; } } #endif "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor3() { var content = @"class C { #if true void Method() { #elif false int i = 10; } } #endif } }"; var expected = @"class C { #if true void Method() { #elif false int i = 10; } } #endif } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor4() { var content = @"class C { #if true void Method() { } #elif false int i = 10; } #endif } "; var expected = @"class C { #if true void Method() { } #elif false int i = 10; } #endif } "; // turn off transformation check - conditional directive preprocessor await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor5() { var content = @"class C { #region Test int i = 10; #endregion void Method() { } } "; var expected = @"class C { #region Test int i = 10; #endregion void Method() { } } "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor6() { var content = @"class C { #region Test int i = 10; #endregion void Method() { } } "; var expected = @"class C { #region Test int i = 10; #endregion void Method() { } } "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor7() { var content = @"class C { #region Test int i = 10; void Method() { } #endregion } "; var expected = @"class C { #region Test int i = 10; void Method() { } #endregion } "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor8() { var content = @"class C { #region Test int i = 10; void Method() { #endregion int i = 10; } } "; var expected = @"class C { #region Test int i = 10; void Method() { #endregion int i = 10; } } "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixAll() { var content = @"class C { #region Test #if true // test /// /// int i = 10; #else void Method() { } #endif #endregion } "; var expected = @"class C { #region Test #if true // test /// /// int i = 10; #else void Method() { } #endif #endregion } "; // turn off transformation check since it doesn't work for conditional directive yet. await AssertFormatAsync(expected, content); } [WorkItem(537895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor9() { var content = @"class C { void Method() { #region Myregion int a; if (true) a++; #endregion } } "; var expected = @"class C { void Method() { #region Myregion int a; if (true) a++; #endregion } } "; await AssertFormatAsync(expected, content); } [WorkItem(537895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor10() { var content = @"class C { void Method() { int a; if (true) a++; #region Myregion } } "; var expected = @"class C { void Method() { int a; if (true) a++; #region Myregion } } "; await AssertFormatAsync(expected, content); } [WorkItem(537765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537765")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment25() { var content = @"class C { void Goo()//method { int x;//variable double y; } } "; var expected = @"class C { void Goo()//method { int x;//variable double y; } } "; await AssertFormatAsync(expected, content); } [WorkItem(537765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537765")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment26() { var content = @"public class Class1 { void Goo() { /**/int x; } }"; var expected = @"public class Class1 { void Goo() { /**/ int x; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment27() { var content = @"public class Class1 { void Goo() { // // } }"; await AssertFormatAsync(content, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment28() { var content = @"public class Class1 { void Goo() { // // } }"; var expected = @"public class Class1 { void Goo() { // // } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment29() { var content = @"public class Class1 { void Goo() { int /**/ i = 10; } }"; var code = @"public class Class1 { void Goo() { int /**/ i = 10; } }"; await AssertFormatAsync(code, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment30() { var content = @" // Test"; var code = @" // Test"; await AssertFormatAsync(code, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment31() { var content = @"/// <summary> /// /// </summary> class Program { static void Main(string[] args) { } } "; var code = @"/// <summary> /// /// </summary> class Program { static void Main(string[] args) { } } "; await AssertFormatAsync(code, content); } [WorkItem(538703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538703")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment32() { var content = @"class Program { ///<summary> /// TestMethod ///</summary> void Method() { } } "; var code = @"class Program { ///<summary> /// TestMethod ///</summary> void Method() { } } "; await AssertFormatAsync(code, content); } [WorkItem(542316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542316")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task CommentInExpression() { var content = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (10,30): error CS0455: Type parameter 'X' inherits conflicting constraints 'B' and 'A' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, ""X"").WithArguments(""X"", ""B"", ""A"").WithLocation(10, 30)); } } "; var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (10,30): error CS0455: Type parameter 'X' inherits conflicting constraints 'B' and 'A' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, ""X"").WithArguments(""X"", ""B"", ""A"").WithLocation(10, 30)); } } "; await AssertFormatAsync(code, content); } [WorkItem(542546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542546")] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatInvalidCode_1() { var expected = @"> Roslyn.Utilities.dll! Basic"; var content = @"> Roslyn.Utilities.dll! Basic"; await AssertFormatAsync(expected, content); } [WorkItem(542546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542546")] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatInvalidCode_2() { var content = @"> Roslyn.Utilities.dll! Line 43 + 0x5 bytes Basic"; var expectedContent = @"> Roslyn.Utilities.dll! Line 43 + 0x5 bytes Basic"; await AssertFormatAsync(expectedContent, content); } [WorkItem(537895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task EmbededStatement1() { var content = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { #region Myregion int a; if (true) a++; #endregion } }"; var expectedContent = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { #region Myregion int a; if (true) a++; #endregion } }"; await AssertFormatAsync(expectedContent, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task RefKeywords() { var content = @"class C { static void Main(string[] args) { int i = 1; TypedReference tr = __makeref( i ); Type t = __reftype( tr ); int j = __refvalue( tr , int ); } }"; var expected = @"class C { static void Main(string[] args) { int i = 1; TypedReference tr = __makeref(i); Type t = __reftype(tr ); int j = __refvalue(tr, int ); } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NewLineOptions_LineFeedOnly() { var tree = SyntaxFactory.ParseCompilationUnit("class C\r\n{\r\n}"); // replace all EOL trivia with elastic markers to force the formatter to add EOL back tree = tree.ReplaceTrivia(tree.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.EndOfLineTrivia)), (o, r) => SyntaxFactory.ElasticMarker); var formatted = Formatter.Format(tree, DefaultWorkspace, DefaultWorkspace.Options.WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, "\n")); var actual = formatted.ToFullString(); var expected = "class C\n{\n}"; Assert.Equal(expected, actual); } [WorkItem(4019, "https://github.com/dotnet/roslyn/issues/4019")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatWithTabs() { var code = @"#region Assembly mscorlib // C:\ #endregion using System.Collections; class F { string s; }"; var expected = @"#region Assembly mscorlib // C:\ #endregion using System.Collections; class F { string s; }"; var tree = SyntaxFactory.ParseCompilationUnit(code); var newLineText = SyntaxFactory.ElasticEndOfLine(DefaultWorkspace.Options.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp)); tree = tree.ReplaceTokens(tree.DescendantTokens(descendIntoTrivia: true) .Where(tr => tr.IsKind(SyntaxKind.EndOfDirectiveToken)), (o, r) => o.WithTrailingTrivia(o.LeadingTrivia.Add(newLineText)) .WithLeadingTrivia(SyntaxFactory.TriviaList()) .WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation)); var formatted = Formatter.Format(tree, DefaultWorkspace, DefaultWorkspace.Options.WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, true)); var actual = formatted.ToFullString(); Assert.Equal(expected, actual); } [WorkItem(39351, "https://github.com/dotnet/roslyn/issues/39351")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task SingleLineComment_AtEndOfFile_DoesNotAddNewLine() { await AssertNoFormattingChangesAsync(@"class Program { } // Test"); } [WorkItem(39351, "https://github.com/dotnet/roslyn/issues/39351")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MultiLineComment_AtEndOfFile_DoesNotAddNewLine() { await AssertNoFormattingChangesAsync(@"class Program { } /* Test */"); } [WorkItem(39351, "https://github.com/dotnet/roslyn/issues/39351")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment_AtEndOfFile_DoesNotAddNewLine() { await AssertNoFormattingChangesAsync(@"class Program { } /// Test"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Formatting; using Roslyn.Test.Utilities; using Xunit; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { public class FormattingEngineTriviaTests : CSharpFormattingTestBase { [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] [WorkItem(31130, "https://github.com/dotnet/roslyn/issues/31130")] public async Task PreprocessorNullable() { var content = @" #nullable class C { #nullable enable void Method() { #nullable disable } }"; var expected = @" #nullable class C { #nullable enable void Method() { #nullable disable } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task PreprocessorInEmptyFile() { var content = @" #line 1000 #error "; var expected = @" #line 1000 #error "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment1() { var content = @" // single line comment class C { }"; var expected = @"// single line comment class C { }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment2() { var content = @"class C { // single line comment int i; }"; var expected = @"class C { // single line comment int i; }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment3() { var content = @"class C { // single line comment }"; var expected = @"class C { // single line comment }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment4() { var content = @"class C { // single line comment // single line comment 2 void Method() { } }"; var expected = @"class C { // single line comment // single line comment 2 void Method() { } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment5() { var content = @"class C { void Method() { // single line comment // single line comment 2 } }"; var expected = @"class C { void Method() { // single line comment // single line comment 2 } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment6() { var content = @"class C { void Method() { // single line comment // single line comment 2 int i = 10; } }"; var expected = @"class C { void Method() { // single line comment // single line comment 2 int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment7() { var content = @"class C { void Method() { // single line comment int i = 10; // single line comment 2 } }"; var expected = @"class C { void Method() { // single line comment int i = 10; // single line comment 2 } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment8() { var content = @"class C { void Method() { /* multiline comment */ int i = 10; } }"; var expected = @"class C { void Method() { /* multiline comment */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment9() { var content = @"class C { void Method() { /* multiline comment */ int i = 10; } }"; var expected = @"class C { void Method() { /* multiline comment */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment10() { var content = @"class C { void Method() { /* multiline comment */ int i = 10; /* multiline comment */ } }"; var expected = @"class C { void Method() { /* multiline comment */ int i = 10; /* multiline comment */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment11() { var content = @"class C { void Method() { /* * multiline comment */ int i = 10; /* * multiline comment */ } }"; var expected = @"class C { void Method() { /* * multiline comment */ int i = 10; /* * multiline comment */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment12() { var content = @"class C { void Method() { /* * multiline comment */ int i = 10; /* * multiline comment */ } }"; var expected = @"class C { void Method() { /* * multiline comment */ int i = 10; /* * multiline comment */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment13() { var content = @"class C { void Method() { // test int i = 10; } }"; var expected = @"class C { void Method() { // test int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment14() { var content = @"class C { void Method() { // test // test 2 // test 3 int i = 10; } }"; var expected = @"class C { void Method() { // test // test 2 // test 3 int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment15() { var content = @"class C { void Method() { /* test */ int i = 10; } }"; var expected = @"class C { void Method() { /* test */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment16() { var content = @"class C { void Method() { /* test * */ int i = 10; } }"; var expected = @"class C { void Method() { /* test * */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment17() { var content = @"class C { void Method() { /* test * */ // test int i = 10; } }"; var expected = @"class C { void Method() { /* test * */ // test int i = 10; } }"; await AssertFormatAsync(expected, content, true); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment18() { var content = @"class C { void Method() { /* test * */ // test // test 2 int i = 10; } }"; var expected = @"class C { void Method() { /* test * */ // test // test 2 int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment19() { var content = @"class C { void Method() { /* test * */ /* test 2 * */ int i = 10; } }"; var expected = @"class C { void Method() { /* test * */ /* test 2 * */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment20() { var content = @"class C { void Method() { int i = 10; /* test * */ /* test 2 * */ } }"; var expected = @"class C { void Method() { int i = 10; /* test * */ /* test 2 * */ } }"; await AssertFormatAsync(expected, content); } // for now, formatting engine doesn't re-indent token if the indentation line contains noisy // chars [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment21() { var content = @"class C { void Method() { /* */ int i = 10; } }"; var expected = @"class C { void Method() { /* */ int i = 10; } }"; await AssertFormatAsync(expected, content); } // for now, formatting engine doesn't re-indent token if the indentation line contains noisy // chars [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment22() { var content = @"class C { void Method() { int i = /* */ 10; } }"; var expected = @"class C { void Method() { int i = /* */ 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment23() { var content = @"class C { void Method() { int /* */ i = /* */ 10; } }"; var expected = @"class C { void Method() { int /* */ i = /* */ 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment24() { var content = @"class C { void Method() { /* */ int i = 10; } }"; var expected = @"class C { void Method() { /* */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment1() { var content = @"class C { void Method() { /** */ int i = 10; } }"; var expected = @"class C { void Method() { /** */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment2() { var content = @"class C { void Method() { /** */ int i = 10; } }"; var expected = @"class C { void Method() { /** */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment3() { var content = @"class C { void Method() { int i = 10; /** */ } }"; var expected = @"class C { void Method() { int i = 10; /** */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment4() { var content = @"class C { void Method() { int i = 10; /** */ } }"; var expected = @"class C { void Method() { int i = 10; /** */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment5() { var content = @"class C { void Method() { int i = 10; /** */ } }"; var expected = @"class C { void Method() { int i = 10; /** */ } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment6() { var content = @"class C { void Method() { int i /** */ = /** */ 10; } }"; var expected = @"class C { void Method() { int i /** */ = /** */ 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment7() { var content = @"class C { void Method() { /// /// int i = 10; } }"; var expected = @"class C { void Method() { /// /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment8() { var content = @"class C { void Method() { /// /// int i = 10; } }"; var expected = @"class C { void Method() { /// /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment9() { var content = @"class C { void Method() { int i = 10; /// /// } }"; var expected = @"class C { void Method() { int i = 10; /// /// } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment10() { var content = @"class C { void Method() { /// /** */ /// /// int i = 10; } }"; var expected = @"class C { void Method() { /// /** */ /// /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment11() { var content = @"class C { void Method() { /// /** */ /** * */ int i = 10; } }"; var expected = @"class C { void Method() { /// /** */ /** * */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment12() { var content = @"class C { void Method() { /// /** */ /** */ int i = 10; } }"; var expected = @"class C { void Method() { /// /** */ /** */ int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixCommentAndDocComment1() { var content = @"class C { void Method() { // /** */ /* */ // int i = 10; } }"; var expected = @"class C { void Method() { // /** */ /* */ // int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixCommentAndDocComment2() { var content = @"class C { void Method() { /* * */ /** * */ /* * */ /// /// int i = 10; } }"; var expected = @"class C { void Method() { /* * */ /** * */ /* * */ /// /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixCommentAndDocComment3() { var content = @"class C { void Method() { // test // test 2 /// <text></text> /// test 3 /// int i = 10; } }"; var expected = @"class C { void Method() { // test // test 2 /// <text></text> /// test 3 /// int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixCommentAndDocComment4() { var content = @"class C { /// <text></text> /// test 3 /// void Method() { // test // test 2 int i = 10; } }"; var expected = @"class C { /// <text></text> /// test 3 /// void Method() { // test // test 2 int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor1() { var content = @"class C { #if true #endif void Method() { int i = 10; } }"; var expected = @"class C { #if true #endif void Method() { int i = 10; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor2() { var content = @"class C { #if true void Method() { int i = 10; } } #endif "; var expected = @"class C { #if true void Method() { int i = 10; } } #endif "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor3() { var content = @"class C { #if true void Method() { #elif false int i = 10; } } #endif } }"; var expected = @"class C { #if true void Method() { #elif false int i = 10; } } #endif } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor4() { var content = @"class C { #if true void Method() { } #elif false int i = 10; } #endif } "; var expected = @"class C { #if true void Method() { } #elif false int i = 10; } #endif } "; // turn off transformation check - conditional directive preprocessor await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor5() { var content = @"class C { #region Test int i = 10; #endregion void Method() { } } "; var expected = @"class C { #region Test int i = 10; #endregion void Method() { } } "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor6() { var content = @"class C { #region Test int i = 10; #endregion void Method() { } } "; var expected = @"class C { #region Test int i = 10; #endregion void Method() { } } "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor7() { var content = @"class C { #region Test int i = 10; void Method() { } #endregion } "; var expected = @"class C { #region Test int i = 10; void Method() { } #endregion } "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor8() { var content = @"class C { #region Test int i = 10; void Method() { #endregion int i = 10; } } "; var expected = @"class C { #region Test int i = 10; void Method() { #endregion int i = 10; } } "; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MixAll() { var content = @"class C { #region Test #if true // test /// /// int i = 10; #else void Method() { } #endif #endregion } "; var expected = @"class C { #region Test #if true // test /// /// int i = 10; #else void Method() { } #endif #endregion } "; // turn off transformation check since it doesn't work for conditional directive yet. await AssertFormatAsync(expected, content); } [WorkItem(537895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor9() { var content = @"class C { void Method() { #region Myregion int a; if (true) a++; #endregion } } "; var expected = @"class C { void Method() { #region Myregion int a; if (true) a++; #endregion } } "; await AssertFormatAsync(expected, content); } [WorkItem(537895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Preprocessor10() { var content = @"class C { void Method() { int a; if (true) a++; #region Myregion } } "; var expected = @"class C { void Method() { int a; if (true) a++; #region Myregion } } "; await AssertFormatAsync(expected, content); } [WorkItem(537765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537765")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment25() { var content = @"class C { void Goo()//method { int x;//variable double y; } } "; var expected = @"class C { void Goo()//method { int x;//variable double y; } } "; await AssertFormatAsync(expected, content); } [WorkItem(537765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537765")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment26() { var content = @"public class Class1 { void Goo() { /**/int x; } }"; var expected = @"public class Class1 { void Goo() { /**/ int x; } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment27() { var content = @"public class Class1 { void Goo() { // // } }"; await AssertFormatAsync(content, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment28() { var content = @"public class Class1 { void Goo() { // // } }"; var expected = @"public class Class1 { void Goo() { // // } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment29() { var content = @"public class Class1 { void Goo() { int /**/ i = 10; } }"; var code = @"public class Class1 { void Goo() { int /**/ i = 10; } }"; await AssertFormatAsync(code, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment30() { var content = @" // Test"; var code = @" // Test"; await AssertFormatAsync(code, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment31() { var content = @"/// <summary> /// /// </summary> class Program { static void Main(string[] args) { } } "; var code = @"/// <summary> /// /// </summary> class Program { static void Main(string[] args) { } } "; await AssertFormatAsync(code, content); } [WorkItem(538703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538703")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task Comment32() { var content = @"class Program { ///<summary> /// TestMethod ///</summary> void Method() { } } "; var code = @"class Program { ///<summary> /// TestMethod ///</summary> void Method() { } } "; await AssertFormatAsync(code, content); } [WorkItem(542316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542316")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task CommentInExpression() { var content = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (10,30): error CS0455: Type parameter 'X' inherits conflicting constraints 'B' and 'A' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, ""X"").WithArguments(""X"", ""B"", ""A"").WithLocation(10, 30)); } } "; var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (10,30): error CS0455: Type parameter 'X' inherits conflicting constraints 'B' and 'A' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, ""X"").WithArguments(""X"", ""B"", ""A"").WithLocation(10, 30)); } } "; await AssertFormatAsync(code, content); } [WorkItem(542546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542546")] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatInvalidCode_1() { var expected = @"> Roslyn.Utilities.dll! Basic"; var content = @"> Roslyn.Utilities.dll! Basic"; await AssertFormatAsync(expected, content); } [WorkItem(542546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542546")] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatInvalidCode_2() { var content = @"> Roslyn.Utilities.dll! Line 43 + 0x5 bytes Basic"; var expectedContent = @"> Roslyn.Utilities.dll! Line 43 + 0x5 bytes Basic"; await AssertFormatAsync(expectedContent, content); } [WorkItem(537895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task EmbededStatement1() { var content = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { #region Myregion int a; if (true) a++; #endregion } }"; var expectedContent = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { #region Myregion int a; if (true) a++; #endregion } }"; await AssertFormatAsync(expectedContent, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task RefKeywords() { var content = @"class C { static void Main(string[] args) { int i = 1; TypedReference tr = __makeref( i ); Type t = __reftype( tr ); int j = __refvalue( tr , int ); } }"; var expected = @"class C { static void Main(string[] args) { int i = 1; TypedReference tr = __makeref(i); Type t = __reftype(tr ); int j = __refvalue(tr, int ); } }"; await AssertFormatAsync(expected, content); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NewLineOptions_LineFeedOnly() { var tree = SyntaxFactory.ParseCompilationUnit("class C\r\n{\r\n}"); // replace all EOL trivia with elastic markers to force the formatter to add EOL back tree = tree.ReplaceTrivia(tree.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.EndOfLineTrivia)), (o, r) => SyntaxFactory.ElasticMarker); var formatted = Formatter.Format(tree, DefaultWorkspace, DefaultWorkspace.Options.WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, "\n")); var actual = formatted.ToFullString(); var expected = "class C\n{\n}"; Assert.Equal(expected, actual); } [WorkItem(4019, "https://github.com/dotnet/roslyn/issues/4019")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatWithTabs() { var code = @"#region Assembly mscorlib // C:\ #endregion using System.Collections; class F { string s; }"; var expected = @"#region Assembly mscorlib // C:\ #endregion using System.Collections; class F { string s; }"; var tree = SyntaxFactory.ParseCompilationUnit(code); var newLineText = SyntaxFactory.ElasticEndOfLine(DefaultWorkspace.Options.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp)); tree = tree.ReplaceTokens(tree.DescendantTokens(descendIntoTrivia: true) .Where(tr => tr.IsKind(SyntaxKind.EndOfDirectiveToken)), (o, r) => o.WithTrailingTrivia(o.LeadingTrivia.Add(newLineText)) .WithLeadingTrivia(SyntaxFactory.TriviaList()) .WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation)); var formatted = Formatter.Format(tree, DefaultWorkspace, DefaultWorkspace.Options.WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, true)); var actual = formatted.ToFullString(); Assert.Equal(expected, actual); } [WorkItem(39351, "https://github.com/dotnet/roslyn/issues/39351")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task SingleLineComment_AtEndOfFile_DoesNotAddNewLine() { await AssertNoFormattingChangesAsync(@"class Program { } // Test"); } [WorkItem(39351, "https://github.com/dotnet/roslyn/issues/39351")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task MultiLineComment_AtEndOfFile_DoesNotAddNewLine() { await AssertNoFormattingChangesAsync(@"class Program { } /* Test */"); } [WorkItem(39351, "https://github.com/dotnet/roslyn/issues/39351")] [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task DocComment_AtEndOfFile_DoesNotAddNewLine() { await AssertNoFormattingChangesAsync(@"class Program { } /// Test"); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Features/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.LanguageServer.Handler.RequestExecutionQueue; namespace Microsoft.CodeAnalysis.LanguageServer; /// <summary> /// Manages the registered workspaces and corresponding LSP solutions for an LSP server. /// This type is tied to a particular server. /// </summary> /// <remarks> /// This is built to store incremental solutions that we update based on LSP text changes. This solution is <b>eventually consistent</b> with the workspace: /// <list type="bullet"> /// <item> When LSP text changes come in, we only fork the relevant document. </item> /// <item> We listen to workspace events. When we receive an event that is not for an LSP open document, /// we delete our incremental LSP solution so that we can fork the workspace with all open LSP documents. </item> /// </list> /// /// Doing incremental forking like this is more complex, but has a few nice properties: /// <list type="bullet"> /// <item>LSP didChange events only cause us to update the document that changed, not all open documents.</item> /// <item>Since we incrementally update our LSP documents, we only have to re-parse the document that changed.</item> /// <item>Since we incrementally update our LSP documents, project versions for other open documents remain unchanged.</item> /// <item>We are not reliant on the workspace being updated frequently (which it is not in VSCode) to do checksum diffing between LSP and the workspace.</item> /// </list> /// </remarks> internal class LspWorkspaceManager : IDocumentChangeTracker, IDisposable { /// <summary> /// Lock to gate access to the <see cref="_workspaceToLspSolution"/> and <see cref="_trackedDocuments"/> /// Access from the LSP server is serial as the LSP queue is processed serially until /// after we give the solution to the request handlers. However workspace events can interleave /// so we must protect against concurrent access here. /// </summary> private readonly object _gate = new(); /// <summary> /// A map from the registered workspace to the running lsp solution with incremental changes from LSP /// text sync applied to it. /// All workspaces registered by the <see cref="LspWorkspaceRegistrationService"/> are added as keys to this dictionary /// with a null value (solution) initially. As LSP text changes come in, we create the incremental solution from the workspace and update it with changes. /// When we detect a change that requires us to re-fork the LSP solution from the workspace we null out the solution for the key. /// </summary> private readonly Dictionary<Workspace, Solution?> _workspaceToLspSolution = new(); /// <summary> /// Stores the current source text for each URI that is being tracked by LSP. /// Each time an LSP text sync notification comes in, this source text is updated to match. /// Used as the backing implementation for the <see cref="IDocumentChangeTracker"/>. /// /// Note that the text here is tracked regardless of whether or not we found a matching roslyn document /// for the URI. /// </summary> private ImmutableDictionary<Uri, SourceText> _trackedDocuments = ImmutableDictionary<Uri, SourceText>.Empty; private readonly string _hostWorkspaceKind; private readonly ILspLogger _logger; private readonly LspMiscellaneousFilesWorkspace? _lspMiscellaneousFilesWorkspace; private readonly LspWorkspaceRegistrationService _lspWorkspaceRegistrationService; private readonly RequestTelemetryLogger _requestTelemetryLogger; public LspWorkspaceManager( ILspLogger logger, LspMiscellaneousFilesWorkspace? lspMiscellaneousFilesWorkspace, LspWorkspaceRegistrationService lspWorkspaceRegistrationService, RequestTelemetryLogger requestTelemetryLogger) { _hostWorkspaceKind = lspWorkspaceRegistrationService.GetHostWorkspaceKind(); _lspMiscellaneousFilesWorkspace = lspMiscellaneousFilesWorkspace; _logger = logger; _requestTelemetryLogger = requestTelemetryLogger; _lspWorkspaceRegistrationService = lspWorkspaceRegistrationService; // This server may have been started after workspaces were registered, we need to ensure we know about them. foreach (var workspace in lspWorkspaceRegistrationService.GetAllRegistrations()) { OnWorkspaceRegistered(this, new LspWorkspaceRegisteredEventArgs(workspace)); } lspWorkspaceRegistrationService.WorkspaceRegistered += OnWorkspaceRegistered; } public void Dispose() { // Workspace events can come in while we're disposing of an LSP server (e.g. restart). lock (_gate) { _lspWorkspaceRegistrationService.WorkspaceRegistered -= OnWorkspaceRegistered; foreach (var registeredWorkspace in _workspaceToLspSolution.Keys) { registeredWorkspace.WorkspaceChanged -= OnWorkspaceChanged; } _workspaceToLspSolution.Clear(); } } #region Workspace Updates /// <summary> /// Handles cases where a new workspace is registered after an LSP server is already started. /// For example, in VS the metadata as source workspace is not created until a metadata files is opened. /// </summary> private void OnWorkspaceRegistered(object? sender, LspWorkspaceRegisteredEventArgs e) { lock (_gate) { // Set the LSP solution for the workspace to null so that when asked we fork from the workspace. _workspaceToLspSolution.Add(e.Workspace, null); e.Workspace.WorkspaceChanged += OnWorkspaceChanged; _logger.TraceInformation($"Registered workspace {e.Workspace.Kind}"); } } /// <summary> /// Subscribed to the <see cref="Workspace.WorkspaceChanged"/> event for registered workspaces. /// If the workspace change is a change to an open LSP document, we ignore the change event as LSP will update us. /// If the workspace change is a change to a non-open document / project change, we trigger a fork from the workspace. /// </summary> private void OnWorkspaceChanged(object? sender, WorkspaceChangeEventArgs e) { var workspace = e.NewSolution.Workspace; if (e.Kind is WorkspaceChangeKind.DocumentChanged) { Contract.ThrowIfNull(e.DocumentId, $"DocumentId missing for document change event {e.Kind}"); // Retrieve the current state of documents owned by LSP. It is not necessarily // consistent with the workspace, but if the documents owned by LSP change we fork from the workspace // and will eventually become consistent. ImmutableDictionary<Uri, SourceText> trackedDocuments; lock (_gate) { trackedDocuments = _trackedDocuments; } if (IsDocumentTrackedByLsp(e.DocumentId, e.NewSolution, trackedDocuments)) { // We're tracking the document already, no need to fork the workspace to get the changes, LSP will have sent them to us. return; } } lock (_gate) { // Documents added/removed, changes to additional docs, closed document changes, any changes to the project, or any changes to the solution // mean we need to re-fork from the workspace to ensure that the lsp solution contains these updates. _workspaceToLspSolution[workspace] = null; } bool IsDocumentTrackedByLsp(DocumentId changedDocumentId, Solution newWorkspaceSolution, ImmutableDictionary<Uri, SourceText> trackedDocuments) { var changedDocument = newWorkspaceSolution.GetRequiredDocument(changedDocumentId); var documentUri = changedDocument.TryGetURI(); return documentUri != null && trackedDocuments.ContainsKey(documentUri); } } #endregion #region Implementation of IDocumentChangeTracker /// <summary> /// Called by the <see cref="DidOpenHandler"/> when a document is opened in LSP. /// </summary> public void StartTracking(Uri uri, SourceText documentText) { lock (_gate) { // First, store the LSP view of the text as the uri is now owned by the LSP client. Contract.ThrowIfTrue(_trackedDocuments.ContainsKey(uri), $"didOpen received for {uri} which is already open."); _trackedDocuments = _trackedDocuments.Add(uri, documentText); // Make sure we reset/update our LSP incremental solutions now that we potentially have a new document. ResetIncrementalLspSolutions_CalledUnderLock(); var updatedSolutions = ComputeIncrementalLspSolutions_CalledUnderLock(); if (updatedSolutions.Any(solution => solution.GetDocuments(uri).Any())) { return; } // If we can't find the document in any of the registered workspaces, add it to our loose files workspace. var miscDocument = _lspMiscellaneousFilesWorkspace?.AddMiscellaneousDocument(uri, documentText); if (miscDocument != null) { _workspaceToLspSolution[miscDocument.Project.Solution.Workspace] = miscDocument.Project.Solution; } } } /// <summary> /// Called by the <see cref="DidCloseHandler"/> when a document is closed in LSP. /// </summary> public void StopTracking(Uri uri) { lock (_gate) { // First, stop tracking this URI and source text as it is no longer owned by LSP. Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(uri), $"didClose received for {uri} which is not open."); _trackedDocuments = _trackedDocuments.Remove(uri); // Trigger a fork of all workspaces, the LSP document text may not match the workspace and this document // may have been removed / moved to a different workspace. ResetIncrementalLspSolutions_CalledUnderLock(); // If the file was added to the LSP misc files workspace, it needs to be removed as we no longer care about it once closed. // If the misc document ended up being added to an actual workspace, we may have already removed it from LSP misc in UpdateLspDocument. _lspMiscellaneousFilesWorkspace?.TryRemoveMiscellaneousDocument(uri); } } /// <summary> /// Called by the <see cref="DidChangeHandler"/> when a document's text is updated in LSP. /// </summary> public void UpdateTrackedDocument(Uri uri, SourceText newSourceText) { lock (_gate) { // Store the updated LSP view of the source text. Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(uri), $"didChange received for {uri} which is not open."); _trackedDocuments = _trackedDocuments.SetItem(uri, newSourceText); // Get our current solutions and re-fork from the workspace as needed. var updatedSolutions = ComputeIncrementalLspSolutions_CalledUnderLock(); var findDocumentResult = FindDocuments(uri, updatedSolutions, clientName: null, _requestTelemetryLogger, _logger); if (findDocumentResult.IsEmpty) { // We didn't find this document in a registered workspace or in the misc workspace. // This can happen when workspace event processing is behind LSP and a new document was added that has not been reflected in the incremental LSP solution yet. // // This means that the LSP solution will be stale until the event is processed and will not be able to answer requests on this URI. // When the workspace event is processed, we will fork from the workspace and apply all missed incremental LSP text (stored in IDocumentChangeTracker) // to bring the incremental LSP solution up to date. // // TODO - Once we always create the misc files workspace we should never hit this path (when workspace events are behind the doc will go into misc). // Remove as part of https://github.com/dotnet/roslyn/issues/57243 return; } // Update all the documents that have a matching uri with the new source text and store as our new incremental solution. // We can have multiple documents with the same URI (e.g. linked documents). var solution = GetSolutionWithReplacedDocuments(findDocumentResult.First().Project.Solution, ImmutableArray.Create((uri, newSourceText))); _workspaceToLspSolution[solution.Workspace] = solution; if (solution.Workspace is not LspMiscellaneousFilesWorkspace && _lspMiscellaneousFilesWorkspace != null) { // If we found the uri in a workspace that isn't LSP misc files, we can remove it from the lsp misc files if it is there. // // Example: In VSCode, the server is started and file opened before the user has chosen which project/sln in the folder they want to open, // and therefore on didOpen the file gets put into LSP misc files. // // Once the workspace is updated with the document however, we proactively cleanup the lsp misc files workspace here // so that we don't keep lingering references around. _lspMiscellaneousFilesWorkspace.TryRemoveMiscellaneousDocument(uri); } } } public ImmutableDictionary<Uri, SourceText> GetTrackedLspText() { lock (_gate) { return _trackedDocuments; } } #endregion #region LSP Solution Retrieval /// <summary> /// Returns the LSP solution associated with the workspace with the specified <see cref="_hostWorkspaceKind"/>. /// This is the solution used for LSP requests that pertain to the entire workspace, for example code search or workspace diagnostics. /// </summary> public Solution? TryGetHostLspSolution() { lock (_gate) { // Ensure we have the latest lsp solutions var updatedSolutions = ComputeIncrementalLspSolutions_CalledUnderLock(); var hostWorkspaceSolution = updatedSolutions.FirstOrDefault(s => s.Workspace.Kind == _hostWorkspaceKind); return hostWorkspaceSolution; } } /// <summary> /// Returns a document with the LSP tracked text forked from the appropriate workspace solution. /// </summary> /// <param name="clientName"> /// Returns documents that have a matching client name. In razor scenarios this is to ensure that the Razor C# server /// only provides data for generated razor documents (which have a client name). /// </param> public Document? GetLspDocument(TextDocumentIdentifier textDocumentIdentifier, string? clientName) { lock (_gate) { // Ensure we have the latest lsp solutions var currentLspSolutions = ComputeIncrementalLspSolutions_CalledUnderLock(); // Search through the latest lsp solutions to find the document with matching uri and client name. var findDocumentResult = FindDocuments(textDocumentIdentifier.Uri, currentLspSolutions, clientName, _requestTelemetryLogger, _logger); if (findDocumentResult.IsEmpty) { return null; } // Filter the matching documents by project context. var documentInProjectContext = findDocumentResult.FindDocumentInProjectContext(textDocumentIdentifier); return documentInProjectContext; } } #endregion /// <summary> /// Helper to clear out the LSP incremental solution for all registered workspaces. /// Should be called under <see cref="_gate"/> /// </summary> private void ResetIncrementalLspSolutions_CalledUnderLock() { Contract.ThrowIfFalse(Monitor.IsEntered(_gate)); var workspaces = _workspaceToLspSolution.Keys.ToImmutableArray(); foreach (var workspace in workspaces) { _workspaceToLspSolution[workspace] = null; } } /// <summary> /// Helper to get LSP solutions for all the registered workspaces. /// If the incremental lsp solution is missing, this will re-fork from the workspace. /// Should be called under <see cref="_gate"/> /// </summary> private ImmutableArray<Solution> ComputeIncrementalLspSolutions_CalledUnderLock() { Contract.ThrowIfFalse(Monitor.IsEntered(_gate)); var workspacePairs = _workspaceToLspSolution.ToImmutableArray(); using var updatedSolutions = TemporaryArray<Solution>.Empty; foreach (var (workspace, incrementalSolution) in workspacePairs) { if (incrementalSolution == null) { // We have no incremental lsp solution, create a new one forked from the workspace with LSP tracked documents. var newIncrementalSolution = GetSolutionWithReplacedDocuments(workspace.CurrentSolution, _trackedDocuments.Select(k => (k.Key, k.Value)).ToImmutableArray()); _workspaceToLspSolution[workspace] = newIncrementalSolution; updatedSolutions.Add(newIncrementalSolution); } else { updatedSolutions.Add(incrementalSolution); } } return updatedSolutions.ToImmutableAndClear(); } /// <summary> /// Looks for document(s - e.g. linked docs) from a single solution matching the input URI in the set of passed in solutions. /// /// Client name is used in razor cases to filter out non-razor documents. However once we switch fully over to pull /// diagnostics, the client should only ever ask the razor server about razor documents, so we may be able to remove it here. /// </summary> private static ImmutableArray<Document> FindDocuments( Uri uri, ImmutableArray<Solution> registeredSolutions, string? clientName, RequestTelemetryLogger telemetryLogger, ILspLogger logger) { logger.TraceInformation($"Finding document corresponding to {uri}"); // Ensure we search the lsp misc files solution last if it is present. registeredSolutions = registeredSolutions .Where(solution => solution.Workspace is not LspMiscellaneousFilesWorkspace) .Concat(registeredSolutions.Where(solution => solution.Workspace is LspMiscellaneousFilesWorkspace)).ToImmutableArray(); // First search the registered workspaces for documents with a matching URI. if (TryGetDocumentsForUri(uri, registeredSolutions, clientName, out var documents, out var solution)) { telemetryLogger.UpdateFindDocumentTelemetryData(success: true, solution.Workspace.Kind); logger.TraceInformation($"{documents.Value.First().FilePath} found in workspace {solution.Workspace.Kind}"); return documents.Value; } // We didn't find the document in any workspace, record a telemetry notification that we did not find it. var searchedWorkspaceKinds = string.Join(";", registeredSolutions.SelectAsArray(s => s.Workspace.Kind)); logger.TraceError($"Could not find '{uri}' with client name '{clientName}'. Searched {searchedWorkspaceKinds}"); telemetryLogger.UpdateFindDocumentTelemetryData(success: false, workspaceKind: null); return ImmutableArray<Document>.Empty; static bool TryGetDocumentsForUri( Uri uri, ImmutableArray<Solution> registeredSolutions, string? clientName, [NotNullWhen(true)] out ImmutableArray<Document>? documents, [NotNullWhen(true)] out Solution? solution) { foreach (var registeredSolution in registeredSolutions) { var matchingDocuments = registeredSolution.GetDocuments(uri, clientName); if (matchingDocuments.Any()) { documents = matchingDocuments; solution = registeredSolution; return true; } } documents = null; solution = null; return false; } } /// <summary> /// Gets a solution that represents the workspace view of the world (as passed in via the solution parameter) /// but with document text for any open documents updated to match the LSP view of the world. This makes /// the LSP server the source of truth for all document text, but all other changes come from the workspace /// </summary> private static Solution GetSolutionWithReplacedDocuments(Solution solution, ImmutableArray<(Uri DocumentUri, SourceText Text)> documentsToReplace) { foreach (var (uri, text) in documentsToReplace) { var documentIds = solution.GetDocumentIds(uri); // The tracked document might not be a part of this solution. if (documentIds.Any()) { solution = solution.WithDocumentText(documentIds, text); } } return solution; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly LspWorkspaceManager _manager; public TestAccessor(LspWorkspaceManager manager) => _manager = manager; public LspMiscellaneousFilesWorkspace? GetLspMiscellaneousFilesWorkspace() => _manager._lspMiscellaneousFilesWorkspace; public ImmutableDictionary<Workspace, Solution?> GetWorkspaceState() { lock (_manager._gate) { return _manager._workspaceToLspSolution.ToImmutableDictionary(); } } /// <summary> /// Used to ensure that tests start with a consistent state in the LSP manager /// no matter what workspace events were triggered during creation. /// </summary> public void ResetLspSolutions() { lock (_manager._gate) { _manager.ResetIncrementalLspSolutions_CalledUnderLock(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.LanguageServer.Handler.RequestExecutionQueue; namespace Microsoft.CodeAnalysis.LanguageServer; /// <summary> /// Manages the registered workspaces and corresponding LSP solutions for an LSP server. /// This type is tied to a particular server. /// </summary> /// <remarks> /// This is built to store incremental solutions that we update based on LSP text changes. This solution is <b>eventually consistent</b> with the workspace: /// <list type="bullet"> /// <item> When LSP text changes come in, we only fork the relevant document. </item> /// <item> We listen to workspace events. When we receive an event that is not for an LSP open document, /// we delete our incremental LSP solution so that we can fork the workspace with all open LSP documents. </item> /// </list> /// /// Doing incremental forking like this is more complex, but has a few nice properties: /// <list type="bullet"> /// <item>LSP didChange events only cause us to update the document that changed, not all open documents.</item> /// <item>Since we incrementally update our LSP documents, we only have to re-parse the document that changed.</item> /// <item>Since we incrementally update our LSP documents, project versions for other open documents remain unchanged.</item> /// <item>We are not reliant on the workspace being updated frequently (which it is not in VSCode) to do checksum diffing between LSP and the workspace.</item> /// </list> /// </remarks> internal class LspWorkspaceManager : IDocumentChangeTracker, IDisposable { /// <summary> /// Lock to gate access to the <see cref="_workspaceToLspSolution"/> and <see cref="_trackedDocuments"/> /// Access from the LSP server is serial as the LSP queue is processed serially until /// after we give the solution to the request handlers. However workspace events can interleave /// so we must protect against concurrent access here. /// </summary> private readonly object _gate = new(); /// <summary> /// A map from the registered workspace to the running lsp solution with incremental changes from LSP /// text sync applied to it. /// All workspaces registered by the <see cref="LspWorkspaceRegistrationService"/> are added as keys to this dictionary /// with a null value (solution) initially. As LSP text changes come in, we create the incremental solution from the workspace and update it with changes. /// When we detect a change that requires us to re-fork the LSP solution from the workspace we null out the solution for the key. /// </summary> private readonly Dictionary<Workspace, Solution?> _workspaceToLspSolution = new(); /// <summary> /// Stores the current source text for each URI that is being tracked by LSP. /// Each time an LSP text sync notification comes in, this source text is updated to match. /// Used as the backing implementation for the <see cref="IDocumentChangeTracker"/>. /// /// Note that the text here is tracked regardless of whether or not we found a matching roslyn document /// for the URI. /// </summary> private ImmutableDictionary<Uri, SourceText> _trackedDocuments = ImmutableDictionary<Uri, SourceText>.Empty; private readonly string _hostWorkspaceKind; private readonly ILspLogger _logger; private readonly LspMiscellaneousFilesWorkspace? _lspMiscellaneousFilesWorkspace; private readonly LspWorkspaceRegistrationService _lspWorkspaceRegistrationService; private readonly RequestTelemetryLogger _requestTelemetryLogger; public LspWorkspaceManager( ILspLogger logger, LspMiscellaneousFilesWorkspace? lspMiscellaneousFilesWorkspace, LspWorkspaceRegistrationService lspWorkspaceRegistrationService, RequestTelemetryLogger requestTelemetryLogger) { _hostWorkspaceKind = lspWorkspaceRegistrationService.GetHostWorkspaceKind(); _lspMiscellaneousFilesWorkspace = lspMiscellaneousFilesWorkspace; _logger = logger; _requestTelemetryLogger = requestTelemetryLogger; _lspWorkspaceRegistrationService = lspWorkspaceRegistrationService; // This server may have been started after workspaces were registered, we need to ensure we know about them. foreach (var workspace in lspWorkspaceRegistrationService.GetAllRegistrations()) { OnWorkspaceRegistered(this, new LspWorkspaceRegisteredEventArgs(workspace)); } lspWorkspaceRegistrationService.WorkspaceRegistered += OnWorkspaceRegistered; } public void Dispose() { // Workspace events can come in while we're disposing of an LSP server (e.g. restart). lock (_gate) { _lspWorkspaceRegistrationService.WorkspaceRegistered -= OnWorkspaceRegistered; foreach (var registeredWorkspace in _workspaceToLspSolution.Keys) { registeredWorkspace.WorkspaceChanged -= OnWorkspaceChanged; } _workspaceToLspSolution.Clear(); } } #region Workspace Updates /// <summary> /// Handles cases where a new workspace is registered after an LSP server is already started. /// For example, in VS the metadata as source workspace is not created until a metadata files is opened. /// </summary> private void OnWorkspaceRegistered(object? sender, LspWorkspaceRegisteredEventArgs e) { lock (_gate) { // Set the LSP solution for the workspace to null so that when asked we fork from the workspace. _workspaceToLspSolution.Add(e.Workspace, null); e.Workspace.WorkspaceChanged += OnWorkspaceChanged; _logger.TraceInformation($"Registered workspace {e.Workspace.Kind}"); } } /// <summary> /// Subscribed to the <see cref="Workspace.WorkspaceChanged"/> event for registered workspaces. /// If the workspace change is a change to an open LSP document, we ignore the change event as LSP will update us. /// If the workspace change is a change to a non-open document / project change, we trigger a fork from the workspace. /// </summary> private void OnWorkspaceChanged(object? sender, WorkspaceChangeEventArgs e) { var workspace = e.NewSolution.Workspace; if (e.Kind is WorkspaceChangeKind.DocumentChanged) { Contract.ThrowIfNull(e.DocumentId, $"DocumentId missing for document change event {e.Kind}"); // Retrieve the current state of documents owned by LSP. It is not necessarily // consistent with the workspace, but if the documents owned by LSP change we fork from the workspace // and will eventually become consistent. ImmutableDictionary<Uri, SourceText> trackedDocuments; lock (_gate) { trackedDocuments = _trackedDocuments; } if (IsDocumentTrackedByLsp(e.DocumentId, e.NewSolution, trackedDocuments)) { // We're tracking the document already, no need to fork the workspace to get the changes, LSP will have sent them to us. return; } } lock (_gate) { // Documents added/removed, changes to additional docs, closed document changes, any changes to the project, or any changes to the solution // mean we need to re-fork from the workspace to ensure that the lsp solution contains these updates. _workspaceToLspSolution[workspace] = null; } bool IsDocumentTrackedByLsp(DocumentId changedDocumentId, Solution newWorkspaceSolution, ImmutableDictionary<Uri, SourceText> trackedDocuments) { var changedDocument = newWorkspaceSolution.GetRequiredDocument(changedDocumentId); var documentUri = changedDocument.TryGetURI(); return documentUri != null && trackedDocuments.ContainsKey(documentUri); } } #endregion #region Implementation of IDocumentChangeTracker /// <summary> /// Called by the <see cref="DidOpenHandler"/> when a document is opened in LSP. /// </summary> public void StartTracking(Uri uri, SourceText documentText) { lock (_gate) { // First, store the LSP view of the text as the uri is now owned by the LSP client. Contract.ThrowIfTrue(_trackedDocuments.ContainsKey(uri), $"didOpen received for {uri} which is already open."); _trackedDocuments = _trackedDocuments.Add(uri, documentText); // Make sure we reset/update our LSP incremental solutions now that we potentially have a new document. ResetIncrementalLspSolutions_CalledUnderLock(); var updatedSolutions = ComputeIncrementalLspSolutions_CalledUnderLock(); if (updatedSolutions.Any(solution => solution.GetDocuments(uri).Any())) { return; } // If we can't find the document in any of the registered workspaces, add it to our loose files workspace. var miscDocument = _lspMiscellaneousFilesWorkspace?.AddMiscellaneousDocument(uri, documentText); if (miscDocument != null) { _workspaceToLspSolution[miscDocument.Project.Solution.Workspace] = miscDocument.Project.Solution; } } } /// <summary> /// Called by the <see cref="DidCloseHandler"/> when a document is closed in LSP. /// </summary> public void StopTracking(Uri uri) { lock (_gate) { // First, stop tracking this URI and source text as it is no longer owned by LSP. Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(uri), $"didClose received for {uri} which is not open."); _trackedDocuments = _trackedDocuments.Remove(uri); // Trigger a fork of all workspaces, the LSP document text may not match the workspace and this document // may have been removed / moved to a different workspace. ResetIncrementalLspSolutions_CalledUnderLock(); // If the file was added to the LSP misc files workspace, it needs to be removed as we no longer care about it once closed. // If the misc document ended up being added to an actual workspace, we may have already removed it from LSP misc in UpdateLspDocument. _lspMiscellaneousFilesWorkspace?.TryRemoveMiscellaneousDocument(uri); } } /// <summary> /// Called by the <see cref="DidChangeHandler"/> when a document's text is updated in LSP. /// </summary> public void UpdateTrackedDocument(Uri uri, SourceText newSourceText) { lock (_gate) { // Store the updated LSP view of the source text. Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(uri), $"didChange received for {uri} which is not open."); _trackedDocuments = _trackedDocuments.SetItem(uri, newSourceText); // Get our current solutions and re-fork from the workspace as needed. var updatedSolutions = ComputeIncrementalLspSolutions_CalledUnderLock(); var findDocumentResult = FindDocuments(uri, updatedSolutions, clientName: null, _requestTelemetryLogger, _logger); if (findDocumentResult.IsEmpty) { // We didn't find this document in a registered workspace or in the misc workspace. // This can happen when workspace event processing is behind LSP and a new document was added that has not been reflected in the incremental LSP solution yet. // // This means that the LSP solution will be stale until the event is processed and will not be able to answer requests on this URI. // When the workspace event is processed, we will fork from the workspace and apply all missed incremental LSP text (stored in IDocumentChangeTracker) // to bring the incremental LSP solution up to date. // // TODO - Once we always create the misc files workspace we should never hit this path (when workspace events are behind the doc will go into misc). // Remove as part of https://github.com/dotnet/roslyn/issues/57243 return; } // Update all the documents that have a matching uri with the new source text and store as our new incremental solution. // We can have multiple documents with the same URI (e.g. linked documents). var solution = GetSolutionWithReplacedDocuments(findDocumentResult.First().Project.Solution, ImmutableArray.Create((uri, newSourceText))); _workspaceToLspSolution[solution.Workspace] = solution; if (solution.Workspace is not LspMiscellaneousFilesWorkspace && _lspMiscellaneousFilesWorkspace != null) { // If we found the uri in a workspace that isn't LSP misc files, we can remove it from the lsp misc files if it is there. // // Example: In VSCode, the server is started and file opened before the user has chosen which project/sln in the folder they want to open, // and therefore on didOpen the file gets put into LSP misc files. // // Once the workspace is updated with the document however, we proactively cleanup the lsp misc files workspace here // so that we don't keep lingering references around. _lspMiscellaneousFilesWorkspace.TryRemoveMiscellaneousDocument(uri); } } } public ImmutableDictionary<Uri, SourceText> GetTrackedLspText() { lock (_gate) { return _trackedDocuments; } } #endregion #region LSP Solution Retrieval /// <summary> /// Returns the LSP solution associated with the workspace with the specified <see cref="_hostWorkspaceKind"/>. /// This is the solution used for LSP requests that pertain to the entire workspace, for example code search or workspace diagnostics. /// </summary> public Solution? TryGetHostLspSolution() { lock (_gate) { // Ensure we have the latest lsp solutions var updatedSolutions = ComputeIncrementalLspSolutions_CalledUnderLock(); var hostWorkspaceSolution = updatedSolutions.FirstOrDefault(s => s.Workspace.Kind == _hostWorkspaceKind); return hostWorkspaceSolution; } } /// <summary> /// Returns a document with the LSP tracked text forked from the appropriate workspace solution. /// </summary> /// <param name="clientName"> /// Returns documents that have a matching client name. In razor scenarios this is to ensure that the Razor C# server /// only provides data for generated razor documents (which have a client name). /// </param> public Document? GetLspDocument(TextDocumentIdentifier textDocumentIdentifier, string? clientName) { lock (_gate) { // Ensure we have the latest lsp solutions var currentLspSolutions = ComputeIncrementalLspSolutions_CalledUnderLock(); // Search through the latest lsp solutions to find the document with matching uri and client name. var findDocumentResult = FindDocuments(textDocumentIdentifier.Uri, currentLspSolutions, clientName, _requestTelemetryLogger, _logger); if (findDocumentResult.IsEmpty) { return null; } // Filter the matching documents by project context. var documentInProjectContext = findDocumentResult.FindDocumentInProjectContext(textDocumentIdentifier); return documentInProjectContext; } } #endregion /// <summary> /// Helper to clear out the LSP incremental solution for all registered workspaces. /// Should be called under <see cref="_gate"/> /// </summary> private void ResetIncrementalLspSolutions_CalledUnderLock() { Contract.ThrowIfFalse(Monitor.IsEntered(_gate)); var workspaces = _workspaceToLspSolution.Keys.ToImmutableArray(); foreach (var workspace in workspaces) { _workspaceToLspSolution[workspace] = null; } } /// <summary> /// Helper to get LSP solutions for all the registered workspaces. /// If the incremental lsp solution is missing, this will re-fork from the workspace. /// Should be called under <see cref="_gate"/> /// </summary> private ImmutableArray<Solution> ComputeIncrementalLspSolutions_CalledUnderLock() { Contract.ThrowIfFalse(Monitor.IsEntered(_gate)); var workspacePairs = _workspaceToLspSolution.ToImmutableArray(); using var updatedSolutions = TemporaryArray<Solution>.Empty; foreach (var (workspace, incrementalSolution) in workspacePairs) { if (incrementalSolution == null) { // We have no incremental lsp solution, create a new one forked from the workspace with LSP tracked documents. var newIncrementalSolution = GetSolutionWithReplacedDocuments(workspace.CurrentSolution, _trackedDocuments.Select(k => (k.Key, k.Value)).ToImmutableArray()); _workspaceToLspSolution[workspace] = newIncrementalSolution; updatedSolutions.Add(newIncrementalSolution); } else { updatedSolutions.Add(incrementalSolution); } } return updatedSolutions.ToImmutableAndClear(); } /// <summary> /// Looks for document(s - e.g. linked docs) from a single solution matching the input URI in the set of passed in solutions. /// /// Client name is used in razor cases to filter out non-razor documents. However once we switch fully over to pull /// diagnostics, the client should only ever ask the razor server about razor documents, so we may be able to remove it here. /// </summary> private static ImmutableArray<Document> FindDocuments( Uri uri, ImmutableArray<Solution> registeredSolutions, string? clientName, RequestTelemetryLogger telemetryLogger, ILspLogger logger) { logger.TraceInformation($"Finding document corresponding to {uri}"); // Ensure we search the lsp misc files solution last if it is present. registeredSolutions = registeredSolutions .Where(solution => solution.Workspace is not LspMiscellaneousFilesWorkspace) .Concat(registeredSolutions.Where(solution => solution.Workspace is LspMiscellaneousFilesWorkspace)).ToImmutableArray(); // First search the registered workspaces for documents with a matching URI. if (TryGetDocumentsForUri(uri, registeredSolutions, clientName, out var documents, out var solution)) { telemetryLogger.UpdateFindDocumentTelemetryData(success: true, solution.Workspace.Kind); logger.TraceInformation($"{documents.Value.First().FilePath} found in workspace {solution.Workspace.Kind}"); return documents.Value; } // We didn't find the document in any workspace, record a telemetry notification that we did not find it. var searchedWorkspaceKinds = string.Join(";", registeredSolutions.SelectAsArray(s => s.Workspace.Kind)); logger.TraceError($"Could not find '{uri}' with client name '{clientName}'. Searched {searchedWorkspaceKinds}"); telemetryLogger.UpdateFindDocumentTelemetryData(success: false, workspaceKind: null); return ImmutableArray<Document>.Empty; static bool TryGetDocumentsForUri( Uri uri, ImmutableArray<Solution> registeredSolutions, string? clientName, [NotNullWhen(true)] out ImmutableArray<Document>? documents, [NotNullWhen(true)] out Solution? solution) { foreach (var registeredSolution in registeredSolutions) { var matchingDocuments = registeredSolution.GetDocuments(uri, clientName); if (matchingDocuments.Any()) { documents = matchingDocuments; solution = registeredSolution; return true; } } documents = null; solution = null; return false; } } /// <summary> /// Gets a solution that represents the workspace view of the world (as passed in via the solution parameter) /// but with document text for any open documents updated to match the LSP view of the world. This makes /// the LSP server the source of truth for all document text, but all other changes come from the workspace /// </summary> private static Solution GetSolutionWithReplacedDocuments(Solution solution, ImmutableArray<(Uri DocumentUri, SourceText Text)> documentsToReplace) { foreach (var (uri, text) in documentsToReplace) { var documentIds = solution.GetDocumentIds(uri); // The tracked document might not be a part of this solution. if (documentIds.Any()) { solution = solution.WithDocumentText(documentIds, text); } } return solution; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly LspWorkspaceManager _manager; public TestAccessor(LspWorkspaceManager manager) => _manager = manager; public LspMiscellaneousFilesWorkspace? GetLspMiscellaneousFilesWorkspace() => _manager._lspMiscellaneousFilesWorkspace; public ImmutableDictionary<Workspace, Solution?> GetWorkspaceState() { lock (_manager._gate) { return _manager._workspaceToLspSolution.ToImmutableDictionary(); } } /// <summary> /// Used to ensure that tests start with a consistent state in the LSP manager /// no matter what workspace events were triggered during creation. /// </summary> public void ResetLspSolutions() { lock (_manager._gate) { _manager.ResetIncrementalLspSolutions_CalledUnderLock(); } } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/Core/EditorConfigSettings/Data/CodeStyle/CodeStyleSetting.BooleanCodeStyleSetting.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract partial class CodeStyleSetting { private class BooleanCodeStyleSetting : BooleanCodeStyleSettingBase { private readonly Option2<CodeStyleOption2<bool>> _option; private readonly AnalyzerConfigOptions _editorConfigOptions; private readonly OptionSet _visualStudioOptions; public BooleanCodeStyleSetting(Option2<CodeStyleOption2<bool>> option, string description, string? trueValueDescription, string? falseValueDescription, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) : base(description, option.Group.Description, trueValueDescription, falseValueDescription, updater) { _option = option; _editorConfigOptions = editorConfigOptions; _visualStudioOptions = visualStudioOptions; Location = new SettingLocation(IsDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); } public override bool IsDefinedInEditorConfig => _editorConfigOptions.TryGetEditorConfigOption<CodeStyleOption2<bool>>(_option, out _); public override SettingLocation Location { get; protected set; } protected override void ChangeSeverity(NotificationOption2 severity) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithNotification(severity)); } public override void ChangeValue(int valueIndex) { var value = valueIndex == 0; ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithValue(value)); } protected override CodeStyleOption2<bool> GetOption() => _editorConfigOptions.TryGetEditorConfigOption(_option, out CodeStyleOption2<bool>? value) && value is not null ? value : _visualStudioOptions.GetOption(_option); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract partial class CodeStyleSetting { private class BooleanCodeStyleSetting : BooleanCodeStyleSettingBase { private readonly Option2<CodeStyleOption2<bool>> _option; private readonly AnalyzerConfigOptions _editorConfigOptions; private readonly OptionSet _visualStudioOptions; public BooleanCodeStyleSetting(Option2<CodeStyleOption2<bool>> option, string description, string? trueValueDescription, string? falseValueDescription, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) : base(description, option.Group.Description, trueValueDescription, falseValueDescription, updater) { _option = option; _editorConfigOptions = editorConfigOptions; _visualStudioOptions = visualStudioOptions; Location = new SettingLocation(IsDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); } public override bool IsDefinedInEditorConfig => _editorConfigOptions.TryGetEditorConfigOption<CodeStyleOption2<bool>>(_option, out _); public override SettingLocation Location { get; protected set; } protected override void ChangeSeverity(NotificationOption2 severity) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithNotification(severity)); } public override void ChangeValue(int valueIndex) { var value = valueIndex == 0; ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithValue(value)); } protected override CodeStyleOption2<bool> GetOption() => _editorConfigOptions.TryGetEditorConfigOption(_option, out CodeStyleOption2<bool>? value) && value is not null ? value : _visualStudioOptions.GetOption(_option); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/CSharpTest2/Recommendations/AssemblyKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AssemblyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttribute() { await VerifyKeywordAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeNestClass() { await VerifyAbsenceAsync( @"class A { [$$ class B { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeNamespace() { await VerifyKeywordAsync( @"[$$ namespace Goo {"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeFileScopedNamespace() { await VerifyKeywordAsync( @"[$$ namespace Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeNamespaceWithoutOpenBracket() { await VerifyAbsenceAsync( @"$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeNamespaceAndAfterUsingWithNoOpenBracket() { await VerifyAbsenceAsync( @" using System; $$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeBeforeNamespaceAndAfterGlobalUsingWithNoOpenBracket() { await VerifyAbsenceAsync( @" global using System; $$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeNamespaceAndAfterUsingWithOpenBracket() { await VerifyKeywordAsync( @" using System; [$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeBeforeNamespaceAndAfterGlobalUsingWithOpenBracket() { await VerifyKeywordAsync( @" global using System; [$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeAssemblyWithOpenBracket() { await VerifyKeywordAsync( @" [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeClass() { await VerifyKeywordAsync( @" [$$ class Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeInterface() { await VerifyKeywordAsync( @" [$$ interface IGoo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeStruct() { await VerifyKeywordAsync( @" [$$ struct Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeEnum() { await VerifyKeywordAsync( @" [$$ enum Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeOtherAttributeWithoutOpenBracket() { await VerifyAbsenceAsync( @" $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterUsingWithoutOpenBracket() { await VerifyAbsenceAsync( @" using System; $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() { await VerifyAbsenceAsync( @" global using System; $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInBeforeAttributeAssemblyAttributeAndAfterUsingWithoutOpenBracket() { await VerifyKeywordAsync( @" using System; [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInBeforeAttributeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() { await VerifyKeywordAsync( @" global using System; [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttributeInNamespace() { await VerifyAbsenceAsync( @"namespace Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInElementAccess() { await VerifyAbsenceAsync( @"class C { void Goo(string[] array) { array[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInIndex() { await VerifyAbsenceAsync( @"class C { public int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassAssemblyParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateAssemblyParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodAssemblyParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AssemblyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttribute() { await VerifyKeywordAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeNestClass() { await VerifyAbsenceAsync( @"class A { [$$ class B { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeNamespace() { await VerifyKeywordAsync( @"[$$ namespace Goo {"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeFileScopedNamespace() { await VerifyKeywordAsync( @"[$$ namespace Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeNamespaceWithoutOpenBracket() { await VerifyAbsenceAsync( @"$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeNamespaceAndAfterUsingWithNoOpenBracket() { await VerifyAbsenceAsync( @" using System; $$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeBeforeNamespaceAndAfterGlobalUsingWithNoOpenBracket() { await VerifyAbsenceAsync( @" global using System; $$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeNamespaceAndAfterUsingWithOpenBracket() { await VerifyKeywordAsync( @" using System; [$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeBeforeNamespaceAndAfterGlobalUsingWithOpenBracket() { await VerifyKeywordAsync( @" global using System; [$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeAssemblyWithOpenBracket() { await VerifyKeywordAsync( @" [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeClass() { await VerifyKeywordAsync( @" [$$ class Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeInterface() { await VerifyKeywordAsync( @" [$$ interface IGoo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeStruct() { await VerifyKeywordAsync( @" [$$ struct Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeEnum() { await VerifyKeywordAsync( @" [$$ enum Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeOtherAttributeWithoutOpenBracket() { await VerifyAbsenceAsync( @" $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterUsingWithoutOpenBracket() { await VerifyAbsenceAsync( @" using System; $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() { await VerifyAbsenceAsync( @" global using System; $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInBeforeAttributeAssemblyAttributeAndAfterUsingWithoutOpenBracket() { await VerifyKeywordAsync( @" using System; [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInBeforeAttributeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() { await VerifyKeywordAsync( @" global using System; [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttributeInNamespace() { await VerifyAbsenceAsync( @"namespace Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInElementAccess() { await VerifyAbsenceAsync( @"class C { void Goo(string[] array) { array[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInIndex() { await VerifyAbsenceAsync( @"class C { public int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassAssemblyParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateAssemblyParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodAssemblyParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ReadOnlyRegionsChangedEventSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class ReadOnlyRegionsChangedEventSource : AbstractTaggerEventSource { private readonly ITextBuffer _subjectBuffer; public ReadOnlyRegionsChangedEventSource(ITextBuffer subjectBuffer) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; } public override void Connect() => _subjectBuffer.ReadOnlyRegionsChanged += OnReadOnlyRegionsChanged; public override void Disconnect() => _subjectBuffer.ReadOnlyRegionsChanged -= OnReadOnlyRegionsChanged; private void OnReadOnlyRegionsChanged(object? sender, SnapshotSpanEventArgs e) => this.RaiseChanged(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class ReadOnlyRegionsChangedEventSource : AbstractTaggerEventSource { private readonly ITextBuffer _subjectBuffer; public ReadOnlyRegionsChangedEventSource(ITextBuffer subjectBuffer) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; } public override void Connect() => _subjectBuffer.ReadOnlyRegionsChanged += OnReadOnlyRegionsChanged; public override void Disconnect() => _subjectBuffer.ReadOnlyRegionsChanged -= OnReadOnlyRegionsChanged; private void OnReadOnlyRegionsChanged(object? sender, SnapshotSpanEventArgs e) => this.RaiseChanged(); } } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Tools/Source/CompilerGeneratorTools/Source/IOperationGenerator/Model.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Xml; using System.Xml.Serialization; #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. namespace IOperationGenerator { [XmlRoot] public class Tree { [XmlAttribute] public string Root; [XmlElement(ElementName = "UnusedOperationKinds")] public OperationKind UnusedOperationKinds; [XmlElement(ElementName = "Node", Type = typeof(Node))] [XmlElement(ElementName = "AbstractNode", Type = typeof(AbstractNode))] public List<TreeType> Types; } public class TreeType { [XmlAttribute] public string Name; [XmlAttribute] public string Base; [XmlAttribute] public string? Namespace; [XmlAttribute(AttributeName = "Internal")] public string? InternalText; public bool IsInternal => InternalText is "true"; [XmlElement(ElementName = "Comments", Type = typeof(Comments))] public Comments Comments; } public class AbstractNode : TreeType { [XmlElement(ElementName = "Property", Type = typeof(Property))] public List<Property> Properties; [XmlElement(ElementName = "Obsolete", Type = typeof(ObsoleteTag))] public ObsoleteTag? Obsolete; [XmlElement(ElementName = "OperationKind", Type = typeof(OperationKind))] public OperationKind? OperationKind; [XmlAttribute(AttributeName = "SkipClassGeneration")] public string SkipClassGenerationText; public bool SkipClassGeneration => SkipClassGenerationText == "true"; public virtual bool IsAbstract => true; } public class Node : AbstractNode { [XmlAttribute] public string? VisitorName; [XmlAttribute(AttributeName = "SkipInVisitor")] public string? SkipInVisitorText; public bool SkipInVisitor => SkipInVisitorText == "true"; [XmlAttribute(AttributeName = "SkipChildrenGeneration")] public string? SkipChildrenGenerationText; public bool SkipChildrenGeneration => SkipChildrenGenerationText == "true"; [XmlAttribute(AttributeName = "SkipInCloner")] public string? SkipInClonerText; public bool SkipInCloner => SkipInClonerText == "true"; [XmlAttribute] public string? ChildrenOrder; public override bool IsAbstract => false; [XmlAttribute(AttributeName = "HasType")] public string HasTypeText; public bool HasType => HasTypeText == "true"; [XmlAttribute(AttributeName = "HasConstantValue")] public string HasConstantValueText; public bool HasConstantValue => HasConstantValueText == "true"; } public class Kind { [XmlAttribute] public string Name; } public class Property { [XmlAttribute] public string Name; [XmlAttribute] public string Type; [XmlAttribute(AttributeName = "New")] public string NewText; public bool IsNew => NewText == "true"; [XmlAttribute(AttributeName = "Internal")] public string? IsInternalText; public bool IsInternal => IsInternalText == "true"; [XmlAttribute(AttributeName = "SkipGeneration")] public string? SkipGenerationText; public bool SkipGeneration => SkipGenerationText == "true"; [XmlAttribute(AttributeName = "MakeAbstract")] public string? MakeAbstractText; public bool MakeAbstract => MakeAbstractText == "true"; [XmlElement(ElementName = "Comments", Type = typeof(Comments))] public Comments? Comments; } public class OperationKind { [XmlAttribute(AttributeName = "Include")] public string? IncludeText; public bool? Include => IncludeText is null ? (bool?)null : IncludeText == "true"; [XmlAttribute] public string? ExtraDescription; [XmlElement(ElementName = "Entry", Type = typeof(OperationKindEntry))] public List<OperationKindEntry> Entries; } public class OperationKindEntry { [XmlAttribute] public string Name; [XmlAttribute(AttributeName = "Value")] public string ValueText; public int Value => int.Parse(ValueText.Substring(2), System.Globalization.NumberStyles.HexNumber); [XmlAttribute(AttributeName = "EditorBrowsable")] public string? EditorBrowsableText; public bool? EditorBrowsable => EditorBrowsableText is null ? (bool?)null : EditorBrowsableText == "true"; [XmlAttribute] public string? ExtraDescription; } public class ObsoleteTag { [XmlAttribute(AttributeName = "Error")] public string ErrorText; [XmlText] public string Message; } public class Comments { [XmlAnyElement] public XmlElement[] Elements; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Xml; using System.Xml.Serialization; #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. namespace IOperationGenerator { [XmlRoot] public class Tree { [XmlAttribute] public string Root; [XmlElement(ElementName = "UnusedOperationKinds")] public OperationKind UnusedOperationKinds; [XmlElement(ElementName = "Node", Type = typeof(Node))] [XmlElement(ElementName = "AbstractNode", Type = typeof(AbstractNode))] public List<TreeType> Types; } public class TreeType { [XmlAttribute] public string Name; [XmlAttribute] public string Base; [XmlAttribute] public string? Namespace; [XmlAttribute(AttributeName = "Internal")] public string? InternalText; public bool IsInternal => InternalText is "true"; [XmlElement(ElementName = "Comments", Type = typeof(Comments))] public Comments Comments; } public class AbstractNode : TreeType { [XmlElement(ElementName = "Property", Type = typeof(Property))] public List<Property> Properties; [XmlElement(ElementName = "Obsolete", Type = typeof(ObsoleteTag))] public ObsoleteTag? Obsolete; [XmlElement(ElementName = "OperationKind", Type = typeof(OperationKind))] public OperationKind? OperationKind; [XmlAttribute(AttributeName = "SkipClassGeneration")] public string SkipClassGenerationText; public bool SkipClassGeneration => SkipClassGenerationText == "true"; public virtual bool IsAbstract => true; } public class Node : AbstractNode { [XmlAttribute] public string? VisitorName; [XmlAttribute(AttributeName = "SkipInVisitor")] public string? SkipInVisitorText; public bool SkipInVisitor => SkipInVisitorText == "true"; [XmlAttribute(AttributeName = "SkipChildrenGeneration")] public string? SkipChildrenGenerationText; public bool SkipChildrenGeneration => SkipChildrenGenerationText == "true"; [XmlAttribute(AttributeName = "SkipInCloner")] public string? SkipInClonerText; public bool SkipInCloner => SkipInClonerText == "true"; [XmlAttribute] public string? ChildrenOrder; public override bool IsAbstract => false; [XmlAttribute(AttributeName = "HasType")] public string HasTypeText; public bool HasType => HasTypeText == "true"; [XmlAttribute(AttributeName = "HasConstantValue")] public string HasConstantValueText; public bool HasConstantValue => HasConstantValueText == "true"; } public class Kind { [XmlAttribute] public string Name; } public class Property { [XmlAttribute] public string Name; [XmlAttribute] public string Type; [XmlAttribute(AttributeName = "New")] public string NewText; public bool IsNew => NewText == "true"; [XmlAttribute(AttributeName = "Internal")] public string? IsInternalText; public bool IsInternal => IsInternalText == "true"; [XmlAttribute(AttributeName = "SkipGeneration")] public string? SkipGenerationText; public bool SkipGeneration => SkipGenerationText == "true"; [XmlAttribute(AttributeName = "MakeAbstract")] public string? MakeAbstractText; public bool MakeAbstract => MakeAbstractText == "true"; [XmlElement(ElementName = "Comments", Type = typeof(Comments))] public Comments? Comments; } public class OperationKind { [XmlAttribute(AttributeName = "Include")] public string? IncludeText; public bool? Include => IncludeText is null ? (bool?)null : IncludeText == "true"; [XmlAttribute] public string? ExtraDescription; [XmlElement(ElementName = "Entry", Type = typeof(OperationKindEntry))] public List<OperationKindEntry> Entries; } public class OperationKindEntry { [XmlAttribute] public string Name; [XmlAttribute(AttributeName = "Value")] public string ValueText; public int Value => int.Parse(ValueText.Substring(2), System.Globalization.NumberStyles.HexNumber); [XmlAttribute(AttributeName = "EditorBrowsable")] public string? EditorBrowsableText; public bool? EditorBrowsable => EditorBrowsableText is null ? (bool?)null : EditorBrowsableText == "true"; [XmlAttribute] public string? ExtraDescription; } public class ObsoleteTag { [XmlAttribute(AttributeName = "Error")] public string ErrorText; [XmlText] public string Message; } public class Comments { [XmlAnyElement] public XmlElement[] Elements; } }
-1
dotnet/roslyn
56,276
Interpolated string handler IOperation support
Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
333fred
"2021-09-09T01:14:50Z"
"2021-10-29T17:30:37Z"
a883f5d9db3ba7cb80e43b4db6c90f77bf32fcca
5256b889b47f5e120ad691d588c8c8b24351fe16
Interpolated string handler IOperation support. Support for interpolated strings in IOperation. Implements part 1 of https://github.com/dotnet/roslyn/issues/54718. CFG will come in a follow-up to keep the review size manageable.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/FileExtensionsMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// MEF metadata class used to find exports declared for a specific file extensions. /// </summary> internal class FileExtensionsMetadata { public IEnumerable<string> Extensions { get; } public FileExtensionsMetadata(IDictionary<string, object> data) => this.Extensions = ((IReadOnlyDictionary<string, object>)data).GetEnumerableMetadata<string>("Extensions"); public FileExtensionsMetadata(params string[] extensions) { if (extensions?.Length == 0) { throw new ArgumentException(nameof(extensions)); } this.Extensions = extensions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// MEF metadata class used to find exports declared for a specific file extensions. /// </summary> internal class FileExtensionsMetadata { public IEnumerable<string> Extensions { get; } public FileExtensionsMetadata(IDictionary<string, object> data) => this.Extensions = ((IReadOnlyDictionary<string, object>)data).GetEnumerableMetadata<string>("Extensions"); public FileExtensionsMetadata(params string[] extensions) { if (extensions?.Length == 0) { throw new ArgumentException(nameof(extensions)); } this.Extensions = extensions; } } }
-1