repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/IAnonymousTypeDisplayExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class IAnonymousTypeDisplayExtensions { public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes( this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position) { var result = parts; while (true) { var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType()); if (delegateAnonymousType == null) { break; } result = result == parts ? new List<SymbolDisplayPart>(parts) : result; ReplaceAnonymousType(result, delegateAnonymousType, service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position)); } return result; } private static void ReplaceAnonymousType( IList<SymbolDisplayPart> list, INamedTypeSymbol anonymousType, IEnumerable<SymbolDisplayPart> parts) { var index = list.IndexOf(p => anonymousType.Equals(p.Symbol)); if (index >= 0) { var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList(); list.Clear(); list.AddRange(result); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class IAnonymousTypeDisplayExtensions { public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes( this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position) { var result = parts; while (true) { var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType()); if (delegateAnonymousType == null) { break; } result = result == parts ? new List<SymbolDisplayPart>(parts) : result; ReplaceAnonymousType(result, delegateAnonymousType, service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position)); } return result; } private static void ReplaceAnonymousType( IList<SymbolDisplayPart> list, INamedTypeSymbol anonymousType, IEnumerable<SymbolDisplayPart> parts) { var index = list.IndexOf(p => anonymousType.Equals(p.Symbol)); if (index >= 0) { var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList(); list.Clear(); list.AddRange(result); } } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.MemberGroup.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Partial Friend Class InvocationExpressionSignatureHelpProvider Private Shared Function GetAccessibleMembers(invocationExpression As InvocationExpressionSyntax, semanticModel As SemanticModel, within As ISymbol, memberGroup As IEnumerable(Of ISymbol), cancellationToken As CancellationToken) As ImmutableArray(Of ISymbol) Dim throughType As ITypeSymbol = Nothing Dim expression = TryCast(invocationExpression.Expression, MemberAccessExpressionSyntax).GetExpressionOfMemberAccessExpression() ' if it is via a base expression "MyBase.", we know the "throughType" is the base class but ' we need to be able to tell between "New Base().M()" and "MyBase.M()". ' currently, Access check methods do not differentiate between them. ' so handle "MyBase." primary-expression here by nulling out "throughType" If expression IsNot Nothing AndAlso TypeOf expression IsNot MyBaseExpressionSyntax Then throughType = semanticModel.GetTypeInfo(expression, cancellationToken).Type End If If TypeOf invocationExpression.Expression Is SimpleNameSyntax AndAlso invocationExpression.IsInStaticContext() Then memberGroup = memberGroup.Where(Function(m) m.IsStatic) End If Return memberGroup.Where(Function(m) m.IsAccessibleWithin(within, throughType)).ToImmutableArray() End Function Private Shared Function GetMemberGroupItems(accessibleMembers As ImmutableArray(Of ISymbol), document As Document, invocationExpression As InvocationExpressionSyntax, semanticModel As SemanticModel) As IEnumerable(Of SignatureHelpItem) If accessibleMembers.Length = 0 Then Return SpecializedCollections.EmptyEnumerable(Of SignatureHelpItem)() End If Return accessibleMembers.Select( Function(s) ConvertMemberGroupMember(document, s, invocationExpression.SpanStart, semanticModel)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Partial Friend Class InvocationExpressionSignatureHelpProvider Private Shared Function GetAccessibleMembers(invocationExpression As InvocationExpressionSyntax, semanticModel As SemanticModel, within As ISymbol, memberGroup As IEnumerable(Of ISymbol), cancellationToken As CancellationToken) As ImmutableArray(Of ISymbol) Dim throughType As ITypeSymbol = Nothing Dim expression = TryCast(invocationExpression.Expression, MemberAccessExpressionSyntax).GetExpressionOfMemberAccessExpression() ' if it is via a base expression "MyBase.", we know the "throughType" is the base class but ' we need to be able to tell between "New Base().M()" and "MyBase.M()". ' currently, Access check methods do not differentiate between them. ' so handle "MyBase." primary-expression here by nulling out "throughType" If expression IsNot Nothing AndAlso TypeOf expression IsNot MyBaseExpressionSyntax Then throughType = semanticModel.GetTypeInfo(expression, cancellationToken).Type End If If TypeOf invocationExpression.Expression Is SimpleNameSyntax AndAlso invocationExpression.IsInStaticContext() Then memberGroup = memberGroup.Where(Function(m) m.IsStatic) End If Return memberGroup.Where(Function(m) m.IsAccessibleWithin(within, throughType)).ToImmutableArray() End Function Private Shared Function GetMemberGroupItems(accessibleMembers As ImmutableArray(Of ISymbol), document As Document, invocationExpression As InvocationExpressionSyntax, semanticModel As SemanticModel) As IEnumerable(Of SignatureHelpItem) If accessibleMembers.Length = 0 Then Return SpecializedCollections.EmptyEnumerable(Of SignatureHelpItem)() End If Return accessibleMembers.Select( Function(s) ConvertMemberGroupMember(document, s, invocationExpression.SpanStart, semanticModel)) End Function End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests_FixAllTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseThrowExpression { public partial class UseThrowExpressionTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocument1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string s, string t) { if (s == null) { {|FixAllInDocument:throw|} new ArgumentNullException(nameof(s)); } if (t == null) { throw new ArgumentNullException(nameof(t)); } _s = s; _t = t; } }", @"using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); _t = t ?? throw new ArgumentNullException(nameof(t)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocument2() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (t == null) { {|FixAllInDocument:throw|} new ArgumentNullException(nameof(t)); } _s = s; _t = t; } }", @"using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); _t = t ?? throw new ArgumentNullException(nameof(t)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocument3() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string s, string t) { if (s == null) { {|FixAllInDocument:throw new ArgumentNullException(nameof(s));|} } if (t == null) { throw new ArgumentNullException(nameof(t)); } _s = s; _t = t; } }", @"using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); _t = t ?? throw new ArgumentNullException(nameof(t)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocument4() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (t == null) { {|FixAllInDocument:throw new ArgumentNullException(nameof(t));|} } _s = s; _t = t; } }", @"using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); _t = t ?? throw new ArgumentNullException(nameof(t)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocumentDoNotTouchOtherDocuments() { await TestInRegularAndScriptAsync( @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { void M(string s, string t) { if (s == null) { {|FixAllInDocument:throw|} new ArgumentNullException(nameof(s)); } _s = s; } } </Document> <Document> using System; class D { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; } } </Document> </Project> </Workspace>", @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); } } </Document> <Document> using System; class D { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; } } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInProject1() { await TestInRegularAndScriptAsync( @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { void M(string s, string t) { if (s == null) { {|FixAllInProject:throw|} new ArgumentNullException(nameof(s)); } _s = s; } } </Document> <Document> using System; class D { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; } } </Document> </Project> </Workspace>", @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); } } </Document> <Document> using System; class D { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); } } </Document> </Project> </Workspace>"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseThrowExpression { public partial class UseThrowExpressionTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocument1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string s, string t) { if (s == null) { {|FixAllInDocument:throw|} new ArgumentNullException(nameof(s)); } if (t == null) { throw new ArgumentNullException(nameof(t)); } _s = s; _t = t; } }", @"using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); _t = t ?? throw new ArgumentNullException(nameof(t)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocument2() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (t == null) { {|FixAllInDocument:throw|} new ArgumentNullException(nameof(t)); } _s = s; _t = t; } }", @"using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); _t = t ?? throw new ArgumentNullException(nameof(t)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocument3() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string s, string t) { if (s == null) { {|FixAllInDocument:throw new ArgumentNullException(nameof(s));|} } if (t == null) { throw new ArgumentNullException(nameof(t)); } _s = s; _t = t; } }", @"using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); _t = t ?? throw new ArgumentNullException(nameof(t)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocument4() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (t == null) { {|FixAllInDocument:throw new ArgumentNullException(nameof(t));|} } _s = s; _t = t; } }", @"using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); _t = t ?? throw new ArgumentNullException(nameof(t)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInDocumentDoNotTouchOtherDocuments() { await TestInRegularAndScriptAsync( @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { void M(string s, string t) { if (s == null) { {|FixAllInDocument:throw|} new ArgumentNullException(nameof(s)); } _s = s; } } </Document> <Document> using System; class D { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; } } </Document> </Project> </Workspace>", @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); } } </Document> <Document> using System; class D { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; } } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] public async Task FixAllInProject1() { await TestInRegularAndScriptAsync( @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { void M(string s, string t) { if (s == null) { {|FixAllInProject:throw|} new ArgumentNullException(nameof(s)); } _s = s; } } </Document> <Document> using System; class D { void M(string s, string t) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; } } </Document> </Project> </Workspace>", @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); } } </Document> <Document> using System; class D { void M(string s, string t) { _s = s ?? throw new ArgumentNullException(nameof(s)); } } </Document> </Project> </Workspace>"); } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeStructTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeStructTests Inherits AbstractCodeStructTests #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> Structure $$S End Structure </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> Partial Structure $$S End Structure </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> Partial Structure $$S End Structure Partial Structure S End Structure </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Imports System Structure $$S End Structure </Code> Dim expected = <Code> Imports System &lt;Serializable()&gt; Structure S End Structure </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> Imports System &lt;Serializable&gt; Structure $$S End Structure </Code> Dim expected = <Code> Imports System &lt;Serializable&gt; &lt;CLSCompliant(True)&gt; Structure S End Structure </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> Imports System ''' &lt;summary&gt;&lt;/summary&gt; Structure $$S End Structure </Code> Dim expected = <Code> Imports System ''' &lt;summary&gt;&lt;/summary&gt; &lt;CLSCompliant(True)&gt; Structure S End Structure </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"}) End Function #End Region #Region "AddImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface1() As Task Dim code = <Code> Structure $$S End Structure </Code> Dim expected = <Code> Structure S Implements I End Structure </Code> Await TestAddImplementedInterface(code, "I", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface2() As Task Dim code = <Code> Structure $$S Implements I End Structure </Code> Dim expected = <Code> Structure S Implements J Implements I End Structure </Code> Await TestAddImplementedInterface(code, "J", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface3() As Task Dim code = <Code> Structure $$S Implements I End Structure </Code> Dim expected = <Code> Structure S Implements I Implements J End Structure </Code> Await TestAddImplementedInterface(code, "J", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddImplementedInterface4() Dim code = <Code> Structure $$S End Structure </Code> TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", 1) End Sub #End Region #Region "RemoveImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface1() As Task Dim code = <Code> Structure $$S Implements I End Structure </Code> Dim expected = <Code> Structure S End Structure </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestRemoveImplementedInterface2() Dim code = <Code> Structure $$S End Structure </Code> TestRemoveImplementedInterfaceThrows(Of COMException)(code, "I") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface3() As Task Dim code = <Code> Structure $$S Implements I, J End Structure </Code> Dim expected = <Code> Structure S Implements I End Structure </Code> Await TestRemoveImplementedInterface(code, "J", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface4() As Task Dim code = <Code> Structure $$S Implements I, J End Structure </Code> Dim expected = <Code> Structure S Implements J End Structure </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface5() As Task Dim code = <Code> Structure $$S Implements I, J, K End Structure </Code> Dim expected = <Code> Structure S Implements I, K End Structure </Code> Await TestRemoveImplementedInterface(code, "J", expected) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> Structure $$Goo End Structure </Code> Dim expected = <Code> Structure Bar End Structure </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "GenericExtender" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseTypesCount() Dim code = <Code> Structure S$$ End Structure </Code> TestGenericNameExtender_GetBaseTypesCount(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseGenericName() Dim code = <Code> Structure S$$ End Structure </Code> TestGenericNameExtender_GetBaseGenericName(code, 1, "System.ValueType") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplementedTypesCount1() Dim code = <Code> Structure S$$ End Structure </Code> TestGenericNameExtender_GetImplementedTypesCount(code, 0) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplementedTypesCount2() Dim code = <Code> Namespace N Structure S$$ Implements IGoo(Of Integer) End Structure Interface IGoo(Of T) End Interface End Namespace </Code> TestGenericNameExtender_GetImplementedTypesCount(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplTypeGenericName1() Dim code = <Code> Structure S$$ End Structure </Code> TestGenericNameExtender_GetImplTypeGenericName(code, 1, Nothing) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplTypeGenericName2() Dim code = <Code> Namespace N Structure S$$ Implements IGoo(Of Integer) End Structure Interface IGoo(Of T) End Interface End Namespace </Code> TestGenericNameExtender_GetImplTypeGenericName(code, 1, "N.IGoo(Of Integer)") End Sub #End Region Private Function GetGenericExtender(codeElement As EnvDTE80.CodeStruct2) As IVBGenericExtender Return CType(codeElement.Extender(ExtenderNames.VBGenericExtender), IVBGenericExtender) End Function Protected Overrides Function GenericNameExtender_GetBaseTypesCount(codeElement As EnvDTE80.CodeStruct2) As Integer Return GetGenericExtender(codeElement).GetBaseTypesCount() End Function Protected Overrides Function GenericNameExtender_GetImplementedTypesCount(codeElement As EnvDTE80.CodeStruct2) As Integer Return GetGenericExtender(codeElement).GetImplementedTypesCount() End Function Protected Overrides Function GenericNameExtender_GetBaseGenericName(codeElement As EnvDTE80.CodeStruct2, index As Integer) As String Return GetGenericExtender(codeElement).GetBaseGenericName(index) End Function Protected Overrides Function GenericNameExtender_GetImplTypeGenericName(codeElement As EnvDTE80.CodeStruct2, index As Integer) As String Return GetGenericExtender(codeElement).GetImplTypeGenericName(index) End Function Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeStructTests Inherits AbstractCodeStructTests #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> Structure $$S End Structure </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> Partial Structure $$S End Structure </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> Partial Structure $$S End Structure Partial Structure S End Structure </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Imports System Structure $$S End Structure </Code> Dim expected = <Code> Imports System &lt;Serializable()&gt; Structure S End Structure </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> Imports System &lt;Serializable&gt; Structure $$S End Structure </Code> Dim expected = <Code> Imports System &lt;Serializable&gt; &lt;CLSCompliant(True)&gt; Structure S End Structure </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> Imports System ''' &lt;summary&gt;&lt;/summary&gt; Structure $$S End Structure </Code> Dim expected = <Code> Imports System ''' &lt;summary&gt;&lt;/summary&gt; &lt;CLSCompliant(True)&gt; Structure S End Structure </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"}) End Function #End Region #Region "AddImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface1() As Task Dim code = <Code> Structure $$S End Structure </Code> Dim expected = <Code> Structure S Implements I End Structure </Code> Await TestAddImplementedInterface(code, "I", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface2() As Task Dim code = <Code> Structure $$S Implements I End Structure </Code> Dim expected = <Code> Structure S Implements J Implements I End Structure </Code> Await TestAddImplementedInterface(code, "J", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface3() As Task Dim code = <Code> Structure $$S Implements I End Structure </Code> Dim expected = <Code> Structure S Implements I Implements J End Structure </Code> Await TestAddImplementedInterface(code, "J", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddImplementedInterface4() Dim code = <Code> Structure $$S End Structure </Code> TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", 1) End Sub #End Region #Region "RemoveImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface1() As Task Dim code = <Code> Structure $$S Implements I End Structure </Code> Dim expected = <Code> Structure S End Structure </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestRemoveImplementedInterface2() Dim code = <Code> Structure $$S End Structure </Code> TestRemoveImplementedInterfaceThrows(Of COMException)(code, "I") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface3() As Task Dim code = <Code> Structure $$S Implements I, J End Structure </Code> Dim expected = <Code> Structure S Implements I End Structure </Code> Await TestRemoveImplementedInterface(code, "J", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface4() As Task Dim code = <Code> Structure $$S Implements I, J End Structure </Code> Dim expected = <Code> Structure S Implements J End Structure </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface5() As Task Dim code = <Code> Structure $$S Implements I, J, K End Structure </Code> Dim expected = <Code> Structure S Implements I, K End Structure </Code> Await TestRemoveImplementedInterface(code, "J", expected) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> Structure $$Goo End Structure </Code> Dim expected = <Code> Structure Bar End Structure </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "GenericExtender" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseTypesCount() Dim code = <Code> Structure S$$ End Structure </Code> TestGenericNameExtender_GetBaseTypesCount(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseGenericName() Dim code = <Code> Structure S$$ End Structure </Code> TestGenericNameExtender_GetBaseGenericName(code, 1, "System.ValueType") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplementedTypesCount1() Dim code = <Code> Structure S$$ End Structure </Code> TestGenericNameExtender_GetImplementedTypesCount(code, 0) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplementedTypesCount2() Dim code = <Code> Namespace N Structure S$$ Implements IGoo(Of Integer) End Structure Interface IGoo(Of T) End Interface End Namespace </Code> TestGenericNameExtender_GetImplementedTypesCount(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplTypeGenericName1() Dim code = <Code> Structure S$$ End Structure </Code> TestGenericNameExtender_GetImplTypeGenericName(code, 1, Nothing) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplTypeGenericName2() Dim code = <Code> Namespace N Structure S$$ Implements IGoo(Of Integer) End Structure Interface IGoo(Of T) End Interface End Namespace </Code> TestGenericNameExtender_GetImplTypeGenericName(code, 1, "N.IGoo(Of Integer)") End Sub #End Region Private Function GetGenericExtender(codeElement As EnvDTE80.CodeStruct2) As IVBGenericExtender Return CType(codeElement.Extender(ExtenderNames.VBGenericExtender), IVBGenericExtender) End Function Protected Overrides Function GenericNameExtender_GetBaseTypesCount(codeElement As EnvDTE80.CodeStruct2) As Integer Return GetGenericExtender(codeElement).GetBaseTypesCount() End Function Protected Overrides Function GenericNameExtender_GetImplementedTypesCount(codeElement As EnvDTE80.CodeStruct2) As Integer Return GetGenericExtender(codeElement).GetImplementedTypesCount() End Function Protected Overrides Function GenericNameExtender_GetBaseGenericName(codeElement As EnvDTE80.CodeStruct2, index As Integer) As String Return GetGenericExtender(codeElement).GetBaseGenericName(index) End Function Protected Overrides Function GenericNameExtender_GetImplTypeGenericName(codeElement As EnvDTE80.CodeStruct2, index As Integer) As String Return GetGenericExtender(codeElement).GetImplTypeGenericName(index) End Function Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Compilers/VisualBasic/Portable/Symbols/MissingNamespaceSymbol.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 Imports System.Collections.Immutable Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports Binder = Microsoft.CodeAnalysis.VisualBasic.Binder Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' A <see cref="MissingNamespaceSymbol"/> is a special kind of <see cref="NamespaceSymbol"/> that represents ''' a namespace that couldn't be found. ''' </summary> Friend Class MissingNamespaceSymbol Inherits NamespaceSymbol Private ReadOnly _name As String Private ReadOnly _containingSymbol As Symbol Public Sub New(containingModule As MissingModuleSymbol) Debug.Assert(containingModule IsNot Nothing) _containingSymbol = containingModule _name = String.Empty End Sub Public Sub New(containingNamespace As NamespaceSymbol, name As String) Debug.Assert(containingNamespace IsNot Nothing) Debug.Assert(name IsNot Nothing) _containingSymbol = containingNamespace _name = name End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingSymbol End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _containingSymbol.ContainingAssembly End Get End Property Friend Overrides ReadOnly Property Extent As NamespaceExtent Get If _containingSymbol.Kind = SymbolKind.NetModule Then Return New NamespaceExtent(DirectCast(_containingSymbol, ModuleSymbol)) End If Return DirectCast(_containingSymbol, NamespaceSymbol).Extent End Get End Property Public Overrides Function GetHashCode() As Integer Return Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode()) End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, MissingNamespaceSymbol) Return other IsNot Nothing AndAlso String.Equals(_name, other._name, StringComparison.Ordinal) AndAlso _containingSymbol.Equals(other._containingSymbol) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetModuleMembers() As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetModuleMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetMembers() As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Friend Overrides ReadOnly Property DeclaredAccessibilityOfMostAccessibleDescendantType As Accessibility Get Return Accessibility.Private End Get End Property Friend Overrides Sub AppendProbableExtensionMethods(name As String, methods As ArrayBuilder(Of MethodSymbol)) Return End Sub Friend Overrides Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder, appendThrough As NamespaceSymbol) Return End Sub Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol) Get Return ImmutableArray(Of NamedTypeSymbol).Empty End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Immutable Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports Binder = Microsoft.CodeAnalysis.VisualBasic.Binder Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' A <see cref="MissingNamespaceSymbol"/> is a special kind of <see cref="NamespaceSymbol"/> that represents ''' a namespace that couldn't be found. ''' </summary> Friend Class MissingNamespaceSymbol Inherits NamespaceSymbol Private ReadOnly _name As String Private ReadOnly _containingSymbol As Symbol Public Sub New(containingModule As MissingModuleSymbol) Debug.Assert(containingModule IsNot Nothing) _containingSymbol = containingModule _name = String.Empty End Sub Public Sub New(containingNamespace As NamespaceSymbol, name As String) Debug.Assert(containingNamespace IsNot Nothing) Debug.Assert(name IsNot Nothing) _containingSymbol = containingNamespace _name = name End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingSymbol End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _containingSymbol.ContainingAssembly End Get End Property Friend Overrides ReadOnly Property Extent As NamespaceExtent Get If _containingSymbol.Kind = SymbolKind.NetModule Then Return New NamespaceExtent(DirectCast(_containingSymbol, ModuleSymbol)) End If Return DirectCast(_containingSymbol, NamespaceSymbol).Extent End Get End Property Public Overrides Function GetHashCode() As Integer Return Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode()) End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, MissingNamespaceSymbol) Return other IsNot Nothing AndAlso String.Equals(_name, other._name, StringComparison.Ordinal) AndAlso _containingSymbol.Equals(other._containingSymbol) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetModuleMembers() As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetModuleMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetMembers() As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Friend Overrides ReadOnly Property DeclaredAccessibilityOfMostAccessibleDescendantType As Accessibility Get Return Accessibility.Private End Get End Property Friend Overrides Sub AppendProbableExtensionMethods(name As String, methods As ArrayBuilder(Of MethodSymbol)) Return End Sub Friend Overrides Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder, appendThrough As NamespaceSymbol) Return End Sub Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol) Get Return ImmutableArray(Of NamedTypeSymbol).Empty End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./docs/analyzers/FixAllProvider.md
Introduction ============ This document covers the following: - Introductory definitions - What is a FixAll occurrences code fix? - How is a FixAll occurrences code fix computed? - Adding FixAll support to your code fixer - Selecting an Equivalence key for code actions - Spectrum of FixAll providers - Built-in FixAllProvider and its limitations - Implementing a custom FixAllProvider Definitions =========== - **Analyzer:** An instance of a type derived from `DiagnosticAnalyzer` that reports diagnostics. - **Code fixer:** An instance of a type derived from `CodeFixProvider` that provides code fixes for compiler and/or analyzer diagnostics. - **Code refactoring:** An instance of a type derived from `CodeRefactoringProvider` that provides source code refactorings. - **Code action:** An action registered by `CodeFixProvider.RegisterCodeFixesAsync` that performs a code fix OR an action registered by `CodeRefactoringProvider.ComputeRefactoringsAsync` that performs a code refactoring. - **Equivalence Key:** A string value representing an equivalence class of all code actions registered by a code fixer or refactoring. Two code actions are treated as equivalent if they have equal `EquivalenceKey` values and were generated by the same code fixer or refactoring. - **FixAll provider:** An instance of a type derived from `FixAllProvider` that provides a FixAll occurrences code fix. A FixAll provider is associated with a corresponding code fixer by `CodeFixProvider.GetFixAllProvider` method. - **FixAll occurrences code fix:** A code action returned by `FixAllProvider.GetFixAsync`, that fixes all or multiple occurrences of diagnostics fixed by the corresponding code fixer, within a given `FixAllScope`. What is a FixAll occurrences code fix? ====================================== In layman terms, a FixAll occurrences code fix means: I have a code fix 'C', that fixes a specific instance of diagnostic 'D' in my source and I want to apply this fix to all instances of 'D' across a broader scope, such as a document or a project or the entire solution. In more technical terms: Given a particular code action registered by a code fixer to fix one or more diagnostics, a corresponding code action registered by its FixAll provider, that applies the original trigger code action across a broader scope (such as a document/project/solution) to fix multiple instances of such diagnostics. How is a FixAll occurrences code fix computed? ============================================== Following steps are used to compute a FixAll occurrences code fix: - Given a specific instance of a diagnostic, compute the set of code actions that claim to fix the diagnostic. - Select a specific code action from this set. In the Visual Studio IDE, this is done by selecting a specific code action in the light bulb menu. - The equivalence key of the selected code action represents the class of code actions that must be applied as part of a FixAll occurrences code fix. - Given this code action, get the FixAll provider corresponding to the code fixer that registered this code action. - If non-null, then request the FixAll provider for its supported FixAllScopes. - Select a specific `FixAllScope` from this set. In the Visual Studio IDE, this is done by clicking on the scope hyperlink in the preview dialog. - Given the trigger diagnostic(s), the equivalence key of the trigger code action, and the FixAll scope, invoke `FixAllProvider.GetFixAsync` to compute the FixAll occurrences code fix. Adding FixAll support to your code fixer ======================================== Follow the below steps to add FixAll support to your code fixer: - Override the `CodeFixProvider.GetFixAllProvider` method and return a non-null instance of a `FixAllProvider`. You may either use our built-in FixAllProvider or implement a custom FixAllProvider. See the following sections in this document for determining the correct approach for your fixer. - Ensure that all the code actions registered by your code fixer have a non-null equivalence key. See the following section to determine how to select an equivalence key. Selecting an Equivalence key for code actions ============================================= Each unique equivalence key for a code fixer defines a unique equivalence class of code actions. Equivalence key of the trigger code action is part of the `FixAllContext` and is used to determine the FixAll occurrences code fix. Normally, you can use the **'title'** of the code action as the equivalence key. However, there are cases where you may desire to have different values. Let us take an example to get a better understanding. Let us consider the [C# SimplifyTypeNamesCodeFixProvider](https://github.com/dotnet/roslyn/blob/main/src/Features/CSharp/Portable/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs) that registers multiple code actions and also has FixAll support. This code fixer offers fixes to simplify the following expressions: - `this` expressions of the form 'this.x' to 'x'. - Qualified type names of the form 'A.B' to 'B'. - Member access expressions of the form 'A.M' to 'M'. This fixer needs the following semantics for the corresponding FixAll occurrences code fixes: - `this` expression simplification: Fix all should simplify all this expressions, regardless of the member being accessed (this.x, this.y, this.z, etc.). - Qualified type name simplification: Fix all should simplify all qualified type names 'A.B' to 'B'. However, we don't want to simplify **all** qualified type names, such as 'C.D', 'E.F', etc. as that would be too generic a fix, which is not likely intended by the user. - Member access expressions: Fix all should simplify all member access expressions 'A.M' to 'M'. It uses the below equivalence keys for its registered code actions to get the desired FixAll behavior: - `this` expression simplification: Generic resource string "Simplify this expression", which explicitly excludes the contents of the node being simplified. - Qualified type name simplification: Formatted resource string "Simplify type name A.B", which explicitly includes the contents of the node being simplified. - Member access expressions: Formatted resource string "Simplify type name A.M", which explicitly includes the contents of the node being simplified. Note that '`this` expression simplification' fix requires a different kind of an equivalence class from the other two simplifications. See method [GetCodeActionId](https://github.com/dotnet/roslyn/blob/main/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs) for the actual implementation. To summarize, use the equivalence key that best suits the category of fixes to be applied as part of a FixAll operation. Spectrum of FixAll providers ============================ When multiple fixes need to be applied to documents, there are various ways to do it: - **Sequential approach**: One way to do it is to compute diagnostics, pick one, ask a fixer to produce a code action to fix that, apply it. Now for the resulting new compilation, recompute diagnostics, pick the next one and repeat the process. This approach would be very slow but would lead to correct results (unless it doesn't converge where one fix introduces a diagnostic that was just fixed by a previous fix). We chose to not implement this approach. - **Batch fix approach**: Another way is to compute all the diagnostics, pick each diagnostic and give it to a fixer and apply it to produce a new solution. If there were 'n' diagnostics, there would be 'n' new solutions. Now just merge them all together in one go. This may produce incorrect results (when different fixes change the same region of code in different ways) but it is very fast. We have one implementation of this approach in `WellKnownFixAllProviders.BatchFixer` - **Custom approach**: Depending on the fix, there may be a custom solution to fix multiple issues. For example, consider an analyzer that simply needs to generate one file as the fix for any instance of the issue. Instead of generating the same file over and over using the previous two approaches, one could write a custom `FixAllProvider` that simply generates the file once if there were any diagnostics at all. Since there are various ways of fixing all issues, we've implemented a framework and provided the one general implementation that we think is useful in many cases. Built-in FixAllProvider ======================= We provide a default `BatchFixAllProvider` implementation of a FixAll provider that uses the underlying code fixer to compute the FixAll occurrences code fixes. To use the batch fixer, you should return the static `WellKnownFixAllProviders.BatchFixer` instance in the `CodeFixProvider.GetFixAllProvider` override. NOTE: See the following section on **'Limitations of the BatchFixer'** to determine if the batch fixer can be used by your code fixer. Given a trigger diagnostic, a trigger code action, the underlying code fixer and the FixAll scope, the BatchFixer computes FixAll occurrences code fix with the following steps: - Compute all instances of the trigger diagnostic across the FixAll scope. - For each computed diagnostic, invoke the underlying code fixer to compute the set of code actions to fix the diagnostic. - Collect all the registered code actions that have the same equivalence key as the trigger code action. - Apply all these code actions on the original solution snapshot to compute new solution snapshots. The batch fixer only batches code action operations of type `ApplyChangesOperation` present within the individual code actions, other types of operations are ignored. - Sequentially merge the new solution snapshots into a final solution snapshot. Only non-conflicting code actions whose fix spans don't overlap the fix spans of prior merged code actions are retained. Limitations of the BatchFixer ============================= The BatchFixer is designed for a common category of fixers where fix spans for diagnostics don't overlap with each other. For example, assume there is a diagnostic that spans a particular expression, and a fixer that fixes that expression. If all the instances of this diagnostic are guaranteed to have non-overlapping spans, then their fixes can be computed independently and this batch of fixes can be subsequently merged together. However, there are cases where the BatchFixer might not work for your fixer. Following are some such examples: - Code fixer registers code actions without an equivalence key or with a null equivalence key. - Code fixer registers non-local code actions, i.e. a code action whose fix span is completely distinct from diagnostic span. For example, a fix that adds a new declaration node. Multiple such fixes are likely to have overlapping spans and hence could be conflicting. - Diagnostics to be fixed as part of FixAll occurrences have overlapping spans. It is likely that fixes for such diagnostics will have overlapping spans too, and hence would conflict with each other. - Code fixer registers code actions with operations other than `ApplyChangesOperation`. BatchFixer ignores such operations and hence may produce unexpected results. Implementing a custom FixAllProvider ==================================== For cases where you cannot use the BatchFixer, you must implement your own `FixAllProvider`. It is recommended that you create a singleton instance of the FixAll provider, instead of creating a new instance for every `CodeFixProvider.GetFixAllProvider` invocation. Following guidelines should help in the implementation: - **GetFixAsync:** Primary method to compute the FixAll occurrences code fix for a given `FixAllContext`. You may use the set of 'GetXXXDiagnosticsAsync' methods on the `FixAllContext` to compute the diagnostics to be fixed. You must return a single code action that fixes all the diagnostics in the given FixAll scope. - **GetSupportedFixAllScopes:** Virtual method to get all the supported FixAll scopes. By default, it returns all the three supported scopes: document, project and solution scopes. Generally, you need not override this method. However, you may do so if you wish to support a subset of these scopes. - **GetSupportedFixAllDiagnosticIds:** Virtual method to get all the fixable diagnostic ids. By default, it returns the underlying code fixer's `FixableDiagnosticIds`. Generally, you need not override this method. However, you may do so if you wish to support FixAll only for a subset of these ids. See [DeclarePublicAPIFix](https://github.com/dotnet/roslyn-analyzers/blob/main/src/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs) for an example implementation of a custom FixAllProvider.
Introduction ============ This document covers the following: - Introductory definitions - What is a FixAll occurrences code fix? - How is a FixAll occurrences code fix computed? - Adding FixAll support to your code fixer - Selecting an Equivalence key for code actions - Spectrum of FixAll providers - Built-in FixAllProvider and its limitations - Implementing a custom FixAllProvider Definitions =========== - **Analyzer:** An instance of a type derived from `DiagnosticAnalyzer` that reports diagnostics. - **Code fixer:** An instance of a type derived from `CodeFixProvider` that provides code fixes for compiler and/or analyzer diagnostics. - **Code refactoring:** An instance of a type derived from `CodeRefactoringProvider` that provides source code refactorings. - **Code action:** An action registered by `CodeFixProvider.RegisterCodeFixesAsync` that performs a code fix OR an action registered by `CodeRefactoringProvider.ComputeRefactoringsAsync` that performs a code refactoring. - **Equivalence Key:** A string value representing an equivalence class of all code actions registered by a code fixer or refactoring. Two code actions are treated as equivalent if they have equal `EquivalenceKey` values and were generated by the same code fixer or refactoring. - **FixAll provider:** An instance of a type derived from `FixAllProvider` that provides a FixAll occurrences code fix. A FixAll provider is associated with a corresponding code fixer by `CodeFixProvider.GetFixAllProvider` method. - **FixAll occurrences code fix:** A code action returned by `FixAllProvider.GetFixAsync`, that fixes all or multiple occurrences of diagnostics fixed by the corresponding code fixer, within a given `FixAllScope`. What is a FixAll occurrences code fix? ====================================== In layman terms, a FixAll occurrences code fix means: I have a code fix 'C', that fixes a specific instance of diagnostic 'D' in my source and I want to apply this fix to all instances of 'D' across a broader scope, such as a document or a project or the entire solution. In more technical terms: Given a particular code action registered by a code fixer to fix one or more diagnostics, a corresponding code action registered by its FixAll provider, that applies the original trigger code action across a broader scope (such as a document/project/solution) to fix multiple instances of such diagnostics. How is a FixAll occurrences code fix computed? ============================================== Following steps are used to compute a FixAll occurrences code fix: - Given a specific instance of a diagnostic, compute the set of code actions that claim to fix the diagnostic. - Select a specific code action from this set. In the Visual Studio IDE, this is done by selecting a specific code action in the light bulb menu. - The equivalence key of the selected code action represents the class of code actions that must be applied as part of a FixAll occurrences code fix. - Given this code action, get the FixAll provider corresponding to the code fixer that registered this code action. - If non-null, then request the FixAll provider for its supported FixAllScopes. - Select a specific `FixAllScope` from this set. In the Visual Studio IDE, this is done by clicking on the scope hyperlink in the preview dialog. - Given the trigger diagnostic(s), the equivalence key of the trigger code action, and the FixAll scope, invoke `FixAllProvider.GetFixAsync` to compute the FixAll occurrences code fix. Adding FixAll support to your code fixer ======================================== Follow the below steps to add FixAll support to your code fixer: - Override the `CodeFixProvider.GetFixAllProvider` method and return a non-null instance of a `FixAllProvider`. You may either use our built-in FixAllProvider or implement a custom FixAllProvider. See the following sections in this document for determining the correct approach for your fixer. - Ensure that all the code actions registered by your code fixer have a non-null equivalence key. See the following section to determine how to select an equivalence key. Selecting an Equivalence key for code actions ============================================= Each unique equivalence key for a code fixer defines a unique equivalence class of code actions. Equivalence key of the trigger code action is part of the `FixAllContext` and is used to determine the FixAll occurrences code fix. Normally, you can use the **'title'** of the code action as the equivalence key. However, there are cases where you may desire to have different values. Let us take an example to get a better understanding. Let us consider the [C# SimplifyTypeNamesCodeFixProvider](https://github.com/dotnet/roslyn/blob/main/src/Features/CSharp/Portable/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs) that registers multiple code actions and also has FixAll support. This code fixer offers fixes to simplify the following expressions: - `this` expressions of the form 'this.x' to 'x'. - Qualified type names of the form 'A.B' to 'B'. - Member access expressions of the form 'A.M' to 'M'. This fixer needs the following semantics for the corresponding FixAll occurrences code fixes: - `this` expression simplification: Fix all should simplify all this expressions, regardless of the member being accessed (this.x, this.y, this.z, etc.). - Qualified type name simplification: Fix all should simplify all qualified type names 'A.B' to 'B'. However, we don't want to simplify **all** qualified type names, such as 'C.D', 'E.F', etc. as that would be too generic a fix, which is not likely intended by the user. - Member access expressions: Fix all should simplify all member access expressions 'A.M' to 'M'. It uses the below equivalence keys for its registered code actions to get the desired FixAll behavior: - `this` expression simplification: Generic resource string "Simplify this expression", which explicitly excludes the contents of the node being simplified. - Qualified type name simplification: Formatted resource string "Simplify type name A.B", which explicitly includes the contents of the node being simplified. - Member access expressions: Formatted resource string "Simplify type name A.M", which explicitly includes the contents of the node being simplified. Note that '`this` expression simplification' fix requires a different kind of an equivalence class from the other two simplifications. See method [GetCodeActionId](https://github.com/dotnet/roslyn/blob/main/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs) for the actual implementation. To summarize, use the equivalence key that best suits the category of fixes to be applied as part of a FixAll operation. Spectrum of FixAll providers ============================ When multiple fixes need to be applied to documents, there are various ways to do it: - **Sequential approach**: One way to do it is to compute diagnostics, pick one, ask a fixer to produce a code action to fix that, apply it. Now for the resulting new compilation, recompute diagnostics, pick the next one and repeat the process. This approach would be very slow but would lead to correct results (unless it doesn't converge where one fix introduces a diagnostic that was just fixed by a previous fix). We chose to not implement this approach. - **Batch fix approach**: Another way is to compute all the diagnostics, pick each diagnostic and give it to a fixer and apply it to produce a new solution. If there were 'n' diagnostics, there would be 'n' new solutions. Now just merge them all together in one go. This may produce incorrect results (when different fixes change the same region of code in different ways) but it is very fast. We have one implementation of this approach in `WellKnownFixAllProviders.BatchFixer` - **Custom approach**: Depending on the fix, there may be a custom solution to fix multiple issues. For example, consider an analyzer that simply needs to generate one file as the fix for any instance of the issue. Instead of generating the same file over and over using the previous two approaches, one could write a custom `FixAllProvider` that simply generates the file once if there were any diagnostics at all. Since there are various ways of fixing all issues, we've implemented a framework and provided the one general implementation that we think is useful in many cases. Built-in FixAllProvider ======================= We provide a default `BatchFixAllProvider` implementation of a FixAll provider that uses the underlying code fixer to compute the FixAll occurrences code fixes. To use the batch fixer, you should return the static `WellKnownFixAllProviders.BatchFixer` instance in the `CodeFixProvider.GetFixAllProvider` override. NOTE: See the following section on **'Limitations of the BatchFixer'** to determine if the batch fixer can be used by your code fixer. Given a trigger diagnostic, a trigger code action, the underlying code fixer and the FixAll scope, the BatchFixer computes FixAll occurrences code fix with the following steps: - Compute all instances of the trigger diagnostic across the FixAll scope. - For each computed diagnostic, invoke the underlying code fixer to compute the set of code actions to fix the diagnostic. - Collect all the registered code actions that have the same equivalence key as the trigger code action. - Apply all these code actions on the original solution snapshot to compute new solution snapshots. The batch fixer only batches code action operations of type `ApplyChangesOperation` present within the individual code actions, other types of operations are ignored. - Sequentially merge the new solution snapshots into a final solution snapshot. Only non-conflicting code actions whose fix spans don't overlap the fix spans of prior merged code actions are retained. Limitations of the BatchFixer ============================= The BatchFixer is designed for a common category of fixers where fix spans for diagnostics don't overlap with each other. For example, assume there is a diagnostic that spans a particular expression, and a fixer that fixes that expression. If all the instances of this diagnostic are guaranteed to have non-overlapping spans, then their fixes can be computed independently and this batch of fixes can be subsequently merged together. However, there are cases where the BatchFixer might not work for your fixer. Following are some such examples: - Code fixer registers code actions without an equivalence key or with a null equivalence key. - Code fixer registers non-local code actions, i.e. a code action whose fix span is completely distinct from diagnostic span. For example, a fix that adds a new declaration node. Multiple such fixes are likely to have overlapping spans and hence could be conflicting. - Diagnostics to be fixed as part of FixAll occurrences have overlapping spans. It is likely that fixes for such diagnostics will have overlapping spans too, and hence would conflict with each other. - Code fixer registers code actions with operations other than `ApplyChangesOperation`. BatchFixer ignores such operations and hence may produce unexpected results. Implementing a custom FixAllProvider ==================================== For cases where you cannot use the BatchFixer, you must implement your own `FixAllProvider`. It is recommended that you create a singleton instance of the FixAll provider, instead of creating a new instance for every `CodeFixProvider.GetFixAllProvider` invocation. Following guidelines should help in the implementation: - **GetFixAsync:** Primary method to compute the FixAll occurrences code fix for a given `FixAllContext`. You may use the set of 'GetXXXDiagnosticsAsync' methods on the `FixAllContext` to compute the diagnostics to be fixed. You must return a single code action that fixes all the diagnostics in the given FixAll scope. - **GetSupportedFixAllScopes:** Virtual method to get all the supported FixAll scopes. By default, it returns all the three supported scopes: document, project and solution scopes. Generally, you need not override this method. However, you may do so if you wish to support a subset of these scopes. - **GetSupportedFixAllDiagnosticIds:** Virtual method to get all the fixable diagnostic ids. By default, it returns the underlying code fixer's `FixableDiagnosticIds`. Generally, you need not override this method. However, you may do so if you wish to support FixAll only for a subset of these ids. See [DeclarePublicAPIFix](https://github.com/dotnet/roslyn-analyzers/blob/main/src/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs) for an example implementation of a custom FixAllProvider.
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/EditorFeatures/VisualBasicTest/SplitComment/SplitCommentCommandHandlerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SplitComment Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitComment <UseExportProvider> Public Class SplitCommentCommandHandlerTests Inherits AbstractSplitCommentCommandHandlerTests Protected Overrides Function CreateWorkspace(markup As String) As TestWorkspace Return TestWorkspace.CreateVisualBasic(markup) End Function <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfComment() TestHandled( "Module Program Sub Main(args As String()) '[||]Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) ' 'Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfDoubleComment1() TestHandled( "Module Program Sub Main(args As String()) ''[||]Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) '' ''Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfDoubleComment2() TestHandled( "Module Program Sub Main(args As String()) '' [||]Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) '' '' Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfDoubleComment3() TestHandled( "Module Program Sub Main(args As String()) ''[||] Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) '' ''Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfCommentWithLeadingSpace1() TestHandled( "Module Program Sub Main(args As String()) ' [||]Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) ' ' Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfCommentWithLeadingSpace2() TestHandled( "Module Program Sub Main(args As String()) '[||] Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) ' 'Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitMiddleOfComment() TestHandled( "Module Program Sub Main(args As String()) ' Test [||]Comment End Sub End Module ", "Module Program Sub Main(args As String()) ' Test ' Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitEndOfComment() TestNotHandled( "Module Program Sub Main(args As String()) ' Test Comment[||] End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestNotAtEndOfFile() TestNotHandled( "Module Program Sub Main(args As String()) ' Test Comment[||]") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentOutOfMethod() TestHandled( "Module Program Sub Main(args As String()) End Sub ' Test [||]Comment End Module ", "Module Program Sub Main(args As String()) End Sub ' Test ' Comment End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentOutOfModule() TestHandled( "Module Program Sub Main(args As String()) End Sub End Module ' Test [||]Comment ", "Module Program Sub Main(args As String()) End Sub End Module ' Test ' Comment ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentOutOfClass() TestHandled( "Class Program Public Shared Sub Main(args As String()) End Sub End Class ' Test [||]Comment ", "Class Program Public Shared Sub Main(args As String()) End Sub End Class ' Test ' Comment ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentOutOfNamespace() TestHandled( "Namespace TestNamespace Module Program Sub Main(args As String()) End Sub End Module End Namespace ' Test [||]Comment ", "Namespace TestNamespace Module Program Sub Main(args As String()) End Sub End Module End Namespace ' Test ' Comment ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentWithLineContinuation() TestNotHandled( "Module Program Sub Main(args As String()) Dim X As Integer _ ' Comment [||]is here = 4 End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)> <InlineData("X[||]Test Comment")> <InlineData("X [||]Test Comment")> <InlineData("X[||] Test Comment")> <InlineData("X [||] Test Comment")> Public Sub TestCommentWithMultipleLeadingSpaces(commentValue As String) TestHandled( $"public class Program public sub Goo() ' {commentValue} end sub end class", "public class Program public sub Goo() ' X ' Test Comment end sub end class") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)> <InlineData("X[||]Test Comment")> <InlineData("X [||]Test Comment")> <InlineData("X[||] Test Comment")> <InlineData("X [||] Test Comment")> Public Sub TestQuadCommentWithMultipleLeadingSpaces(commentValue As String) TestHandled( $"public class Program public sub Goo() '''' {commentValue} end sub end class", "public class Program public sub Goo() '''' X '''' Test Comment end sub end class") End Sub <WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitWithCommentAfterwards1() TestNotHandled( "public class Program public sub Goo() ' goo[||] 'Test Comment end sub end class") End Sub <WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitWithCommentAfterwards2() TestNotHandled( "public class Program { public sub Goo() { ' goo [||] 'Test Comment end sub end class") End Sub <WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitWithCommentAfterwards3() TestNotHandled( "public class Program { public sub Goo() ' goo [||]'Test Comment end sub end class") End Sub <WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitWithCommentAfterwards4() TestNotHandled( "public class Program public sub Goo() // [|goo|] 'Test Comment end sub end class") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SplitComment Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitComment <UseExportProvider> Public Class SplitCommentCommandHandlerTests Inherits AbstractSplitCommentCommandHandlerTests Protected Overrides Function CreateWorkspace(markup As String) As TestWorkspace Return TestWorkspace.CreateVisualBasic(markup) End Function <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfComment() TestHandled( "Module Program Sub Main(args As String()) '[||]Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) ' 'Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfDoubleComment1() TestHandled( "Module Program Sub Main(args As String()) ''[||]Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) '' ''Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfDoubleComment2() TestHandled( "Module Program Sub Main(args As String()) '' [||]Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) '' '' Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfDoubleComment3() TestHandled( "Module Program Sub Main(args As String()) ''[||] Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) '' ''Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfCommentWithLeadingSpace1() TestHandled( "Module Program Sub Main(args As String()) ' [||]Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) ' ' Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitStartOfCommentWithLeadingSpace2() TestHandled( "Module Program Sub Main(args As String()) '[||] Test Comment End Sub End Module ", "Module Program Sub Main(args As String()) ' 'Test Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitMiddleOfComment() TestHandled( "Module Program Sub Main(args As String()) ' Test [||]Comment End Sub End Module ", "Module Program Sub Main(args As String()) ' Test ' Comment End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitEndOfComment() TestNotHandled( "Module Program Sub Main(args As String()) ' Test Comment[||] End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestNotAtEndOfFile() TestNotHandled( "Module Program Sub Main(args As String()) ' Test Comment[||]") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentOutOfMethod() TestHandled( "Module Program Sub Main(args As String()) End Sub ' Test [||]Comment End Module ", "Module Program Sub Main(args As String()) End Sub ' Test ' Comment End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentOutOfModule() TestHandled( "Module Program Sub Main(args As String()) End Sub End Module ' Test [||]Comment ", "Module Program Sub Main(args As String()) End Sub End Module ' Test ' Comment ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentOutOfClass() TestHandled( "Class Program Public Shared Sub Main(args As String()) End Sub End Class ' Test [||]Comment ", "Class Program Public Shared Sub Main(args As String()) End Sub End Class ' Test ' Comment ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentOutOfNamespace() TestHandled( "Namespace TestNamespace Module Program Sub Main(args As String()) End Sub End Module End Namespace ' Test [||]Comment ", "Namespace TestNamespace Module Program Sub Main(args As String()) End Sub End Module End Namespace ' Test ' Comment ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitCommentWithLineContinuation() TestNotHandled( "Module Program Sub Main(args As String()) Dim X As Integer _ ' Comment [||]is here = 4 End Sub End Module ") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)> <InlineData("X[||]Test Comment")> <InlineData("X [||]Test Comment")> <InlineData("X[||] Test Comment")> <InlineData("X [||] Test Comment")> Public Sub TestCommentWithMultipleLeadingSpaces(commentValue As String) TestHandled( $"public class Program public sub Goo() ' {commentValue} end sub end class", "public class Program public sub Goo() ' X ' Test Comment end sub end class") End Sub <WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")> <WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)> <InlineData("X[||]Test Comment")> <InlineData("X [||]Test Comment")> <InlineData("X[||] Test Comment")> <InlineData("X [||] Test Comment")> Public Sub TestQuadCommentWithMultipleLeadingSpaces(commentValue As String) TestHandled( $"public class Program public sub Goo() '''' {commentValue} end sub end class", "public class Program public sub Goo() '''' X '''' Test Comment end sub end class") End Sub <WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitWithCommentAfterwards1() TestNotHandled( "public class Program public sub Goo() ' goo[||] 'Test Comment end sub end class") End Sub <WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitWithCommentAfterwards2() TestNotHandled( "public class Program { public sub Goo() { ' goo [||] 'Test Comment end sub end class") End Sub <WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitWithCommentAfterwards3() TestNotHandled( "public class Program { public sub Goo() ' goo [||]'Test Comment end sub end class") End Sub <WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")> <WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)> Public Sub TestSplitWithCommentAfterwards4() TestNotHandled( "public class Program public sub Goo() // [|goo|] 'Test Comment end sub end class") End Sub End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Workspaces/Core/Portable/LinkedFileDiffMerging/IMergeConflictHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal interface IMergeConflictHandler { IEnumerable<TextChange> CreateEdits(SourceText originalSourceText, IEnumerable<UnmergedDocumentChanges> unmergedChanges); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal interface IMergeConflictHandler { IEnumerable<TextChange> CreateEdits(SourceText originalSourceText, IEnumerable<UnmergedDocumentChanges> unmergedChanges); } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Workspaces/Core/Portable/Shared/Utilities/IStreamingProgressTrackerExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class IStreamingProgressTrackerExtensions { /// <summary> /// Returns an <see cref="IAsyncDisposable"/> that will call <see /// cref="IStreamingProgressTracker.ItemCompletedAsync"/> on <paramref /// name="progressTracker"/> when it is disposed. /// </summary> public static async Task<IAsyncDisposable> AddSingleItemAsync(this IStreamingProgressTracker progressTracker, CancellationToken cancellationToken) { await progressTracker.AddItemsAsync(1, cancellationToken).ConfigureAwait(false); return new StreamingProgressDisposer(progressTracker, cancellationToken); } private class StreamingProgressDisposer : IAsyncDisposable { private readonly IStreamingProgressTracker _progressTracker; private readonly CancellationToken _cancellationToken; public StreamingProgressDisposer(IStreamingProgressTracker progressTracker, CancellationToken cancellationToken) { _progressTracker = progressTracker; _cancellationToken = cancellationToken; } public async ValueTask DisposeAsync() => await _progressTracker.ItemCompletedAsync(_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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class IStreamingProgressTrackerExtensions { /// <summary> /// Returns an <see cref="IAsyncDisposable"/> that will call <see /// cref="IStreamingProgressTracker.ItemCompletedAsync"/> on <paramref /// name="progressTracker"/> when it is disposed. /// </summary> public static async Task<IAsyncDisposable> AddSingleItemAsync(this IStreamingProgressTracker progressTracker, CancellationToken cancellationToken) { await progressTracker.AddItemsAsync(1, cancellationToken).ConfigureAwait(false); return new StreamingProgressDisposer(progressTracker, cancellationToken); } private class StreamingProgressDisposer : IAsyncDisposable { private readonly IStreamingProgressTracker _progressTracker; private readonly CancellationToken _cancellationToken; public StreamingProgressDisposer(IStreamingProgressTracker progressTracker, CancellationToken cancellationToken) { _progressTracker = progressTracker; _cancellationToken = cancellationToken; } public async ValueTask DisposeAsync() => await _progressTracker.ItemCompletedAsync(_cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./docs/features/local-functions.work.md
Local Function Status ===================== This is a checklist for current and outstanding work on the local functions feature, as spec'd in [local-functions.md](./local-functions.md). -------------------- Known issues ============ Compiler: - [ ] Parser builds nodes for local functions when feature not enabled (#9940) - [ ] Compiler crash: base call to state machine method, in state machine method (#9872) - [ ] Need custom warning for unused local function (#9661) - [ ] Generate quick action does not offer to generate local (#9352) - [ ] Parser ambiguity research (#10388) - [ ] Dynamic support (#10389) - [ ] Referring to local function in expression tree (#10390) - [ ] Resolve definite assignment rules (#10391) - [ ] Remove support for `var` return type (#10392) - [ ] Update error messages (#10393) IDE: - [ ] Some selections around local functions fail extract method refactoring [ ] (#8719) - [ ] Extracting local function passed to an Action introduces compiler error [ ] (#8718) - [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717) - [ ] Inline temp introductes compiler error (#8716) - [ ] Call hierarchy search never terminates on local functions (#8654) - [ ] Nav bar doesn't support local functions (#8648) - [ ] No outlining for local functions (#8647) - [ ] Squiggles all over the place when using an unsupported modifier (#8645) - [ ] Peek definition errors out on local function (#8644) - [ ] Void keyword not recommended while declaring local function (#8616) - [ ] Change signature doesn't update the signature of the local function (#8539) Feature Completeness Progress ============================= - [x] N-level nested local functions - [x] Capture - Works alongside lambdas and behaves very similarly in fallback cases - Has zero-allocation closures (struct frames by ref) on functions never converted to a delegate and are not an iterator/async - [x] Standard parameter features - params - ref/out - named/optional - [x] Visibility - May revisit design (currently shadows, may do overloads) - [x] Generics - Nongeneric local functions in generic methods (same as lambdas). - Generic local functions in nongeneric methods. - Generic local functions in generic methods. - Arbitrary nesting of generic local functions. - Generic local functions with constraints. - [x] Inferred return type - [x] Iterators - [x] Async
Local Function Status ===================== This is a checklist for current and outstanding work on the local functions feature, as spec'd in [local-functions.md](./local-functions.md). -------------------- Known issues ============ Compiler: - [ ] Parser builds nodes for local functions when feature not enabled (#9940) - [ ] Compiler crash: base call to state machine method, in state machine method (#9872) - [ ] Need custom warning for unused local function (#9661) - [ ] Generate quick action does not offer to generate local (#9352) - [ ] Parser ambiguity research (#10388) - [ ] Dynamic support (#10389) - [ ] Referring to local function in expression tree (#10390) - [ ] Resolve definite assignment rules (#10391) - [ ] Remove support for `var` return type (#10392) - [ ] Update error messages (#10393) IDE: - [ ] Some selections around local functions fail extract method refactoring [ ] (#8719) - [ ] Extracting local function passed to an Action introduces compiler error [ ] (#8718) - [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717) - [ ] Inline temp introductes compiler error (#8716) - [ ] Call hierarchy search never terminates on local functions (#8654) - [ ] Nav bar doesn't support local functions (#8648) - [ ] No outlining for local functions (#8647) - [ ] Squiggles all over the place when using an unsupported modifier (#8645) - [ ] Peek definition errors out on local function (#8644) - [ ] Void keyword not recommended while declaring local function (#8616) - [ ] Change signature doesn't update the signature of the local function (#8539) Feature Completeness Progress ============================= - [x] N-level nested local functions - [x] Capture - Works alongside lambdas and behaves very similarly in fallback cases - Has zero-allocation closures (struct frames by ref) on functions never converted to a delegate and are not an iterator/async - [x] Standard parameter features - params - ref/out - named/optional - [x] Visibility - May revisit design (currently shadows, may do overloads) - [x] Generics - Nongeneric local functions in generic methods (same as lambdas). - Generic local functions in nongeneric methods. - Generic local functions in generic methods. - Arbitrary nesting of generic local functions. - Generic local functions with constraints. - [x] Inferred return type - [x] Iterators - [x] Async
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Features/Core/Portable/SolutionCrawler/IDocumentDifferenceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class DocumentDifferenceResult { public InvocationReasons ChangeType { get; } public SyntaxNode? ChangedMember { get; } public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null) { ChangeType = changeType; ChangedMember = changedMember; } } internal interface IDocumentDifferenceService : ILanguageService { Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class DocumentDifferenceResult { public InvocationReasons ChangeType { get; } public SyntaxNode? ChangedMember { get; } public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null) { ChangeType = changeType; ChangedMember = changedMember; } } internal interface IDocumentDifferenceService : ILanguageService { Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/VisualStudio/IntegrationTest/TestUtilities/Common/Comparison.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common { internal static class Comparison { public static bool AreStringValuesEqual(string? str1, string? str2) => (str1 ?? "") == (str2 ?? ""); public static bool AreArraysEqual<T>(T[]? array1, T[]? array2) where T : IEquatable<T> { if (array1 is null || array2 is null) { // both must be null return array1 == array2; } if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (!EqualityComparer<T>.Default.Equals(array1[i], array2[i])) { return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common { internal static class Comparison { public static bool AreStringValuesEqual(string? str1, string? str2) => (str1 ?? "") == (str2 ?? ""); public static bool AreArraysEqual<T>(T[]? array1, T[]? array2) where T : IEquatable<T> { if (array1 is null || array2 is null) { // both must be null return array1 == array2; } if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (!EqualityComparer<T>.Default.Equals(array1[i], array2[i])) { return false; } } return true; } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/EditorFeatures/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/VisualStudio/Core/Def/Implementation/Snippets/IVsContainedLanguageHostInternal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { /// <summary> /// Redefine IVsContainedLanguageHost so we can call InsertImportsDirective which would /// otherwise expect the namespace string as a ushort. /// </summary> [Guid("0429916F-69E1-4336-AB7E-72086FB0D6BC")] [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsContainedLanguageHostInternal { // These Reserved* methods are here to use up space in the vtable void Reserved1(); void Reserved2(); void Reserved3(); void Reserved4(); void Reserved5(); void Reserved6(); void Reserved7(); void Reserved8(); void Reserved9(); void Reserved10(); void Reserved11(); void Reserved12(); [PreserveSig] int InsertImportsDirective([MarshalAs(UnmanagedType.LPWStr)] string pwcImportP); void Reserved13(); void Reserved14(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { /// <summary> /// Redefine IVsContainedLanguageHost so we can call InsertImportsDirective which would /// otherwise expect the namespace string as a ushort. /// </summary> [Guid("0429916F-69E1-4336-AB7E-72086FB0D6BC")] [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsContainedLanguageHostInternal { // These Reserved* methods are here to use up space in the vtable void Reserved1(); void Reserved2(); void Reserved3(); void Reserved4(); void Reserved5(); void Reserved6(); void Reserved7(); void Reserved8(); void Reserved9(); void Reserved10(); void Reserved11(); void Reserved12(); [PreserveSig] int InsertImportsDirective([MarshalAs(UnmanagedType.LPWStr)] string pwcImportP); void Reserved13(); void Reserved14(); } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicAddImportsService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.AddImports Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.AddImports <ExportLanguageService(GetType(IAddImportsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicAddImportsService Inherits AbstractAddImportsService(Of CompilationUnitSyntax, NamespaceBlockSyntax, ImportsStatementSyntax, ImportsStatementSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Private Shared ReadOnly ImportsStatementComparer As ImportsStatementComparer = New ImportsStatementComparer(New CaseInsensitiveTokenComparer()) Protected Overrides Function IsEquivalentImport(a As SyntaxNode, b As SyntaxNode) As Boolean Dim importsA = TryCast(a, ImportsStatementSyntax) Dim importsB = TryCast(b, ImportsStatementSyntax) If importsA Is Nothing OrElse importsB Is Nothing Then Return False End If Return ImportsStatementComparer.Compare(importsA, importsB) = 0 End Function Protected Overrides Function GetGlobalImports(compilation As Compilation, generator As SyntaxGenerator) As ImmutableArray(Of SyntaxNode) Dim result = ArrayBuilder(Of SyntaxNode).GetInstance() For Each import In compilation.MemberImports() If TypeOf import Is INamespaceSymbol Then result.Add(generator.NamespaceImportDeclaration(import.ToDisplayString())) End If Next Return result.ToImmutableAndFree() End Function Protected Overrides Function GetAlias(usingOrAlias As ImportsStatementSyntax) As SyntaxNode Return usingOrAlias.ImportsClauses.OfType(Of SimpleImportsClauseSyntax). Where(Function(c) c.Alias IsNot Nothing). FirstOrDefault()?.Alias End Function Protected Overrides Function IsStaticUsing(usingOrAlias As ImportsStatementSyntax) As Boolean ' Visual Basic doesn't support static imports Return False End Function Protected Overrides Function GetExterns(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax) Return Nothing End Function Protected Overrides Function GetUsingsAndAliases(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax) If node.Kind() = SyntaxKind.CompilationUnit Then Return DirectCast(node, CompilationUnitSyntax).Imports End If Return Nothing End Function Protected Overrides Function Rewrite( externAliases() As ImportsStatementSyntax, usingDirectives() As ImportsStatementSyntax, staticUsingDirectives() As ImportsStatementSyntax, aliasDirectives() As ImportsStatementSyntax, externContainer As SyntaxNode, usingContainer As SyntaxNode, staticUsingContainer As SyntaxNode, aliasContainer As SyntaxNode, placeSystemNamespaceFirst As Boolean, allowInHiddenRegions As Boolean, root As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode Dim compilationUnit = DirectCast(root, CompilationUnitSyntax) If Not compilationUnit.CanAddImportsStatements(allowInHiddenRegions, cancellationToken) Then Return compilationUnit End If Return compilationUnit.AddImportsStatements( usingDirectives.Concat(aliasDirectives).ToList(), placeSystemNamespaceFirst, Array.Empty(Of SyntaxAnnotation)) End Function Private Class CaseInsensitiveTokenComparer Implements IComparer(Of SyntaxToken) Public Function Compare(x As SyntaxToken, y As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare ' By using 'ValueText' we get the value that is normalized. i.e. ' [class] will be 'class', and unicode escapes will be converted ' to actual unicode. This allows sorting to work properly across ' tokens that have different source representations, but which ' mean the same thing. ' Don't bother checking the raw kind, since this will only ever be used with Identifier tokens. Return CaseInsensitiveComparer.Default.Compare(x.GetIdentifierText(), y.GetIdentifierText()) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.AddImports Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.AddImports <ExportLanguageService(GetType(IAddImportsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicAddImportsService Inherits AbstractAddImportsService(Of CompilationUnitSyntax, NamespaceBlockSyntax, ImportsStatementSyntax, ImportsStatementSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Private Shared ReadOnly ImportsStatementComparer As ImportsStatementComparer = New ImportsStatementComparer(New CaseInsensitiveTokenComparer()) Protected Overrides Function IsEquivalentImport(a As SyntaxNode, b As SyntaxNode) As Boolean Dim importsA = TryCast(a, ImportsStatementSyntax) Dim importsB = TryCast(b, ImportsStatementSyntax) If importsA Is Nothing OrElse importsB Is Nothing Then Return False End If Return ImportsStatementComparer.Compare(importsA, importsB) = 0 End Function Protected Overrides Function GetGlobalImports(compilation As Compilation, generator As SyntaxGenerator) As ImmutableArray(Of SyntaxNode) Dim result = ArrayBuilder(Of SyntaxNode).GetInstance() For Each import In compilation.MemberImports() If TypeOf import Is INamespaceSymbol Then result.Add(generator.NamespaceImportDeclaration(import.ToDisplayString())) End If Next Return result.ToImmutableAndFree() End Function Protected Overrides Function GetAlias(usingOrAlias As ImportsStatementSyntax) As SyntaxNode Return usingOrAlias.ImportsClauses.OfType(Of SimpleImportsClauseSyntax). Where(Function(c) c.Alias IsNot Nothing). FirstOrDefault()?.Alias End Function Protected Overrides Function IsStaticUsing(usingOrAlias As ImportsStatementSyntax) As Boolean ' Visual Basic doesn't support static imports Return False End Function Protected Overrides Function GetExterns(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax) Return Nothing End Function Protected Overrides Function GetUsingsAndAliases(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax) If node.Kind() = SyntaxKind.CompilationUnit Then Return DirectCast(node, CompilationUnitSyntax).Imports End If Return Nothing End Function Protected Overrides Function Rewrite( externAliases() As ImportsStatementSyntax, usingDirectives() As ImportsStatementSyntax, staticUsingDirectives() As ImportsStatementSyntax, aliasDirectives() As ImportsStatementSyntax, externContainer As SyntaxNode, usingContainer As SyntaxNode, staticUsingContainer As SyntaxNode, aliasContainer As SyntaxNode, placeSystemNamespaceFirst As Boolean, allowInHiddenRegions As Boolean, root As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode Dim compilationUnit = DirectCast(root, CompilationUnitSyntax) If Not compilationUnit.CanAddImportsStatements(allowInHiddenRegions, cancellationToken) Then Return compilationUnit End If Return compilationUnit.AddImportsStatements( usingDirectives.Concat(aliasDirectives).ToList(), placeSystemNamespaceFirst, Array.Empty(Of SyntaxAnnotation)) End Function Private Class CaseInsensitiveTokenComparer Implements IComparer(Of SyntaxToken) Public Function Compare(x As SyntaxToken, y As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare ' By using 'ValueText' we get the value that is normalized. i.e. ' [class] will be 'class', and unicode escapes will be converted ' to actual unicode. This allows sorting to work properly across ' tokens that have different source representations, but which ' mean the same thing. ' Don't bother checking the raw kind, since this will only ever be used with Identifier tokens. Return CaseInsensitiveComparer.Default.Compare(x.GetIdentifierText(), y.GetIdentifierText()) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Implement this abstract type to provide fix all/multiple occurrences code fixes for source code problems. /// Alternatively, you can use any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/>. /// </summary> public abstract class FixAllProvider { /// <summary> /// Gets the supported scopes for fixing all occurrences of a diagnostic. /// By default, it returns the following scopes: /// (a) <see cref="FixAllScope.Document"/> /// (b) <see cref="FixAllScope.Project"/> and /// (c) <see cref="FixAllScope.Solution"/> /// </summary> public virtual IEnumerable<FixAllScope> GetSupportedFixAllScopes() => ImmutableArray.Create(FixAllScope.Document, FixAllScope.Project, FixAllScope.Solution); /// <summary> /// Gets the diagnostic IDs for which fix all occurrences is supported. /// By default, it returns <see cref="CodeFixProvider.FixableDiagnosticIds"/> for the given <paramref name="originalCodeFixProvider"/>. /// </summary> /// <param name="originalCodeFixProvider">Original code fix provider that returned this fix all provider from <see cref="CodeFixProvider.GetFixAllProvider"/> method.</param> public virtual IEnumerable<string> GetSupportedFixAllDiagnosticIds(CodeFixProvider originalCodeFixProvider) => originalCodeFixProvider.FixableDiagnosticIds; /// <summary> /// Gets fix all occurrences fix for the given fixAllContext. /// </summary> public abstract Task<CodeAction?> GetFixAsync(FixAllContext fixAllContext); /// <summary> /// Create a <see cref="FixAllProvider"/> that fixes documents independently. This should be used instead of /// <see cref="WellKnownFixAllProviders.BatchFixer"/> in the case where fixes for a <see cref="Diagnostic"/> /// only affect the <see cref="Document"/> the diagnostic was produced in. /// </summary> /// <param name="fixAllAsync"> /// Callback that will the fix diagnostics present in the provided document. The document returned will only be /// examined for its content (e.g. it's <see cref="SyntaxTree"/> or <see cref="SourceText"/>. No other aspects /// of it (like attributes), or changes to the <see cref="Project"/> or <see cref="Solution"/> it points at /// will be considered. /// </param> public static FixAllProvider Create(Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> fixAllAsync) { if (fixAllAsync == null) throw new ArgumentNullException(nameof(fixAllAsync)); return new CallbackDocumentBasedFixAllProvider(fixAllAsync); } private class CallbackDocumentBasedFixAllProvider : DocumentBasedFixAllProvider { private readonly Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> _fixAllAsync; public CallbackDocumentBasedFixAllProvider(Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> fixAllAsync) { _fixAllAsync = fixAllAsync; } protected override Task<Document?> FixAllAsync(FixAllContext context, Document document, ImmutableArray<Diagnostic> diagnostics) => _fixAllAsync(context, document, 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Implement this abstract type to provide fix all/multiple occurrences code fixes for source code problems. /// Alternatively, you can use any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/>. /// </summary> public abstract class FixAllProvider { /// <summary> /// Gets the supported scopes for fixing all occurrences of a diagnostic. /// By default, it returns the following scopes: /// (a) <see cref="FixAllScope.Document"/> /// (b) <see cref="FixAllScope.Project"/> and /// (c) <see cref="FixAllScope.Solution"/> /// </summary> public virtual IEnumerable<FixAllScope> GetSupportedFixAllScopes() => ImmutableArray.Create(FixAllScope.Document, FixAllScope.Project, FixAllScope.Solution); /// <summary> /// Gets the diagnostic IDs for which fix all occurrences is supported. /// By default, it returns <see cref="CodeFixProvider.FixableDiagnosticIds"/> for the given <paramref name="originalCodeFixProvider"/>. /// </summary> /// <param name="originalCodeFixProvider">Original code fix provider that returned this fix all provider from <see cref="CodeFixProvider.GetFixAllProvider"/> method.</param> public virtual IEnumerable<string> GetSupportedFixAllDiagnosticIds(CodeFixProvider originalCodeFixProvider) => originalCodeFixProvider.FixableDiagnosticIds; /// <summary> /// Gets fix all occurrences fix for the given fixAllContext. /// </summary> public abstract Task<CodeAction?> GetFixAsync(FixAllContext fixAllContext); /// <summary> /// Create a <see cref="FixAllProvider"/> that fixes documents independently. This should be used instead of /// <see cref="WellKnownFixAllProviders.BatchFixer"/> in the case where fixes for a <see cref="Diagnostic"/> /// only affect the <see cref="Document"/> the diagnostic was produced in. /// </summary> /// <param name="fixAllAsync"> /// Callback that will the fix diagnostics present in the provided document. The document returned will only be /// examined for its content (e.g. it's <see cref="SyntaxTree"/> or <see cref="SourceText"/>. No other aspects /// of it (like attributes), or changes to the <see cref="Project"/> or <see cref="Solution"/> it points at /// will be considered. /// </param> public static FixAllProvider Create(Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> fixAllAsync) { if (fixAllAsync == null) throw new ArgumentNullException(nameof(fixAllAsync)); return new CallbackDocumentBasedFixAllProvider(fixAllAsync); } private class CallbackDocumentBasedFixAllProvider : DocumentBasedFixAllProvider { private readonly Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> _fixAllAsync; public CallbackDocumentBasedFixAllProvider(Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> fixAllAsync) { _fixAllAsync = fixAllAsync; } protected override Task<Document?> FixAllAsync(FixAllContext context, Document document, ImmutableArray<Diagnostic> diagnostics) => _fixAllAsync(context, document, diagnostics); } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Compilers/CSharp/Test/Symbol/Compilation/GetUnusedImportDirectivesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class GetUnusedImportDirectivesTests : SemanticModelTestBase { [Fact] public void UnusedUsing1() { var text = @" using System; class C { void Goo() { } }"; var tree = Parse(text); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); } [WorkItem(865627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865627")] [Fact] public void TestUnusedExtensionMarksImportsAsUsed() { string class1Source = @"using System; namespace ClassLibrary1 { public class Class1 { public void Method1(string arg1) { Console.WriteLine(arg1); } } } "; var classLib1 = CreateCompilation(source: class1Source, assemblyName: "ClassLibrary1"); string class2Source = @"using System; using ClassLibrary1; namespace ClassLibrary2 { public static class Class2 { public static void Method1(this Class1 arg0, string arg1) { Console.Write(""Erroneous: "" + arg1); } } }"; var classLib2 = CreateCompilation(source: class2Source, assemblyName: "ClassLibrary2", references: new[] { classLib1.ToMetadataReference() }); string consoleApplicationSource = @"using ClassLibrary2; using ClassLibrary1; namespace ConsoleApplication { class Program { static void Main(string[] args) { var instance1 = new Class1(); instance1.Method1(""Argument1""); } } }"; var tree = Parse(consoleApplicationSource); var comp = CreateCompilation(tree, new[] { classLib1.ToMetadataReference(), classLib2.ToMetadataReference() }, assemblyName: "ConsoleApplication"); var model = comp.GetSemanticModel(tree) as CSharpSemanticModel; var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single().Expression; //This is the crux of the test. //Without this line, with or without the fix, the model never gets pushed to evaluate extension method candidates //and therefore never marked ClassLibrary2 as a used import in consoleApplication. //Without the fix, this call used to result in ClassLibrary2 getting marked as used, after the fix, this call does not //result in changing ClassLibrary2's used status. model.GetMemberGroup(syntax); model.GetDiagnostics().Verify(Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ClassLibrary2;")); } [WorkItem(747219, "DevDiv2/DevDiv")] [Fact] public void UnusedUsing747219() { var text = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { Enumerable.Repeat(1, 1); } }"; var comp = CreateEmptyCompilation(text, new[] { MscorlibRef }); //all unused because system.core was not included and Enumerable didn't bind comp.VerifyDiagnostics( // (4,14): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?) // using System.Linq; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Linq").WithArguments("Linq", "System"), // (11,9): error CS0103: The name 'Enumerable' does not exist in the current context // Enumerable.Repeat(1, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Enumerable").WithArguments("Enumerable"), // (4,1): info CS8019: Unnecessary using directive. // using System.Linq; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (3,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;"), // (5,1): info CS8019: Unnecessary using directive. // using System.Threading.Tasks; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading.Tasks;") ); comp = comp.WithReferences(comp.References.Concat(SystemCoreRef)); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (3,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;"), // (5,1): info CS8019: Unnecessary using directive. // using System.Threading.Tasks; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading.Tasks;") ); } [Fact] public void UsedUsing1() { var text = @" using System; class C { void Goo() { Console.WriteLine(); } }"; var tree = Parse(text); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); } [Fact] public void SpeculativeBindingDoesNotAffectResult() { var text = @" using System; class C { void Goo() { /*here*/ } }"; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var position = text.IndexOf("/*here*/", StringComparison.Ordinal); var info = model.GetSpeculativeSymbolInfo(position, SyntaxFactory.IdentifierName("Console"), SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.NotNull(info.Symbol); Assert.Equal(SymbolKind.NamedType, info.Symbol.Kind); Assert.Equal("Console", info.Symbol.Name); Assert.Equal(SymbolKind.Namespace, info.Symbol.ContainingSymbol.Kind); Assert.Equal("System", info.Symbol.ContainingSymbol.Name); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;") ); } [ClrOnlyFact(ClrOnlyReason.Unknown)] public void AllAssemblyLevelAttributesMustBeBound() { var snkPath = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey).Path; var signing = Parse(@" using System.Reflection; [assembly: AssemblyVersion(""1.2.3.4"")] [assembly: AssemblyKeyFile(@""" + snkPath + @""")] "); var ivtCompilation = CreateCompilation( assemblyName: "IVT", options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()), source: new[] { Parse(@" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Lib, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] namespace NamespaceContainingInternalsOnly { internal static class Extensions { internal static void Goo(this int x) {} } } "), signing }); var libCompilation = CreateCompilation( assemblyName: "Lib", options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()), references: new[] { ivtCompilation.ToMetadataReference() }, source: new[] { Parse(@" using NamespaceContainingInternalsOnly; public class C { internal static void F(int x) { x.Goo(); } } "), signing }); libCompilation.VerifyDiagnostics(); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void SemanticModelCallDoesNotCountsAsUse() { var source = @" using System.Collections; using System.Collections.Generic; class C { void M() { return; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System.Collections; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"), // (3,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;") ); comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(3)); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System.Collections; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"), // (3,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;") ); } [Fact] public void NoHiddenDiagnosticsForWarningLevel0() { var source = @" using System.Collections; using System.Collections.Generic; class C { void M() { return; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(0)); comp.VerifyDiagnostics(); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void INF_UnusedUsingDirective() { var source = @" using System.Collections; using C = System.Console; "; CreateCompilation(source).VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System.Collections; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"), // (3,1): info CS8019: Unnecessary using directive. // using C = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using C = System.Console;")); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void INF_UnusedExternAlias() { var source = @" extern alias A; "; var lib = CreateEmptyCompilation("", assemblyName: "lib"); var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("A")) }); comp.VerifyDiagnostics( // (2,1): info CS8020: Unused extern alias. // extern alias A; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias A;")); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void CrefCountsAsUse() { var source = @" using System; /// <see cref='Console'/> public class C { } "; // Not reporting doc comment diagnostics. It is still a use. CreateCompilation(source).VerifyDiagnostics(); // Binding doc comments. CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(); } [WorkItem(770147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770147")] [Fact] public void InfoAndWarnAsError() { var source = @" using System; "; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyEmitDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithWarningAsError(false)); } [Fact] public void UnusedUsingInteractive() { var tree = Parse("using System;", options: TestOptions.Script); var comp = CSharpCompilation.CreateScriptCompilation("sub1", tree, new[] { MscorlibRef_v4_0_30316_17626 }); comp.VerifyDiagnostics(); } [Fact] public void UnusedUsingScript() { var tree = Parse("using System;", options: TestOptions.Script); var comp = CreateCompilationWithMscorlib45(new[] { tree }); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); } [Fact, WorkItem(18348, "https://github.com/dotnet/roslyn/issues/18348")] public void IncorrectUnusedUsingWhenAttributeOnParameter_01() { var source1 = @"using System.Runtime.InteropServices; partial class Program { partial void M([Out] [In] ref int x) { } }"; var source2 = @"partial class Program { partial void M(ref int x); }"; var comp = CreateCompilation(new[] { source1, source2 }); var tree = comp.SyntaxTrees[0]; //comp.VerifyDiagnostics(); // doing this first hides the symptoms of the bug var model = comp.GetSemanticModel(tree); // There should be no diagnostics. model.GetDiagnostics().Verify( //// (1,1): hidden CS8019: Unnecessary using directive. //// using System.Runtime.InteropServices; //Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Runtime.InteropServices;").WithLocation(1, 1) ); } [Fact, WorkItem(18348, "https://github.com/dotnet/roslyn/issues/18348")] public void IncorrectUnusedUsingWhenAttributeOnParameter_02() { var source1 = @"using System.Runtime.InteropServices; partial class Program { partial void M([Out] [In] ref int x); }"; var source2 = @"partial class Program { partial void M(ref int x) { } }"; var comp = CreateCompilation(new[] { source1, source2 }); var tree = comp.SyntaxTrees[0]; //comp.VerifyDiagnostics(); // doing this first hides the symptoms of the bug var model = comp.GetSemanticModel(tree); // There should be no diagnostics. model.GetDiagnostics().Verify( //// (1,1): hidden CS8019: Unnecessary using directive. //// using System.Runtime.InteropServices; //Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Runtime.InteropServices;").WithLocation(1, 1) ); } [Fact, WorkItem(2773, "https://github.com/dotnet/roslyn/issues/2773")] public void UsageInDocComment() { var source = @"using X; /// <summary/> public class Program { /// <summary> /// <see cref=""Q""/> /// </summary> static void Main(string[] args) { } } namespace X { /// <summary/> public class Q { } } "; foreach (DocumentationMode documentationMode in Enum.GetValues(typeof(DocumentationMode))) { var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithDocumentationMode(documentationMode)); compilation.VerifyDiagnostics(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class GetUnusedImportDirectivesTests : SemanticModelTestBase { [Fact] public void UnusedUsing1() { var text = @" using System; class C { void Goo() { } }"; var tree = Parse(text); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); } [WorkItem(865627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865627")] [Fact] public void TestUnusedExtensionMarksImportsAsUsed() { string class1Source = @"using System; namespace ClassLibrary1 { public class Class1 { public void Method1(string arg1) { Console.WriteLine(arg1); } } } "; var classLib1 = CreateCompilation(source: class1Source, assemblyName: "ClassLibrary1"); string class2Source = @"using System; using ClassLibrary1; namespace ClassLibrary2 { public static class Class2 { public static void Method1(this Class1 arg0, string arg1) { Console.Write(""Erroneous: "" + arg1); } } }"; var classLib2 = CreateCompilation(source: class2Source, assemblyName: "ClassLibrary2", references: new[] { classLib1.ToMetadataReference() }); string consoleApplicationSource = @"using ClassLibrary2; using ClassLibrary1; namespace ConsoleApplication { class Program { static void Main(string[] args) { var instance1 = new Class1(); instance1.Method1(""Argument1""); } } }"; var tree = Parse(consoleApplicationSource); var comp = CreateCompilation(tree, new[] { classLib1.ToMetadataReference(), classLib2.ToMetadataReference() }, assemblyName: "ConsoleApplication"); var model = comp.GetSemanticModel(tree) as CSharpSemanticModel; var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single().Expression; //This is the crux of the test. //Without this line, with or without the fix, the model never gets pushed to evaluate extension method candidates //and therefore never marked ClassLibrary2 as a used import in consoleApplication. //Without the fix, this call used to result in ClassLibrary2 getting marked as used, after the fix, this call does not //result in changing ClassLibrary2's used status. model.GetMemberGroup(syntax); model.GetDiagnostics().Verify(Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ClassLibrary2;")); } [WorkItem(747219, "DevDiv2/DevDiv")] [Fact] public void UnusedUsing747219() { var text = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { Enumerable.Repeat(1, 1); } }"; var comp = CreateEmptyCompilation(text, new[] { MscorlibRef }); //all unused because system.core was not included and Enumerable didn't bind comp.VerifyDiagnostics( // (4,14): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?) // using System.Linq; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Linq").WithArguments("Linq", "System"), // (11,9): error CS0103: The name 'Enumerable' does not exist in the current context // Enumerable.Repeat(1, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Enumerable").WithArguments("Enumerable"), // (4,1): info CS8019: Unnecessary using directive. // using System.Linq; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (3,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;"), // (5,1): info CS8019: Unnecessary using directive. // using System.Threading.Tasks; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading.Tasks;") ); comp = comp.WithReferences(comp.References.Concat(SystemCoreRef)); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (3,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;"), // (5,1): info CS8019: Unnecessary using directive. // using System.Threading.Tasks; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading.Tasks;") ); } [Fact] public void UsedUsing1() { var text = @" using System; class C { void Goo() { Console.WriteLine(); } }"; var tree = Parse(text); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); } [Fact] public void SpeculativeBindingDoesNotAffectResult() { var text = @" using System; class C { void Goo() { /*here*/ } }"; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var position = text.IndexOf("/*here*/", StringComparison.Ordinal); var info = model.GetSpeculativeSymbolInfo(position, SyntaxFactory.IdentifierName("Console"), SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.NotNull(info.Symbol); Assert.Equal(SymbolKind.NamedType, info.Symbol.Kind); Assert.Equal("Console", info.Symbol.Name); Assert.Equal(SymbolKind.Namespace, info.Symbol.ContainingSymbol.Kind); Assert.Equal("System", info.Symbol.ContainingSymbol.Name); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;") ); } [ClrOnlyFact(ClrOnlyReason.Unknown)] public void AllAssemblyLevelAttributesMustBeBound() { var snkPath = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey).Path; var signing = Parse(@" using System.Reflection; [assembly: AssemblyVersion(""1.2.3.4"")] [assembly: AssemblyKeyFile(@""" + snkPath + @""")] "); var ivtCompilation = CreateCompilation( assemblyName: "IVT", options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()), source: new[] { Parse(@" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Lib, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] namespace NamespaceContainingInternalsOnly { internal static class Extensions { internal static void Goo(this int x) {} } } "), signing }); var libCompilation = CreateCompilation( assemblyName: "Lib", options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()), references: new[] { ivtCompilation.ToMetadataReference() }, source: new[] { Parse(@" using NamespaceContainingInternalsOnly; public class C { internal static void F(int x) { x.Goo(); } } "), signing }); libCompilation.VerifyDiagnostics(); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void SemanticModelCallDoesNotCountsAsUse() { var source = @" using System.Collections; using System.Collections.Generic; class C { void M() { return; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System.Collections; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"), // (3,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;") ); comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(3)); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System.Collections; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"), // (3,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;") ); } [Fact] public void NoHiddenDiagnosticsForWarningLevel0() { var source = @" using System.Collections; using System.Collections.Generic; class C { void M() { return; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(0)); comp.VerifyDiagnostics(); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void INF_UnusedUsingDirective() { var source = @" using System.Collections; using C = System.Console; "; CreateCompilation(source).VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System.Collections; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"), // (3,1): info CS8019: Unnecessary using directive. // using C = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using C = System.Console;")); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void INF_UnusedExternAlias() { var source = @" extern alias A; "; var lib = CreateEmptyCompilation("", assemblyName: "lib"); var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("A")) }); comp.VerifyDiagnostics( // (2,1): info CS8020: Unused extern alias. // extern alias A; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias A;")); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void CrefCountsAsUse() { var source = @" using System; /// <see cref='Console'/> public class C { } "; // Not reporting doc comment diagnostics. It is still a use. CreateCompilation(source).VerifyDiagnostics(); // Binding doc comments. CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(); } [WorkItem(770147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770147")] [Fact] public void InfoAndWarnAsError() { var source = @" using System; "; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyEmitDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithWarningAsError(false)); } [Fact] public void UnusedUsingInteractive() { var tree = Parse("using System;", options: TestOptions.Script); var comp = CSharpCompilation.CreateScriptCompilation("sub1", tree, new[] { MscorlibRef_v4_0_30316_17626 }); comp.VerifyDiagnostics(); } [Fact] public void UnusedUsingScript() { var tree = Parse("using System;", options: TestOptions.Script); var comp = CreateCompilationWithMscorlib45(new[] { tree }); comp.VerifyDiagnostics( // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); } [Fact, WorkItem(18348, "https://github.com/dotnet/roslyn/issues/18348")] public void IncorrectUnusedUsingWhenAttributeOnParameter_01() { var source1 = @"using System.Runtime.InteropServices; partial class Program { partial void M([Out] [In] ref int x) { } }"; var source2 = @"partial class Program { partial void M(ref int x); }"; var comp = CreateCompilation(new[] { source1, source2 }); var tree = comp.SyntaxTrees[0]; //comp.VerifyDiagnostics(); // doing this first hides the symptoms of the bug var model = comp.GetSemanticModel(tree); // There should be no diagnostics. model.GetDiagnostics().Verify( //// (1,1): hidden CS8019: Unnecessary using directive. //// using System.Runtime.InteropServices; //Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Runtime.InteropServices;").WithLocation(1, 1) ); } [Fact, WorkItem(18348, "https://github.com/dotnet/roslyn/issues/18348")] public void IncorrectUnusedUsingWhenAttributeOnParameter_02() { var source1 = @"using System.Runtime.InteropServices; partial class Program { partial void M([Out] [In] ref int x); }"; var source2 = @"partial class Program { partial void M(ref int x) { } }"; var comp = CreateCompilation(new[] { source1, source2 }); var tree = comp.SyntaxTrees[0]; //comp.VerifyDiagnostics(); // doing this first hides the symptoms of the bug var model = comp.GetSemanticModel(tree); // There should be no diagnostics. model.GetDiagnostics().Verify( //// (1,1): hidden CS8019: Unnecessary using directive. //// using System.Runtime.InteropServices; //Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Runtime.InteropServices;").WithLocation(1, 1) ); } [Fact, WorkItem(2773, "https://github.com/dotnet/roslyn/issues/2773")] public void UsageInDocComment() { var source = @"using X; /// <summary/> public class Program { /// <summary> /// <see cref=""Q""/> /// </summary> static void Main(string[] args) { } } namespace X { /// <summary/> public class Q { } } "; foreach (DocumentationMode documentationMode in Enum.GetValues(typeof(DocumentationMode))) { var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithDocumentationMode(documentationMode)); compilation.VerifyDiagnostics(); } } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Compilers/CSharp/Test/Symbol/Compilation/SymbolSearchTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolSearchTests : CSharpTestBase { [Fact] public void TestSymbolFilterNone() { Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(n => true, SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(n => true, SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName("", SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName("", SymbolFilter.None); }); } [Fact] public void TestPredicateNull() { Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(predicate: null); }); Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(predicate: null); }); } [Fact] public void TestNameNull() { Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(name: null); }); Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(name: null); }); } [Fact] public void TestMergedNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: false, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: true, count: 0); } [Fact] public void TestSourceNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: false, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: true, count: 0); } [Fact] public void TestClassInMergedNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: true, count: 0); } [Fact] public void TestClassInSourceNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: true, count: 0); } [Fact] public void TestMembers() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: false, count: 0); } [Fact] public void TestPartialSearch() { var compilation = GetTestCompilation(); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 4); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: false, count: 4); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: true, count: 8); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: false, count: 1); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: true, count: 5); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: false, count: 5); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 9); Test(compilation, n => n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 2); } [WorkItem(876191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876191")] [Fact] public void TestExplicitInterfaceSearch() { const string source = @" interface I { void M(); } class Explicit : I { void I.M() { } } class Implicit : I { public void M() { } } "; var compilation = CreateCompilation(new[] { source }); Test(compilation, n => n.IndexOf("M", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 3); } private static CSharpCompilation GetTestCompilation() { const string source = @" namespace System { public class Test { } } namespace MyNamespace { public class Test1 { } } public class MyClass { private int myField; internal int MyProperty { get; set; } void MyMethod() { } public event EventHandler MyEvent; delegate string MyDelegate(int i); } struct MyStruct { } interface MyInterface { } enum Enum { EnumValue } "; return CreateCompilation(source: new string[] { source }); } private static void TestNameAndPredicate(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count) { Test(compilation, name, includeNamespace, includeType, includeMember, count); Test(compilation, n => n == name, includeNamespace, includeType, includeMember, count); } private static void Test(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count) { SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember); Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter)); Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count()); } private static void Test(CSharpCompilation compilation, Func<string, bool> predicate, bool includeNamespace, bool includeType, bool includeMember, int count) { SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember); Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter)); Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count()); } private static SymbolFilter ComputeFilter(bool includeNamespace, bool includeType, bool includeMember) { var filter = SymbolFilter.None; filter = includeNamespace ? (filter | SymbolFilter.Namespace) : filter; filter = includeType ? (filter | SymbolFilter.Type) : filter; filter = includeMember ? (filter | SymbolFilter.Member) : filter; return filter; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolSearchTests : CSharpTestBase { [Fact] public void TestSymbolFilterNone() { Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(n => true, SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(n => true, SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName("", SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName("", SymbolFilter.None); }); } [Fact] public void TestPredicateNull() { Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(predicate: null); }); Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(predicate: null); }); } [Fact] public void TestNameNull() { Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(name: null); }); Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(name: null); }); } [Fact] public void TestMergedNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: false, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: true, count: 0); } [Fact] public void TestSourceNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: false, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: true, count: 0); } [Fact] public void TestClassInMergedNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: true, count: 0); } [Fact] public void TestClassInSourceNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: true, count: 0); } [Fact] public void TestMembers() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: false, count: 0); } [Fact] public void TestPartialSearch() { var compilation = GetTestCompilation(); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 4); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: false, count: 4); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: true, count: 8); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: false, count: 1); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: true, count: 5); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: false, count: 5); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 9); Test(compilation, n => n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 2); } [WorkItem(876191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876191")] [Fact] public void TestExplicitInterfaceSearch() { const string source = @" interface I { void M(); } class Explicit : I { void I.M() { } } class Implicit : I { public void M() { } } "; var compilation = CreateCompilation(new[] { source }); Test(compilation, n => n.IndexOf("M", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 3); } private static CSharpCompilation GetTestCompilation() { const string source = @" namespace System { public class Test { } } namespace MyNamespace { public class Test1 { } } public class MyClass { private int myField; internal int MyProperty { get; set; } void MyMethod() { } public event EventHandler MyEvent; delegate string MyDelegate(int i); } struct MyStruct { } interface MyInterface { } enum Enum { EnumValue } "; return CreateCompilation(source: new string[] { source }); } private static void TestNameAndPredicate(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count) { Test(compilation, name, includeNamespace, includeType, includeMember, count); Test(compilation, n => n == name, includeNamespace, includeType, includeMember, count); } private static void Test(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count) { SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember); Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter)); Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count()); } private static void Test(CSharpCompilation compilation, Func<string, bool> predicate, bool includeNamespace, bool includeType, bool includeMember, int count) { SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember); Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter)); Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count()); } private static SymbolFilter ComputeFilter(bool includeNamespace, bool includeType, bool includeMember) { var filter = SymbolFilter.None; filter = includeNamespace ? (filter | SymbolFilter.Namespace) : filter; filter = includeType ? (filter | SymbolFilter.Type) : filter; filter = includeMember ? (filter | SymbolFilter.Member) : filter; return filter; } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/StaticKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class StaticKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticInLambdaTest() VerifyRecommendationsContain(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticNotInsideSingleLineLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() | </MethodBody>, "Static") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class StaticKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticInLambdaTest() VerifyRecommendationsContain(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticNotInsideSingleLineLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() | </MethodBody>, "Static") End Sub End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/VisualStudio/Core/Test/Venus/VisualBasicContainedLanguageSupportTests.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.Editor Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.TextManager.Interop Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus Public Class VisualBasicContainedLanguageCodeSupportTests Inherits AbstractContainedLanguageCodeSupportTests #Region "IsValid Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_1() AssertValidId("field") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Escaped() AssertValidId("[field]") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_EscapedKeyword() AssertValidId("[Class]") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_ContainsNumbers() AssertValidId("abc123") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Keyword() AssertNotValidId("Class") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_StartsWithNumber() AssertNotValidId("123abc") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Punctuation() AssertNotValidId("abc.abc") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_TypeChar() AssertValidId("abc$") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_TypeCharInMiddle() AssertNotValidId("abc$abc") End Sub #End Region #Region "GetBaseClassName Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_NonexistingClass() Dim code As String = <text>Class c End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.False(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "A", CancellationToken.None, baseClassName)) Assert.Null(baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromObject() Dim code As String = <text>Class C End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("Object", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromFrameworkType() Dim code As String = <text> Imports System Class C Inherits Exception End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("System.Exception", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromUserDefinedType() Dim code As String = <text> Class B End Class Class C Inherits B End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_FullyQualifiedNames() Dim code As String = <text> Namespace N Class B End Class Class C Inherits B End Class End Namespace</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C", CancellationToken.None, baseClassName)) Assert.Equal("N.B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_MinimallyQualifiedNames() Dim code As String = <text> Namespace N Class B End Class Class C Inherits B End Class End Namespace</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C", CancellationToken.None, baseClassName)) Assert.Equal("N.B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_EscapedKeyword() Dim code As String = <text> Class [Class] End Class Class Derived Inherits [Class] End Class </text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "Derived", CancellationToken.None, baseClassName)) Assert.Equal("[Class]", baseClassName) End Using End Sub #End Region #Region "CreateUniqueEventName Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_ButtonClick() Dim code As String = <text> Public Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class </text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionWithEventHandler() Dim code As String = <text> Public Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class </text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionWithOtherMembers() Dim code As String = <text> Public Partial Class _Default Inherits System.Web.UI.Page Public Property Button1_Click As String Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionFromPartialClass() Dim code As String = <text> Public Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class Public Partial Class _Default Public Property Button1_Click As String End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionFromBaseClass() Dim code As String = <text> Public Partial Class _Default Inherits MyBaseClass Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class Public Class MyBaseClass Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub #End Region #Region "GetCompatibleEventHandlers" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_EventDoesntExist() Dim code As String = <text> Imports System Public Class Button End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Assert.Throws(Of InvalidOperationException)( Sub() ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) End Sub) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_ObjTypeNameIsWrong() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Assert.Throws(Of InvalidOperationException)( Sub() ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="CheckBox", nameOfEvent:="Click", cancellationToken:=Nothing) End Sub) End Using End Sub ' To Do: Investigate - this feels wrong. when Handles Clause exists <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_MatchExists() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal(1, eventHandlers.Count()) Assert.Equal("Page_Load", eventHandlers.Single().Item1) Assert.Equal("Page_Load(Object,System.EventArgs)", eventHandlers.Single().Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_MatchesExist() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal(2, eventHandlers.Count()) ' It has to be page_load and button click, but are they always ordered in the same way? End Using End Sub ' add tests for CompatibleSignatureToDelegate (#params, return type) #End Region #Region "GetEventHandlerMemberId" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetEventHandlerMemberId_HandlerExists() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerId) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetEventHandlerMemberId_CantFindHandler() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", cancellationToken:=Nothing) Assert.Equal(Nothing, eventHandlerId) End Using End Sub #End Region #Region "EnsureEventHandler" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestEnsureEventHandler_HandlerExists() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:="Button1", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", itemidInsertionPoint:=0, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) ' Since a valid handler exists, item2 and item3 of the tuple returned must be nothing Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1) Assert.Equal(Nothing, eventHandlerIdTextPosition.Item2) Assert.Equal(New TextSpan(), eventHandlerIdTextPosition.Item3) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestEnsureEventHandler_GenerateNewHandler() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) End Sub End Class</text>.NormalizedValue Dim generatedCode As String = <text> Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub</text>.NormalizedValue Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:="Button1", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", itemidInsertionPoint:=0, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1) TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language) Assert.Equal(New TextSpan With {.iStartLine = 12, .iEndLine = 12}, eventHandlerIdTextPosition.Item3) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> <WorkItem(850035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850035")> Public Sub TestEnsureEventHandler_WithHandlesAndNullObjectName() Dim code As String = " Imports System Namespace System.Web.UI Public Class Page Public Event Load as EventHandler End Class End Namespace Public Class _Default Inherits System.Web.UI.Page End Class" Dim generatedCode As String = " Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:=Nothing, objectTypeName:="System.Web.UI.Page", nameOfEvent:="Load", eventHandlerName:="Page_Load", itemidInsertionPoint:=0, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) Assert.Equal("Page_Load(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1) TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language) Assert.Equal(New TextSpan With {.iStartLine = 12, .iEndLine = 12}, eventHandlerIdTextPosition.Item3) End Using End Sub #End Region #Region "GetMemberNavigationPoint" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMemberNavigationPoint() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value ' Expect the cursor to be inside the method body of Button1_Click, line 14 column 8 Dim expectedSpan As New Microsoft.VisualStudio.TextManager.Interop.TextSpan() With { .iStartLine = 14, .iStartIndex = 8, .iEndLine = 14, .iEndIndex = 8 } Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim targetDocument As Document = Nothing Dim actualSpan As TextSpan = Nothing If Not ContainedLanguageCodeSupport.TryGetMemberNavigationPoint( thisDocument:=document, className:="_Default", uniqueMemberID:="Button1_Click(Object,System.EventArgs)", textSpan:=actualSpan, targetDocument:=targetDocument, cancellationToken:=Nothing) Then Assert.True(False, "should have succeeded") End If Assert.Equal(expectedSpan, actualSpan) End Using End Sub #End Region #Region "GetMembers" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongParamType() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object, e As Object) End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongParamCount() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object) End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongReturnType() Dim code As String = <text> Imports System Public Partial Class _Default Protected Function Page_Load(sender As Object, e As EventArgs) As Integer End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub ' To Do: Investigate, this returns the method even if handles is missing. that ok? <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlers() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Page_Load", userFunction.Item1) Assert.Equal("Page_Load(Object,System.EventArgs)", userFunction.Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_UserFunctions() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Test(x as String) End Sub End Class </text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Test", userFunction.Item1) Assert.Equal("Test(String)", userFunction.Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_Events() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="Button", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Click", userFunction.Item1) Assert.Equal("Click(EVENT)", userFunction.Item2) End Using End Sub #End Region #Region "OnRenamed (TryRenameElement)" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableMembers() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.Page_Load", newFullyQualifiedName:="_Default.Page_Load1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub ' To Do: Who tests the fully qualified names and their absence? <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_UnresolvableMembers() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.Fictional", newFullyQualifiedName:="_Default.Fictional1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.False(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableClass() Dim code As String = <text>Public Partial Class Goo End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASS, oldFullyQualifiedName:="Goo", newFullyQualifiedName:="Bar", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableNamespace() Dim code As String = <text>Namespace Goo End Namespace</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_NAMESPACE, oldFullyQualifiedName:="Goo", newFullyQualifiedName:="Bar", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_Button() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.button", newFullyQualifiedName:="_Default.button1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub #End Region ' TODO: Does Dev10 cover more here, like conflicts with existing members? Protected Overrides ReadOnly Property DefaultCode As String Get Return <text> Class C End Class </text>.Value End Get End Property Protected Overrides ReadOnly Property Language As String Get Return Microsoft.CodeAnalysis.LanguageNames.VisualBasic End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.TextManager.Interop Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus Public Class VisualBasicContainedLanguageCodeSupportTests Inherits AbstractContainedLanguageCodeSupportTests #Region "IsValid Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_1() AssertValidId("field") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Escaped() AssertValidId("[field]") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_EscapedKeyword() AssertValidId("[Class]") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_ContainsNumbers() AssertValidId("abc123") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Keyword() AssertNotValidId("Class") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_StartsWithNumber() AssertNotValidId("123abc") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Punctuation() AssertNotValidId("abc.abc") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_TypeChar() AssertValidId("abc$") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_TypeCharInMiddle() AssertNotValidId("abc$abc") End Sub #End Region #Region "GetBaseClassName Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_NonexistingClass() Dim code As String = <text>Class c End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.False(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "A", CancellationToken.None, baseClassName)) Assert.Null(baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromObject() Dim code As String = <text>Class C End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("Object", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromFrameworkType() Dim code As String = <text> Imports System Class C Inherits Exception End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("System.Exception", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromUserDefinedType() Dim code As String = <text> Class B End Class Class C Inherits B End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_FullyQualifiedNames() Dim code As String = <text> Namespace N Class B End Class Class C Inherits B End Class End Namespace</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C", CancellationToken.None, baseClassName)) Assert.Equal("N.B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_MinimallyQualifiedNames() Dim code As String = <text> Namespace N Class B End Class Class C Inherits B End Class End Namespace</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C", CancellationToken.None, baseClassName)) Assert.Equal("N.B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_EscapedKeyword() Dim code As String = <text> Class [Class] End Class Class Derived Inherits [Class] End Class </text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "Derived", CancellationToken.None, baseClassName)) Assert.Equal("[Class]", baseClassName) End Using End Sub #End Region #Region "CreateUniqueEventName Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_ButtonClick() Dim code As String = <text> Public Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class </text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionWithEventHandler() Dim code As String = <text> Public Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class </text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionWithOtherMembers() Dim code As String = <text> Public Partial Class _Default Inherits System.Web.UI.Page Public Property Button1_Click As String Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionFromPartialClass() Dim code As String = <text> Public Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class Public Partial Class _Default Public Property Button1_Click As String End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionFromBaseClass() Dim code As String = <text> Public Partial Class _Default Inherits MyBaseClass Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class Public Class MyBaseClass Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub #End Region #Region "GetCompatibleEventHandlers" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_EventDoesntExist() Dim code As String = <text> Imports System Public Class Button End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Assert.Throws(Of InvalidOperationException)( Sub() ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) End Sub) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_ObjTypeNameIsWrong() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Assert.Throws(Of InvalidOperationException)( Sub() ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="CheckBox", nameOfEvent:="Click", cancellationToken:=Nothing) End Sub) End Using End Sub ' To Do: Investigate - this feels wrong. when Handles Clause exists <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_MatchExists() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal(1, eventHandlers.Count()) Assert.Equal("Page_Load", eventHandlers.Single().Item1) Assert.Equal("Page_Load(Object,System.EventArgs)", eventHandlers.Single().Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_MatchesExist() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal(2, eventHandlers.Count()) ' It has to be page_load and button click, but are they always ordered in the same way? End Using End Sub ' add tests for CompatibleSignatureToDelegate (#params, return type) #End Region #Region "GetEventHandlerMemberId" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetEventHandlerMemberId_HandlerExists() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerId) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetEventHandlerMemberId_CantFindHandler() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", cancellationToken:=Nothing) Assert.Equal(Nothing, eventHandlerId) End Using End Sub #End Region #Region "EnsureEventHandler" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestEnsureEventHandler_HandlerExists() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:="Button1", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", itemidInsertionPoint:=0, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) ' Since a valid handler exists, item2 and item3 of the tuple returned must be nothing Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1) Assert.Equal(Nothing, eventHandlerIdTextPosition.Item2) Assert.Equal(New TextSpan(), eventHandlerIdTextPosition.Item3) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestEnsureEventHandler_GenerateNewHandler() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) End Sub End Class</text>.NormalizedValue Dim generatedCode As String = <text> Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub</text>.NormalizedValue Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:="Button1", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", itemidInsertionPoint:=0, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1) TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language) Assert.Equal(New TextSpan With {.iStartLine = 12, .iEndLine = 12}, eventHandlerIdTextPosition.Item3) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> <WorkItem(850035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850035")> Public Sub TestEnsureEventHandler_WithHandlesAndNullObjectName() Dim code As String = " Imports System Namespace System.Web.UI Public Class Page Public Event Load as EventHandler End Class End Namespace Public Class _Default Inherits System.Web.UI.Page End Class" Dim generatedCode As String = " Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:=Nothing, objectTypeName:="System.Web.UI.Page", nameOfEvent:="Load", eventHandlerName:="Page_Load", itemidInsertionPoint:=0, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) Assert.Equal("Page_Load(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1) TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language) Assert.Equal(New TextSpan With {.iStartLine = 12, .iEndLine = 12}, eventHandlerIdTextPosition.Item3) End Using End Sub #End Region #Region "GetMemberNavigationPoint" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMemberNavigationPoint() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value ' Expect the cursor to be inside the method body of Button1_Click, line 14 column 8 Dim expectedSpan As New Microsoft.VisualStudio.TextManager.Interop.TextSpan() With { .iStartLine = 14, .iStartIndex = 8, .iEndLine = 14, .iEndIndex = 8 } Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim targetDocument As Document = Nothing Dim actualSpan As TextSpan = Nothing If Not ContainedLanguageCodeSupport.TryGetMemberNavigationPoint( thisDocument:=document, className:="_Default", uniqueMemberID:="Button1_Click(Object,System.EventArgs)", textSpan:=actualSpan, targetDocument:=targetDocument, cancellationToken:=Nothing) Then Assert.True(False, "should have succeeded") End If Assert.Equal(expectedSpan, actualSpan) End Using End Sub #End Region #Region "GetMembers" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongParamType() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object, e As Object) End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongParamCount() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object) End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongReturnType() Dim code As String = <text> Imports System Public Partial Class _Default Protected Function Page_Load(sender As Object, e As EventArgs) As Integer End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub ' To Do: Investigate, this returns the method even if handles is missing. that ok? <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlers() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Page_Load", userFunction.Item1) Assert.Equal("Page_Load(Object,System.EventArgs)", userFunction.Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_UserFunctions() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Test(x as String) End Sub End Class </text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Test", userFunction.Item1) Assert.Equal("Test(String)", userFunction.Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_Events() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="Button", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Click", userFunction.Item1) Assert.Equal("Click(EVENT)", userFunction.Item2) End Using End Sub #End Region #Region "OnRenamed (TryRenameElement)" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableMembers() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.Page_Load", newFullyQualifiedName:="_Default.Page_Load1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub ' To Do: Who tests the fully qualified names and their absence? <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_UnresolvableMembers() Dim code As String = <text> Imports System Public Partial Class _Default Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.Fictional", newFullyQualifiedName:="_Default.Fictional1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.False(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableClass() Dim code As String = <text>Public Partial Class Goo End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASS, oldFullyQualifiedName:="Goo", newFullyQualifiedName:="Bar", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableNamespace() Dim code As String = <text>Namespace Goo End Namespace</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_NAMESPACE, oldFullyQualifiedName:="Goo", newFullyQualifiedName:="Bar", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_Button() Dim code As String = <text> Imports System Public Class Button Public Event Click As EventHandler End Class Public Class _Default Private button As Button Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click End Sub End Class</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.button", newFullyQualifiedName:="_Default.button1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub #End Region ' TODO: Does Dev10 cover more here, like conflicts with existing members? Protected Overrides ReadOnly Property DefaultCode As String Get Return <text> Class C End Class </text>.Value End Get End Property Protected Overrides ReadOnly Property Language As String Get Return Microsoft.CodeAnalysis.LanguageNames.VisualBasic End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/VisualStudio/Core/Test/DebuggerIntelliSense/CSharpDebuggerIntellisenseTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense <[UseExportProvider]> Public Class CSharpDebuggerIntellisenseTests <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacter() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacterInImmediateWindow() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function LocalsInBlockAfterInstructionPointer() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] int x = 3; string bar = "goo"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("x") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("x") state.SendBackspace() state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionAfterReturn() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] int x = 3; string bar = "goo"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) state.SendReturn() Assert.Equal("", state.GetCurrentViewLineText()) state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ExecutedUnexecutedLocals() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("goo") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("goo") state.SendTab() state.SendTypeChars(".ToS") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("ToString") For i As Integer = 0 To 7 state.SendBackspace() Next Await state.AssertNoCompletionSession() state.SendTypeChars("green") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("green") state.SendTab() state.SendTypeChars(".ToS") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("ToString") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals1() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { [|int variable1 = 0;|] } Console.Write(0); int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsContainAll("variable1", "variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals2() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; [|}|] Console.Write(0); int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsContainAll("variable1", "variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals3() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } [|Console.Write(0);|] int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals4() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); [|int variable2 = 0;|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals5() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); int variable2 = 0; [|}|] }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals6() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); int variable2 = 0; } [|}|]</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsDoNotContainAny("variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInParameterizedConstructor() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("new string(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInMethodCall() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void something(string z, int b) { } static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("something(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInGenericMethodCall() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void something&lt;T&gt;(&lt;T&gt; z, int b) { return z } static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("something<int>(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function InstructionPointerInForeach() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { int OOO = 3; foreach (var z in "goo") { [|var q = 1;|] } } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) Await state.VerifyCompletionAndDotAfter("q") Await state.VerifyCompletionAndDotAfter("OOO") End Using End Function <WorkItem(531165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531165")> <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ClassDesigner1() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static int STATICINT; static void Main(string[] args) { } [| |] public void M1() { throw new System.NotImplementedException(); } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("STATICI") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("STATICINT") End Using End Function <WorkItem(531167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531167")> <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ClassDesigner2() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { } [| |] void M1() { } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("1") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1124544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1124544")> <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionUsesContextBufferPositions() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null $$</Document> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacterInLinkedFileContext() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> { static void Main(string[] args) [|{|] } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.TextView.TextBuffer.Insert(0, "123123123123123123123123123 + ") state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("123123123123123123123123123 + arg", state.GetCurrentViewLineText()) state.SendTab() Assert.Contains("args", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function TypeNumberAtStartOfViewDoesNotCrash() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendTypeChars("4") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function BuilderSettingRetainedBetweenComputations_Watch() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=False) state.SendTypeChars("args") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("args", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) state.SendToggleCompletionMode() Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) state.SendTypeChars(".") Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function BuilderSettingRetainedBetweenComputations_Watch_Immediate() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=True) state.SendTypeChars("args") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("args", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) state.SendToggleCompletionMode() Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) state.SendTypeChars(".") Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) End Using End Function <WorkItem(1163608, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1163608")> <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function TestItemDescription() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("args") Dim description = Await state.GetSelectedItemDescriptionAsync() Assert.Contains("args", description.Text) state.SendTab() Assert.Contains("args", state.GetCurrentViewLineText()) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense <[UseExportProvider]> Public Class CSharpDebuggerIntellisenseTests <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacter() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacterInImmediateWindow() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function LocalsInBlockAfterInstructionPointer() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] int x = 3; string bar = "goo"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("x") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("x") state.SendBackspace() state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionAfterReturn() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] int x = 3; string bar = "goo"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) state.SendReturn() Assert.Equal("", state.GetCurrentViewLineText()) state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ExecutedUnexecutedLocals() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("goo") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("goo") state.SendTab() state.SendTypeChars(".ToS") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("ToString") For i As Integer = 0 To 7 state.SendBackspace() Next Await state.AssertNoCompletionSession() state.SendTypeChars("green") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("green") state.SendTab() state.SendTypeChars(".ToS") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("ToString") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals1() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { [|int variable1 = 0;|] } Console.Write(0); int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsContainAll("variable1", "variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals2() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; [|}|] Console.Write(0); int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsContainAll("variable1", "variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals3() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } [|Console.Write(0);|] int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals4() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); [|int variable2 = 0;|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals5() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); int variable2 = 0; [|}|] }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals6() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); int variable2 = 0; } [|}|]</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsDoNotContainAny("variable2") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInParameterizedConstructor() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("new string(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInMethodCall() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void something(string z, int b) { } static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("something(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInGenericMethodCall() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void something&lt;T&gt;(&lt;T&gt; z, int b) { return z } static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("something<int>(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function InstructionPointerInForeach() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { int OOO = 3; foreach (var z in "goo") { [|var q = 1;|] } } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) Await state.VerifyCompletionAndDotAfter("q") Await state.VerifyCompletionAndDotAfter("OOO") End Using End Function <WorkItem(531165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531165")> <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ClassDesigner1() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static int STATICINT; static void Main(string[] args) { } [| |] public void M1() { throw new System.NotImplementedException(); } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("STATICI") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("STATICINT") End Using End Function <WorkItem(531167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531167")> <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ClassDesigner2() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { } [| |] void M1() { } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("1") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1124544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1124544")> <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionUsesContextBufferPositions() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null $$</Document> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacterInLinkedFileContext() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> { static void Main(string[] args) [|{|] } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.TextView.TextBuffer.Insert(0, "123123123123123123123123123 + ") state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("123123123123123123123123123 + arg", state.GetCurrentViewLineText()) state.SendTab() Assert.Contains("args", state.GetCurrentViewLineText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function TypeNumberAtStartOfViewDoesNotCrash() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendTypeChars("4") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function BuilderSettingRetainedBetweenComputations_Watch() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=False) state.SendTypeChars("args") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("args", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) state.SendToggleCompletionMode() Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) state.SendTypeChars(".") Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function BuilderSettingRetainedBetweenComputations_Watch_Immediate() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=True) state.SendTypeChars("args") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("args", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) state.SendToggleCompletionMode() Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) state.SendTypeChars(".") Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) End Using End Function <WorkItem(1163608, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1163608")> <WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function TestItemDescription() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("args") Dim description = Await state.GetSelectedItemDescriptionAsync() Assert.Contains("args", description.Text) state.SendTab() Assert.Contains("args", state.GetCurrentViewLineText()) End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/EditorFeatures/Test/EditorConfigSettings/Data/CodeStyleSettingsTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias WORKSPACES; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using WORKSPACES::Microsoft.CodeAnalysis.Options; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorConfigSettings.Data { public class CodeStyleSettingsTest { [Theory] [InlineData(true)] [InlineData(false)] public static void CodeStyleSettingBoolFactory(bool defaultValue) { var option = CreateBoolOption(defaultValue); var editorConfigOptions = new TestAnalyzerConfigOptions(); var visualStudioOptions = new TestOptionSet<bool>(option.DefaultValue); var setting = CodeStyleSetting.Create(option, description: "TestDesciption", editorConfigOptions, visualStudioOptions, updater: null!, fileName: null!); Assert.Equal(string.Empty, setting.Category); Assert.Equal("TestDesciption", setting.Description); Assert.False(setting.IsDefinedInEditorConfig); Assert.Equal(typeof(bool), setting.Type); Assert.Equal(defaultValue, setting.Value); } [Theory] [InlineData(DayOfWeek.Monday)] [InlineData(DayOfWeek.Friday)] public static void CodeStyleSettingEnumFactory(DayOfWeek defaultValue) { var option = CreateEnumOption(defaultValue); var editorConfigOptions = new TestAnalyzerConfigOptions(); var visualStudioOptions = new TestOptionSet<DayOfWeek>(option.DefaultValue); var setting = CodeStyleSetting.Create(option, description: "TestDesciption", enumValues: (DayOfWeek[])Enum.GetValues(typeof(DayOfWeek)), valueDescriptions: Enum.GetNames(typeof(DayOfWeek)), editorConfigOptions, visualStudioOptions, updater: null!, fileName: null!); Assert.Equal(string.Empty, setting.Category); Assert.Equal("TestDesciption", setting.Description); Assert.False(setting.IsDefinedInEditorConfig); Assert.Equal(typeof(DayOfWeek), setting.Type); Assert.Equal(defaultValue, setting.Value); } private static Option2<CodeStyleOption2<bool>> CreateBoolOption(bool @default = false) { var option = CodeStyleOption2<bool>.Default; option = (CodeStyleOption2<bool>)((ICodeStyleOption)option).WithValue(@default); return new Option2<CodeStyleOption2<bool>>(feature: "TestFeature", name: "TestOption", defaultValue: option); } private static Option2<CodeStyleOption2<T>> CreateEnumOption<T>(T @default) where T : notnull, Enum { var option = CodeStyleOption2<T>.Default; option = (CodeStyleOption2<T>)((ICodeStyleOption)option).WithValue(@default); return new Option2<CodeStyleOption2<T>>(feature: "TestFeature", name: "TestOption", defaultValue: option); } private class TestAnalyzerConfigOptions : AnalyzerConfigOptions { private readonly IDictionary<string, string> _dictionary; public TestAnalyzerConfigOptions((string, string)[]? options = null) => _dictionary = options?.ToDictionary(x => x.Item1, x => x.Item2) ?? new Dictionary<string, string>(); public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) => _dictionary.TryGetValue(key, out value); } private class TestOptionSet<T> : OptionSet { private readonly object? _value; public TestOptionSet(CodeStyleOption2<T> value) => _value = value; public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) => this; internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) => Array.Empty<OptionKey>(); private protected override object? GetOptionCore(OptionKey optionKey) => _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. extern alias WORKSPACES; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using WORKSPACES::Microsoft.CodeAnalysis.Options; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorConfigSettings.Data { public class CodeStyleSettingsTest { [Theory] [InlineData(true)] [InlineData(false)] public static void CodeStyleSettingBoolFactory(bool defaultValue) { var option = CreateBoolOption(defaultValue); var editorConfigOptions = new TestAnalyzerConfigOptions(); var visualStudioOptions = new TestOptionSet<bool>(option.DefaultValue); var setting = CodeStyleSetting.Create(option, description: "TestDesciption", editorConfigOptions, visualStudioOptions, updater: null!, fileName: null!); Assert.Equal(string.Empty, setting.Category); Assert.Equal("TestDesciption", setting.Description); Assert.False(setting.IsDefinedInEditorConfig); Assert.Equal(typeof(bool), setting.Type); Assert.Equal(defaultValue, setting.Value); } [Theory] [InlineData(DayOfWeek.Monday)] [InlineData(DayOfWeek.Friday)] public static void CodeStyleSettingEnumFactory(DayOfWeek defaultValue) { var option = CreateEnumOption(defaultValue); var editorConfigOptions = new TestAnalyzerConfigOptions(); var visualStudioOptions = new TestOptionSet<DayOfWeek>(option.DefaultValue); var setting = CodeStyleSetting.Create(option, description: "TestDesciption", enumValues: (DayOfWeek[])Enum.GetValues(typeof(DayOfWeek)), valueDescriptions: Enum.GetNames(typeof(DayOfWeek)), editorConfigOptions, visualStudioOptions, updater: null!, fileName: null!); Assert.Equal(string.Empty, setting.Category); Assert.Equal("TestDesciption", setting.Description); Assert.False(setting.IsDefinedInEditorConfig); Assert.Equal(typeof(DayOfWeek), setting.Type); Assert.Equal(defaultValue, setting.Value); } private static Option2<CodeStyleOption2<bool>> CreateBoolOption(bool @default = false) { var option = CodeStyleOption2<bool>.Default; option = (CodeStyleOption2<bool>)((ICodeStyleOption)option).WithValue(@default); return new Option2<CodeStyleOption2<bool>>(feature: "TestFeature", name: "TestOption", defaultValue: option); } private static Option2<CodeStyleOption2<T>> CreateEnumOption<T>(T @default) where T : notnull, Enum { var option = CodeStyleOption2<T>.Default; option = (CodeStyleOption2<T>)((ICodeStyleOption)option).WithValue(@default); return new Option2<CodeStyleOption2<T>>(feature: "TestFeature", name: "TestOption", defaultValue: option); } private class TestAnalyzerConfigOptions : AnalyzerConfigOptions { private readonly IDictionary<string, string> _dictionary; public TestAnalyzerConfigOptions((string, string)[]? options = null) => _dictionary = options?.ToDictionary(x => x.Item1, x => x.Item2) ?? new Dictionary<string, string>(); public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) => _dictionary.TryGetValue(key, out value); } private class TestOptionSet<T> : OptionSet { private readonly object? _value; public TestOptionSet(CodeStyleOption2<T> value) => _value = value; public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) => this; internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) => Array.Empty<OptionKey>(); private protected override object? GetOptionCore(OptionKey optionKey) => _value; } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Compilers/Test/Resources/Core/MetadataTests/InterfaceAndClass/VBInterfaces01.dll
MZ@ !L!This program cannot be run in DOS mode. $PELO8N! .5 @@ @4W@`  H.text4  `.rsrc@@@.reloc `@B5H0"( *( *s s s s *0~o +*0~o +*0~o +*0~o +*0( ( +*0 ( +*0( +*0 ( +*0 - (+ ++ +*0 *( *0, { o -(+ { o  +*J( s } *:( }*0 { +*"}*BSJB v4.0.30319l#~t@#Strings#US#GUID#BlobW %3'!+  -  s sI% d= |( Ap)7:7 E7 O ] x~! #16 1_-1:1G!*P X ` " ) O( x5 B Fc!Fh4!lP!Fqh!x!%!!9!FqFFFFqF F F5 FFFF  FFFF! "F 1$"F CF\Fj22V $ 9I-Q$,4<$9,949<9Yaiqch)q2DL\LfqL). .@+L@$C$C3Ic$c3i+L3{LsL+L$+L$+L+L$ +L $@+L@$`+L`$+L+L+L$+L$+L$LDLLLmrw|w  OTsY^N[rx   $%&'uuQX_f^e    --l<Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1IPropIProp02IMeth01IMeth02IMeth03INestedNestedMicrosoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceget_ReadOnlyPropget_ReadOnlyPropWithParamsp1set_WriteOnlyPropValueset_WriteOnlyPropWithParamsget_NormalPropset_NormalPropget_NormalPropWithParamsp2set_NormalPropWithParamsReadOnlyPropReadOnlyPropWithParamsWriteOnlyPropWriteOnlyPropWithParamsNormalPropNormalPropWithParamsget_DefaultPropWithParamsset_DefaultPropWithParamsDefaultPropWithParamsSub01aryFunc01NestedSubpNestedFunc_sbyteget_ReadOnlySByteset_WriteOnlySBytevalueget_PropSByteset_PropSByteReadOnlySByteWriteOnlySBytePropSByteSystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeSystem.ReflectionDefaultMemberAttributeParamArrayAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeVBInterfaces01VBInterfaces01.dll \uF2Cz\V4?_ :        0 (          (( ( (   (          ( !  MyTemplate10.0.0.0  My.WebServicesMy.Application My.Computer My.User=  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__   DefaultPropWithParams TWrapNonExceptionThrows45 5_CorDllMainmscoree.dll% @0HX@dd4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0HInternalNameVBInterfaces01.dll(LegalCopyright POriginalFilenameVBInterfaces01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.00 05
MZ@ !L!This program cannot be run in DOS mode. $PELO8N! .5 @@ @4W@`  H.text4  `.rsrc@@@.reloc `@B5H0"( *( *s s s s *0~o +*0~o +*0~o +*0~o +*0( ( +*0 ( +*0( +*0 ( +*0 - (+ ++ +*0 *( *0, { o -(+ { o  +*J( s } *:( }*0 { +*"}*BSJB v4.0.30319l#~t@#Strings#US#GUID#BlobW %3'!+  -  s sI% d= |( Ap)7:7 E7 O ] x~! #16 1_-1:1G!*P X ` " ) O( x5 B Fc!Fh4!lP!Fqh!x!%!!9!FqFFFFqF F F5 FFFF  FFFF! "F 1$"F CF\Fj22V $ 9I-Q$,4<$9,949<9Yaiqch)q2DL\LfqL). .@+L@$C$C3Ic$c3i+L3{LsL+L$+L$+L+L$ +L $@+L@$`+L`$+L+L+L$+L$+L$LDLLLmrw|w  OTsY^N[rx   $%&'uuQX_f^e    --l<Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1IPropIProp02IMeth01IMeth02IMeth03INestedNestedMicrosoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceget_ReadOnlyPropget_ReadOnlyPropWithParamsp1set_WriteOnlyPropValueset_WriteOnlyPropWithParamsget_NormalPropset_NormalPropget_NormalPropWithParamsp2set_NormalPropWithParamsReadOnlyPropReadOnlyPropWithParamsWriteOnlyPropWriteOnlyPropWithParamsNormalPropNormalPropWithParamsget_DefaultPropWithParamsset_DefaultPropWithParamsDefaultPropWithParamsSub01aryFunc01NestedSubpNestedFunc_sbyteget_ReadOnlySByteset_WriteOnlySBytevalueget_PropSByteset_PropSByteReadOnlySByteWriteOnlySBytePropSByteSystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeSystem.ReflectionDefaultMemberAttributeParamArrayAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeVBInterfaces01VBInterfaces01.dll \uF2Cz\V4?_ :        0 (          (( ( (   (          ( !  MyTemplate10.0.0.0  My.WebServicesMy.Application My.Computer My.User=  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__   DefaultPropWithParams TWrapNonExceptionThrows45 5_CorDllMainmscoree.dll% @0HX@dd4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0HInternalNameVBInterfaces01.dll(LegalCopyright POriginalFilenameVBInterfaces01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.00 05
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Compilers/CSharp/Portable/Symbols/SpecializedSymbolCollections.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class SpecializedSymbolCollections { public static PooledHashSet<TSymbol> GetPooledSymbolHashSetInstance<TSymbol>() where TSymbol : Symbol { var instance = PooledSymbolHashSet<TSymbol>.s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } private static class PooledSymbolHashSet<TSymbol> where TSymbol : Symbol { internal static readonly ObjectPool<PooledHashSet<TSymbol>> s_poolInstance = PooledHashSet<TSymbol>.CreatePool(SymbolEqualityComparer.ConsiderEverything); } public static PooledDictionary<KSymbol, V> GetPooledSymbolDictionaryInstance<KSymbol, V>() where KSymbol : Symbol { var instance = PooledSymbolDictionary<KSymbol, V>.s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } private static class PooledSymbolDictionary<TSymbol, V> where TSymbol : Symbol { internal static readonly ObjectPool<PooledDictionary<TSymbol, V>> s_poolInstance = PooledDictionary<TSymbol, V>.CreatePool(SymbolEqualityComparer.ConsiderEverything); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class SpecializedSymbolCollections { public static PooledHashSet<TSymbol> GetPooledSymbolHashSetInstance<TSymbol>() where TSymbol : Symbol { var instance = PooledSymbolHashSet<TSymbol>.s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } private static class PooledSymbolHashSet<TSymbol> where TSymbol : Symbol { internal static readonly ObjectPool<PooledHashSet<TSymbol>> s_poolInstance = PooledHashSet<TSymbol>.CreatePool(SymbolEqualityComparer.ConsiderEverything); } public static PooledDictionary<KSymbol, V> GetPooledSymbolDictionaryInstance<KSymbol, V>() where KSymbol : Symbol { var instance = PooledSymbolDictionary<KSymbol, V>.s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } private static class PooledSymbolDictionary<TSymbol, V> where TSymbol : Symbol { internal static readonly ObjectPool<PooledDictionary<TSymbol, V>> s_poolInstance = PooledDictionary<TSymbol, V>.CreatePool(SymbolEqualityComparer.ConsiderEverything); } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.SelectionChangedEventSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class SelectionChangedEventSource : AbstractTaggerEventSource { private readonly ITextView _textView; public SelectionChangedEventSource(ITextView textView) => _textView = textView; public override void Connect() => _textView.Selection.SelectionChanged += OnSelectionChanged; public override void Disconnect() => _textView.Selection.SelectionChanged -= OnSelectionChanged; private void OnSelectionChanged(object? sender, EventArgs args) => 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 System; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class SelectionChangedEventSource : AbstractTaggerEventSource { private readonly ITextView _textView; public SelectionChangedEventSource(ITextView textView) => _textView = textView; public override void Connect() => _textView.Selection.SelectionChanged += OnSelectionChanged; public override void Disconnect() => _textView.Selection.SelectionChanged -= OnSelectionChanged; private void OnSelectionChanged(object? sender, EventArgs args) => RaiseChanged(); } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/VisualStudio/Core/Def/Implementation/Workspace/GlobalUndoServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; /// <summary> /// A service that provide a way to undo operations applied to the workspace /// </summary> [ExportWorkspaceServiceFactory(typeof(IGlobalUndoService), ServiceLayer.Host), Shared] internal partial class GlobalUndoServiceFactory : IWorkspaceServiceFactory { private readonly GlobalUndoService _singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GlobalUndoServiceFactory( IThreadingContext threadingContext, ITextUndoHistoryRegistry undoHistoryRegistry, SVsServiceProvider serviceProvider, Lazy<VisualStudioWorkspace> workspace) { _singleton = new GlobalUndoService(threadingContext, undoHistoryRegistry, serviceProvider, workspace); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => _singleton; private class GlobalUndoService : IGlobalUndoService { private readonly IThreadingContext _threadingContext; private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly IVsLinkedUndoTransactionManager _undoManager; private readonly Lazy<VisualStudioWorkspace> _lazyVSWorkspace; internal int ActiveTransactions; public GlobalUndoService(IThreadingContext threadingContext, ITextUndoHistoryRegistry undoHistoryRegistry, SVsServiceProvider serviceProvider, Lazy<VisualStudioWorkspace> lazyVSWorkspace) { _threadingContext = threadingContext; _undoHistoryRegistry = undoHistoryRegistry; _undoManager = (IVsLinkedUndoTransactionManager)serviceProvider.GetService(typeof(SVsLinkedUndoTransactionManager)); _lazyVSWorkspace = lazyVSWorkspace; } public bool CanUndo(Workspace workspace) { // only primary workspace supports global undo return _lazyVSWorkspace.Value == workspace; } public IWorkspaceGlobalUndoTransaction OpenGlobalUndoTransaction(Workspace workspace, string description) { if (!CanUndo(workspace)) { throw new ArgumentException(ServicesVSResources.given_workspace_doesn_t_support_undo); } var transaction = new WorkspaceUndoTransaction(_threadingContext, _undoHistoryRegistry, _undoManager, workspace, description, this); ActiveTransactions++; return transaction; } public bool IsGlobalTransactionOpen(Workspace workspace) => ActiveTransactions > 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; /// <summary> /// A service that provide a way to undo operations applied to the workspace /// </summary> [ExportWorkspaceServiceFactory(typeof(IGlobalUndoService), ServiceLayer.Host), Shared] internal partial class GlobalUndoServiceFactory : IWorkspaceServiceFactory { private readonly GlobalUndoService _singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GlobalUndoServiceFactory( IThreadingContext threadingContext, ITextUndoHistoryRegistry undoHistoryRegistry, SVsServiceProvider serviceProvider, Lazy<VisualStudioWorkspace> workspace) { _singleton = new GlobalUndoService(threadingContext, undoHistoryRegistry, serviceProvider, workspace); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => _singleton; private class GlobalUndoService : IGlobalUndoService { private readonly IThreadingContext _threadingContext; private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly IVsLinkedUndoTransactionManager _undoManager; private readonly Lazy<VisualStudioWorkspace> _lazyVSWorkspace; internal int ActiveTransactions; public GlobalUndoService(IThreadingContext threadingContext, ITextUndoHistoryRegistry undoHistoryRegistry, SVsServiceProvider serviceProvider, Lazy<VisualStudioWorkspace> lazyVSWorkspace) { _threadingContext = threadingContext; _undoHistoryRegistry = undoHistoryRegistry; _undoManager = (IVsLinkedUndoTransactionManager)serviceProvider.GetService(typeof(SVsLinkedUndoTransactionManager)); _lazyVSWorkspace = lazyVSWorkspace; } public bool CanUndo(Workspace workspace) { // only primary workspace supports global undo return _lazyVSWorkspace.Value == workspace; } public IWorkspaceGlobalUndoTransaction OpenGlobalUndoTransaction(Workspace workspace, string description) { if (!CanUndo(workspace)) { throw new ArgumentException(ServicesVSResources.given_workspace_doesn_t_support_undo); } var transaction = new WorkspaceUndoTransaction(_threadingContext, _undoHistoryRegistry, _undoManager, workspace, description, this); ActiveTransactions++; return transaction; } public bool IsGlobalTransactionOpen(Workspace workspace) => ActiveTransactions > 0; } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Test/Diagnostics/PerfMargin/PerfMarginPanel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Windows; using System.Windows.Controls; using System.Windows.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; namespace Roslyn.Hosting.Diagnostics.PerfMargin { public class PerfMarginPanel : UserControl { private static readonly DataModel s_model = new DataModel(); private static readonly PerfEventActivityLogger s_logger = new PerfEventActivityLogger(s_model); private readonly ListView _mainListView; private readonly Grid _mainGrid; private readonly DispatcherTimer _timer; private readonly List<StatusIndicator> _indicators = new List<StatusIndicator>(); private ListView _detailsListView; private bool _stopTimer; public PerfMarginPanel() { Logger.SetLogger(AggregateLogger.AddOrReplace(s_logger, Logger.GetLogger(), l => l is PerfEventActivityLogger)); // grid _mainGrid = new Grid(); _mainGrid.ColumnDefinitions.Add(new ColumnDefinition()); _mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); _mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); // set diagnostic list _mainListView = CreateContent(new ActivityLevel[] { s_model.RootNode }.Concat(s_model.RootNode.Children), useWrapPanel: true); _mainListView.SelectionChanged += OnPerfItemsListSelectionChanged; Grid.SetRow(_mainListView, 0); _mainGrid.Children.Add(_mainListView); this.Content = _mainGrid; _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(500), DispatcherPriority.Background, UpdateUI, this.Dispatcher); StartTimer(); s_model.RootNode.IsActiveChanged += (s, e) => { if (_stopTimer) { StartTimer(); } }; } private void StartTimer() { _timer.Start(); _stopTimer = false; } private void UpdateUI(object sender, EventArgs e) { foreach (var item in _indicators) { item.UpdateOnUIThread(); } if (_stopTimer) { _timer.Stop(); } else { // Stop it next time if there was no activity. _stopTimer = true; } } private ListView CreateContent(IEnumerable<ActivityLevel> items, bool useWrapPanel) { var listView = new ListView(); foreach (var item in items) { StackPanel s = new StackPanel() { Orientation = Orientation.Horizontal }; ////g.HorizontalAlignment = HorizontalAlignment.Stretch; StatusIndicator indicator = new StatusIndicator(item); indicator.Subscribe(); indicator.Width = 30; indicator.Height = 10; s.Children.Add(indicator); _indicators.Add(indicator); TextBlock label = new TextBlock(); label.Text = item.Name; Grid.SetColumn(label, 1); s.Children.Add(label); s.ToolTip = item.Name; s.Tag = item; listView.Items.Add(s); } if (useWrapPanel) { listView.SelectionMode = SelectionMode.Single; listView.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled); var wrapPanelFactory = new FrameworkElementFactory(typeof(WrapPanel)); wrapPanelFactory.SetValue(WrapPanel.ItemWidthProperty, 120d); listView.ItemsPanel = new ItemsPanelTemplate(wrapPanelFactory); } return listView; } private void OnPerfItemsListSelectionChanged(object sender, SelectionChangedEventArgs e) { if (_detailsListView != null) { _mainGrid.ColumnDefinitions.RemoveAt(1); _mainGrid.Children.Remove(_detailsListView); foreach (StackPanel item in _detailsListView.Items) { var indicator = item.Children[0] as StatusIndicator; _indicators.Remove(indicator); indicator.Unsubscribe(); } _detailsListView = null; } var selectedItem = _mainListView.SelectedItem as StackPanel; if (selectedItem == null) { return; } if (selectedItem.Tag is ActivityLevel context && context.Children != null && context.Children.Any()) { _detailsListView = CreateContent(context.Children, useWrapPanel: false); _mainGrid.Children.Add(_detailsListView); _mainGrid.ColumnDefinitions.Add(new ColumnDefinition()); Grid.SetColumn(_detailsListView, 1); // Update the UI StartTimer(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Windows; using System.Windows.Controls; using System.Windows.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; namespace Roslyn.Hosting.Diagnostics.PerfMargin { public class PerfMarginPanel : UserControl { private static readonly DataModel s_model = new DataModel(); private static readonly PerfEventActivityLogger s_logger = new PerfEventActivityLogger(s_model); private readonly ListView _mainListView; private readonly Grid _mainGrid; private readonly DispatcherTimer _timer; private readonly List<StatusIndicator> _indicators = new List<StatusIndicator>(); private ListView _detailsListView; private bool _stopTimer; public PerfMarginPanel() { Logger.SetLogger(AggregateLogger.AddOrReplace(s_logger, Logger.GetLogger(), l => l is PerfEventActivityLogger)); // grid _mainGrid = new Grid(); _mainGrid.ColumnDefinitions.Add(new ColumnDefinition()); _mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); _mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); // set diagnostic list _mainListView = CreateContent(new ActivityLevel[] { s_model.RootNode }.Concat(s_model.RootNode.Children), useWrapPanel: true); _mainListView.SelectionChanged += OnPerfItemsListSelectionChanged; Grid.SetRow(_mainListView, 0); _mainGrid.Children.Add(_mainListView); this.Content = _mainGrid; _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(500), DispatcherPriority.Background, UpdateUI, this.Dispatcher); StartTimer(); s_model.RootNode.IsActiveChanged += (s, e) => { if (_stopTimer) { StartTimer(); } }; } private void StartTimer() { _timer.Start(); _stopTimer = false; } private void UpdateUI(object sender, EventArgs e) { foreach (var item in _indicators) { item.UpdateOnUIThread(); } if (_stopTimer) { _timer.Stop(); } else { // Stop it next time if there was no activity. _stopTimer = true; } } private ListView CreateContent(IEnumerable<ActivityLevel> items, bool useWrapPanel) { var listView = new ListView(); foreach (var item in items) { StackPanel s = new StackPanel() { Orientation = Orientation.Horizontal }; ////g.HorizontalAlignment = HorizontalAlignment.Stretch; StatusIndicator indicator = new StatusIndicator(item); indicator.Subscribe(); indicator.Width = 30; indicator.Height = 10; s.Children.Add(indicator); _indicators.Add(indicator); TextBlock label = new TextBlock(); label.Text = item.Name; Grid.SetColumn(label, 1); s.Children.Add(label); s.ToolTip = item.Name; s.Tag = item; listView.Items.Add(s); } if (useWrapPanel) { listView.SelectionMode = SelectionMode.Single; listView.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled); var wrapPanelFactory = new FrameworkElementFactory(typeof(WrapPanel)); wrapPanelFactory.SetValue(WrapPanel.ItemWidthProperty, 120d); listView.ItemsPanel = new ItemsPanelTemplate(wrapPanelFactory); } return listView; } private void OnPerfItemsListSelectionChanged(object sender, SelectionChangedEventArgs e) { if (_detailsListView != null) { _mainGrid.ColumnDefinitions.RemoveAt(1); _mainGrid.Children.Remove(_detailsListView); foreach (StackPanel item in _detailsListView.Items) { var indicator = item.Children[0] as StatusIndicator; _indicators.Remove(indicator); indicator.Unsubscribe(); } _detailsListView = null; } var selectedItem = _mainListView.SelectedItem as StackPanel; if (selectedItem == null) { return; } if (selectedItem.Tag is ActivityLevel context && context.Children != null && context.Children.Any()) { _detailsListView = CreateContent(context.Children, useWrapPanel: false); _mainGrid.Children.Add(_detailsListView); _mainGrid.ColumnDefinitions.Add(new ColumnDefinition()); Grid.SetColumn(_detailsListView, 1); // Update the UI StartTimer(); } } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ParenthesizedExpression: return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics); default: return BindExpression(node, diagnostics, invoked, indexed); } } private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult) { // If overload resolution has failed then we want to stash away the original methods that we // considered so that the IDE can display tooltips or other information about them. // However, if a method group contained a generic method that was type inferred then // the IDE wants information about the *inferred* method, not the original unconstructed // generic method. if (overloadResolutionResult == null) { return ImmutableArray<MethodSymbol>.Empty; } var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var result in overloadResolutionResult.Results) { builder.Add(result.Member); } return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Helper method to create a synthesized method invocation expression. /// </summary> /// <param name="node">Syntax Node.</param> /// <param name="receiver">Receiver for the method call.</param> /// <param name="methodName">Method to be invoked on the receiver.</param> /// <param name="args">Arguments to the method call.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="typeArgsSyntax">Optional type arguments syntax.</param> /// <param name="typeArgs">Optional type arguments.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param> /// <param name="allowUnexpandedForm">False to prevent selecting a params method in unexpanded form.</param> /// <returns>Synthesized method invocation expression.</returns> internal BoundExpression MakeInvocationExpression( SyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray<BoundExpression> args, BindingDiagnosticBag diagnostics, SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>), ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>), ImmutableArray<(string Name, Location Location)?> names = default, CSharpSyntaxNode? queryClause = null, bool allowFieldsAndProperties = false, bool allowUnexpandedForm = true, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(receiver != null); Debug.Assert(names.IsDefault || names.Length == args.Length); receiver = BindToNaturalType(receiver, diagnostics); var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary); // The other consumers of this helper (await and collection initializers) require the target member to be a method. if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess)) { Symbol symbol; MessageID msgId; if (boundExpression.Kind == BoundKind.FieldAccess) { msgId = MessageID.IDS_SK_FIELD; symbol = ((BoundFieldAccess)boundExpression).FieldSymbol; } else { msgId = MessageID.IDS_SK_PROPERTY; symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol; } diagnostics.Add( ErrorCode.ERR_BadSKknown, node.Location, methodName, msgId.Localize(), MessageID.IDS_SK_METHOD.Localize()); return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true); } boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); boundExpression.WasCompilerGenerated = true; var analyzedArguments = AnalyzedArguments.GetInstance(); Debug.Assert(!args.Any(e => e.Kind == BoundKind.OutVariablePendingInference || e.Kind == BoundKind.OutDeconstructVarPendingInference || e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType())); analyzedArguments.Arguments.AddRange(args); if (!names.IsDefault) { analyzedArguments.Names.AddRange(names); } BoundExpression result = BindInvocationExpression( node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm); // Query operator can't be called dynamically. if (queryClause != null && result.Kind == BoundKind.DynamicInvocation) { // the error has already been reported by BindInvocationExpression Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result.WasCompilerGenerated = true; analyzedArguments.Free(); return result; } #nullable disable /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression result; if (TryBindNameofOperator(node, diagnostics, out result)) { return result; // all of the binding is done by BindNameofOperator } // M(__arglist()) is legal, but M(__arglist(__arglist()) is not! bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression; AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); if (isArglist) { BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false); result = BindArgListOperator(node, diagnostics, analyzedArguments); } else { BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics); boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null; BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); result = BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics); } analyzedArguments.Free(); return result; } private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments) { bool hasErrors = analyzedArguments.HasErrors; // We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them. TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node); for (int i = 0; i < analyzedArguments.Arguments.Count; ++i) { BoundExpression argument = analyzedArguments.Arguments[i]; if (argument.Kind == BoundKind.OutVariablePendingInference) { analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics); } else if ((object)argument.Type == null && !argument.HasAnyErrors) { // We are going to need every argument in here to have a type. If we don't have one, // try converting it to object. We'll either succeed (if it is a null literal) // or fail with a good error message. // // Note that the native compiler converts null literals to object, and for everything // else it either crashes, or produces nonsense code. Roslyn improves upon this considerably. analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics); } else if (argument.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax); hasErrors = true; } else if (analyzedArguments.RefKind(i) == RefKind.None) { analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics); } switch (analyzedArguments.RefKind(i)) { case RefKind.None: case RefKind.Ref: break; default: // Disallow "in" or "out" arguments Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax); hasErrors = true; break; } } ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable(); ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors); } /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null, bool allowUnexpandedForm = true) { BoundExpression result; NamedTypeSymbol delegateType; if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic()) { // Either we have a dynamic method group invocation "dyn.M(...)" or // a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic // invocation and let the lowering pass sort it out. ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause); } else if (boundExpression.Kind == BoundKind.MethodGroup) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindMethodGroupInvocation( node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm, anyApplicableCandidates: out _); } else if ((object)(delegateType = GetDelegateType(boundExpression)) != null) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node)) { return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType); } else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics); } else { if (!boundExpression.HasAnyErrors) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location); } result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments); } CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics); return result; } private BoundExpression BindDynamicInvocation( SyntaxNode node, BoundExpression expression, AnalyzedArguments arguments, ImmutableArray<MethodSymbol> applicableMethods, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics); bool hasErrors = false; if (expression.Kind == BoundKind.MethodGroup) { BoundMethodGroup methodGroup = (BoundMethodGroup)expression; BoundExpression receiver = methodGroup.ReceiverOpt; // receiver is null if we are calling a static method declared on an outer class via its simple name: if (receiver != null) { switch (receiver.Kind) { case BoundKind.BaseReference: Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name); hasErrors = true; break; case BoundKind.ThisReference: // Can't call the HasThis method due to EE doing odd things with containing member and its containing type. if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated) { // Only a static method can be called in a constructor initializer. If we were not in a ctor initializer // the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before // the base constructor is called. We need to handle this as a type qualified static method call. // Also applicable to things like field initializers, which run before the ctor initializer. expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver, receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(), resultKind: methodGroup.ResultKind); } break; case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags, finalReceiver, methodGroup.ResultKind); break; } } } else { expression = BindToNaturalType(expression, diagnostics); } ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause); return new BoundDynamicInvocation( node, arguments.GetNames(), refKindsArray, applicableMethods, expression, argArray, type: Compilation.DynamicType, hasErrors: hasErrors); } private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { if (arguments.Names.Count == 0) { return; } if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { return; } bool seenName = false; for (int i = 0; i < arguments.Names.Count; i++) { if (arguments.Names[i] != null) { seenName = true; } else if (seenName) { Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax); return; } } } private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count); builder.AddRange(arguments.Arguments); for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = builder[i] switch { OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics), BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics), var arg => BindToNaturalType(arg, diagnostics) }; } return builder.ToImmutableAndFree(); } // Returns true if there were errors. private static bool ReportBadDynamicArguments( SyntaxNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKinds, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { bool hasErrors = false; bool reportedBadQuery = false; if (!refKinds.IsDefault) { for (int argIndex = 0; argIndex < refKinds.Length; argIndex++) { if (refKinds[argIndex] == RefKind.In) { Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax); hasErrors = true; } } } foreach (var arg in arguments) { if (!IsLegalDynamicOperand(arg)) { if (queryClause != null && !reportedBadQuery) { reportedBadQuery = true; Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node); hasErrors = true; continue; } if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda) { // Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.MethodGroup) { // Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.ArgListOperator) { // Not a great error message, since __arglist is not a type, but it'll do. // error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist"); } else { // Lambdas,anonymous methods and method groups are the typeless expressions that // are not usable as dynamic arguments; if we get here then the expression must have a type. Debug.Assert((object)arg.Type != null); // error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type); hasErrors = true; } } } return hasErrors; } private BoundExpression BindDelegateInvocation( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, NamedTypeSymbol delegateType) { BoundExpression result; var methodGroup = MethodGroup.GetInstance(); methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod); var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: analyzedArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments // was dynamic then treat this as a dynamic call. if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } else { result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause); } overloadResolutionResult.Free(); methodGroup.Free(); return result; } private static bool HasApplicableConditionalMethod(OverloadResolutionResult<MethodSymbol> results) { var r = results.Results; for (int i = 0; i < r.Length; ++i) { if (r[i].IsApplicable && r[i].Member.IsConditional) { return true; } } return false; } private BoundExpression BindMethodGroupInvocation( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, bool allowUnexpandedForm, out bool anyApplicableCandidates) { BoundExpression result; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup( methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); diagnostics.Add(expression, useSiteInfo); anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember; if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading. if (resolution.HasAnyErrors) { ImmutableArray<MethodSymbol> originalMethods; LookupResultKind resultKind; ImmutableArray<TypeWithAnnotations> typeArguments; if (resolution.OverloadResolutionResult != null) { originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult); resultKind = resolution.MethodGroup.ResultKind; typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable(); } else { originalMethods = methodGroup.Methods; resultKind = methodGroup.ResultKind; typeArguments = methodGroup.TypeArgumentsOpt; } result = CreateBadCall( syntax, methodName, methodGroup.ReceiverOpt, originalMethods, resultKind, typeArguments, analyzedArguments, invokedAsExtensionMethod: resolution.IsExtensionMethodGroup, isDelegate: false); } else if (!resolution.IsEmpty) { // We're checking resolution.ResultKind, rather than methodGroup.HasErrors // to better handle the case where there's a problem with the receiver // (e.g. inaccessible), but the method group resolved correctly (e.g. because // it's actually an accessible static method on a base type). // CONSIDER: could check for error types amongst method group type arguments. if (resolution.ResultKind != LookupResultKind.Viable) { if (resolution.MethodGroup != null) { // we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448. result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause); } // Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting. result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { // If overload resolution found one or more applicable methods and at least one argument // was dynamic then treat this as a dynamic call. if (resolution.AnalyzedArguments.HasDynamicArgument && resolution.OverloadResolutionResult.HasAnyApplicableMember) { if (resolution.IsLocalFunctionInvocation) { result = BindLocalFunctionInvocationWithDynamicArgument( syntax, expression, methodName, methodGroup, diagnostics, queryClause, resolution); } else if (resolution.IsExtensionMethodGroup) { // error CS1973: 'T' has no applicable method named 'M' but appears to have an // extension method by that name. Extension methods cannot be dynamically dispatched. Consider // casting the dynamic arguments or calling the extension method without the extension method // syntax. // We found an extension method, so the instance associated with the method group must have // existed and had a type. Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null); Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name); result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult)) { // warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime // because one or more applicable overloads are conditional methods Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name); } // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, diagnostics); if (finalApplicableCandidates.Length > 0) { result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates, diagnostics, queryClause); } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } } } else { result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } } } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } resolution.Free(); return result; } private BoundExpression BindLocalFunctionInvocationWithDynamicArgument( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup boundMethodGroup, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, MethodGroupResolution resolution) { // Invocations of local functions with dynamic arguments don't need // to be dispatched as dynamic invocations since they cannot be // overloaded. Instead, we'll just emit a standard call with // dynamic implicit conversions for any dynamic arguments. There // are two exceptions: "params", and unconstructed generics. While // implementing those cases with dynamic invocations is possible, // we have decided the implementation complexity is not worth it. // Refer to the comments below for the exact semantics. Debug.Assert(resolution.IsLocalFunctionInvocation); Debug.Assert(resolution.OverloadResolutionResult.Succeeded); Debug.Assert(queryClause == null); var validResult = resolution.OverloadResolutionResult.ValidResult; var args = resolution.AnalyzedArguments.Arguments.ToImmutable(); var refKindsArray = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull(); ReportBadDynamicArguments(syntax, args, refKindsArray, diagnostics, queryClause); var localFunction = validResult.Member; var methodResult = validResult.Result; // We're only in trouble if a dynamic argument is passed to the // params parameter and is ambiguous at compile time between normal // and expanded form i.e., there is exactly one dynamic argument to // a params parameter // See https://github.com/dotnet/roslyn/issues/10708 if (OverloadResolution.IsValidParams(localFunction) && methodResult.Kind == MemberResolutionKind.ApplicableInNormalForm) { var parameters = localFunction.Parameters; Debug.Assert(parameters.Last().IsParams); var lastParamIndex = parameters.Length - 1; for (int i = 0; i < args.Length; ++i) { var arg = args[i]; if (arg.HasDynamicType() && methodResult.ParameterFromArgument(i) == lastParamIndex) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionParamsParameter, syntax, parameters.Last().Name, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } } } // If we call an unconstructed generic local function with a // dynamic argument in a place where it influences the type // parameters, we need to dynamically dispatch the call (as the // function must be constructed at runtime). We cannot do that, so // disallow that. However, doing a specific analysis of each // argument and its corresponding parameter to check if it's // generic (and allow dynamic in non-generic parameters) may break // overload resolution in the future, if we ever allow overloaded // local functions. So, just disallow any mixing of dynamic and // inferred generics. (Explicit generic arguments are fine) // See https://github.com/dotnet/roslyn/issues/21317 if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && localFunction.IsGenericMethod) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionTypeParameter, syntax, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } return BindInvocationExpressionContinued( node: syntax, expression: expression, methodName: methodName, result: resolution.OverloadResolutionResult, analyzedArguments: resolution.AnalyzedArguments, methodGroup: resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } private ImmutableArray<TMethodOrPropertySymbol> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>( SyntaxNode syntax, OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult, BoundExpression receiverOpt, ImmutableArray<TypeWithAnnotations> typeArgumentsOpt, BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol { Debug.Assert(overloadResolutionResult.HasAnyApplicableMember); var finalCandidates = ArrayBuilder<TMethodOrPropertySymbol>.GetInstance(); BindingDiagnosticBag firstFailed = null; var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++) { var result = overloadResolutionResult.ResultsBuilder[i]; if (result.Result.IsApplicable) { // For F to pass the check, all of the following must hold: // ... // * If the type parameters of F were substituted in the step above, their constraints are satisfied. // * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). // * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: false) && (typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics)))) { finalCandidates.Add(result.Member); continue; } if (firstFailed == null) { firstFailed = candidateDiagnostics; candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); } else { candidateDiagnostics.Clear(); } } } if (firstFailed != null) { // Report diagnostics of the first candidate that failed the validation // unless we have at least one candidate that passes. if (finalCandidates.Count == 0) { diagnostics.AddRange(firstFailed); } firstFailed.Free(); } candidateDiagnostics.Free(); return finalCandidates.ToImmutableAndFree(); } private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); // It is never legal to box a restricted type, even if we are boxing it as the receiver // of a method call. When must be box? We skip boxing when the method in question is defined // on the restricted type or overridden by the restricted type. switch (expression.Kind) { case BoundKind.Call: { var call = (BoundCall)expression; if (!call.HasAnyErrors && call.ReceiverOpt != null && (object)call.ReceiverOpt.Type != null) { // error CS0029: Cannot implicitly convert type 'A' to 'B' // Case 1: receiver is a restricted type, and method called is defined on a parent type if (call.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(call.Method.ContainingType, call.ReceiverOpt.Type, TypeCompareKind.ConsiderEverything2)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, call.ReceiverOpt.Type, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } // Case 2: receiver is a base reference, and the child type is restricted else if (call.ReceiverOpt.Kind == BoundKind.BaseReference && this.ContainingType.IsRestrictedType()) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, this.ContainingType, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } } } break; case BoundKind.DynamicInvocation: { var dynInvoke = (BoundDynamicInvocation)expression; if (!dynInvoke.HasAnyErrors && (object)dynInvoke.Expression.Type != null && dynInvoke.Expression.Type.IsRestrictedType()) { // eg: b = typedReference.Equals(dyn); // error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, dynInvoke.Expression.Syntax, dynInvoke.Expression.Type); } } break; case BoundKind.FunctionPointerInvocation: break; default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Perform overload resolution on the method group or expression (BoundMethodGroup) /// and arguments and return a BoundExpression representing the invocation. /// </summary> /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> /// <param name="methodName">Name of the invoked method.</param> /// <param name="result">Overload resolution result for method group executed by caller.</param> /// <param name="analyzedArguments">Arguments bound by the caller.</param> /// <param name="methodGroup">Method group if the invocation represents a potentially overloaded member.</param> /// <param name="delegateTypeOpt">Delegate type if method group represents a delegate.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <returns>BoundCall or error expression representing the invocation.</returns> private BoundCall BindInvocationExpressionContinued( SyntaxNode node, SyntaxNode expression, string methodName, OverloadResolutionResult<MethodSymbol> result, AnalyzedArguments analyzedArguments, MethodGroup methodGroup, NamedTypeSymbol delegateTypeOpt, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null) { Debug.Assert(node != null); Debug.Assert(methodGroup != null); Debug.Assert(methodGroup.Error == null); Debug.Assert(methodGroup.Methods.Count > 0); Debug.Assert(((object)delegateTypeOpt == null) || (methodGroup.Methods.Count == 1)); var invokedAsExtensionMethod = methodGroup.IsExtensionMethodGroup; // Delegate invocations should never be considered extension method // invocations (even though the delegate may refer to an extension method). Debug.Assert(!invokedAsExtensionMethod || ((object)delegateTypeOpt == null)); // We have already determined that we are not in a situation where we can successfully do // a dynamic binding. We might be in one of the following situations: // // * There were dynamic arguments but overload resolution still found zero applicable candidates. // * There were no dynamic arguments and overload resolution found zero applicable candidates. // * There were no dynamic arguments and overload resolution found multiple applicable candidates // without being able to find the best one. // // In those three situations we might give an additional error. if (!result.Succeeded) { if (analyzedArguments.HasErrors) { // Errors for arguments have already been reported, except for unbound lambdas and switch expressions. // We report those now. foreach (var argument in analyzedArguments.Arguments) { switch (argument) { case UnboundLambda unboundLambda: var boundWithErrors = unboundLambda.BindForErrorRecovery(); diagnostics.AddRange(boundWithErrors.Diagnostics); break; case BoundUnconvertedObjectCreationExpression _: case BoundTupleLiteral _: // Tuple literals can contain unbound lambdas or switch expressions. _ = BindToNaturalType(argument, diagnostics); break; case BoundUnconvertedSwitchExpression { Type: { } naturalType } switchExpr: _ = ConvertSwitchExpression(switchExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; case BoundUnconvertedConditionalOperator { Type: { } naturalType } conditionalExpr: _ = ConvertConditionalExpression(conditionalExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; } } } else { // Since there were no argument errors to report, we report an error on the invocation itself. string name = (object)delegateTypeOpt == null ? methodName : null; result.ReportDiagnostics( binder: this, location: GetLocationForOverloadResolutionDiagnostic(node, expression), nodeOpt: node, diagnostics: diagnostics, name: name, receiver: methodGroup.Receiver, invokedExpression: expression, arguments: analyzedArguments, memberGroup: methodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: delegateTypeOpt, queryClause: queryClause); } return CreateBadCall(node, methodGroup.Name, invokedAsExtensionMethod && analyzedArguments.Arguments.Count > 0 && (object)methodGroup.Receiver == (object)analyzedArguments.Arguments[0] ? null : methodGroup.Receiver, GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, invokedAsExtensionMethod: invokedAsExtensionMethod, isDelegate: ((object)delegateTypeOpt != null)); } // Otherwise, there were no dynamic arguments and overload resolution found a unique best candidate. // We still have to determine if it passes final validation. var methodResult = result.ValidResult; var returnType = methodResult.Member.ReturnType; var method = methodResult.Member; // It is possible that overload resolution succeeded, but we have chosen an // instance method and we're in a static method. A careful reading of the // overload resolution spec shows that the "final validation" stage allows an // "implicit this" on any method call, not just method calls from inside // instance methods. Therefore we must detect this scenario here, rather than in // overload resolution. var receiver = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !method.RequiresInstanceReceiver && !invokedAsExtensionMethod, diagnostics); var receiverRefKind = receiver?.GetRefKind(); uint receiverValEscapeScope = method.RequiresInstanceReceiver && receiver != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments(methodResult, analyzedArguments.Arguments, diagnostics, receiver?.Type, receiverRefKind, receiverValEscapeScope); var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = methodResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); // Note: we specifically want to do final validation (7.6.5.1) without checking delegate compatibility (15.2), // so we're calling MethodGroupFinalValidation directly, rather than via MethodGroupConversionHasErrors. // Note: final validation wants the receiver that corresponds to the source representation // (i.e. the first argument, if invokedAsExtensionMethod). var gotError = MemberGroupFinalValidation(receiver, method, expression, diagnostics, invokedAsExtensionMethod); CheckImplicitThisCopyInReadOnlyMember(receiver, method, diagnostics); if (invokedAsExtensionMethod) { BoundExpression receiverArgument = analyzedArguments.Argument(0); ParameterSymbol receiverParameter = method.Parameters.First(); // we will have a different receiver if ReplaceTypeOrValueReceiver has unwrapped TypeOrValue if ((object)receiver != receiverArgument) { // Because the receiver didn't pass through CoerceArguments, we need to apply an appropriate conversion here. Debug.Assert(argsToParams.IsDefault || argsToParams[0] == 0); receiverArgument = CreateConversion(receiver, methodResult.Result.ConversionForArg(0), receiverParameter.Type, diagnostics); } if (receiverParameter.RefKind == RefKind.Ref) { // If this was a ref extension method, receiverArgument must be checked for L-value constraints. // This helper method will also replace it with a BoundBadExpression if it was invalid. receiverArgument = CheckValue(receiverArgument, BindValueKind.RefOrOut, diagnostics); if (analyzedArguments.RefKinds.Count == 0) { analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count; } // receiver of a `ref` extension method is a `ref` argument. (and we have checked above that it can be passed as a Ref) // we need to adjust the argument refkind as if we had a `ref` modifier in a call. analyzedArguments.RefKinds[0] = RefKind.Ref; CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } else if (receiverParameter.RefKind == RefKind.In) { // NB: receiver of an `in` extension method is treated as a `byval` argument, so no changes from the default refkind is needed in that case. Debug.Assert(analyzedArguments.RefKind(0) == RefKind.None); CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } analyzedArguments.Arguments[0] = receiverArgument; } // This will be the receiver of the BoundCall node that we create. // For extension methods, there is no receiver because the receiver in source was actually the first argument. // For instance methods, we may have synthesized an implicit this node. We'll keep it for the emitter. // For static methods, we may have synthesized a type expression. It serves no purpose, so we'll drop it. if (invokedAsExtensionMethod || (!method.RequiresInstanceReceiver && receiver != null && receiver.WasCompilerGenerated)) { receiver = null; } var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var args = analyzedArguments.Arguments.ToImmutable(); if (!gotError && method.RequiresInstanceReceiver && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(node, diagnostics); } // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. gotError = ReportUnsafeIfNotAllowed(node, diagnostics) || gotError; } bool hasBaseReceiver = receiver != null && receiver.Kind == BoundKind.BaseReference; ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node.Location, isDelegateConversion: false); // No use site errors, but there could be use site warnings. // If there are any use site warnings, they have already been reported by overload resolution. Debug.Assert(!method.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); if (method.IsRuntimeFinalizer()) { ErrorCode code = hasBaseReceiver ? ErrorCode.ERR_CallingBaseFinalizeDeprecated : ErrorCode.ERR_CallingFinalizeDeprecated; Error(diagnostics, code, node); gotError = true; } Debug.Assert(args.IsDefaultOrEmpty || (object)receiver != (object)args[0]); if (!gotError) { gotError = !CheckInvocationArgMixing( node, method, receiver, method.Parameters, args, argsToParams, this.LocalScopeDepth, diagnostics); } bool isDelegateCall = (object)delegateTypeOpt != null; if (!isDelegateCall) { if (method.RequiresInstanceReceiver) { WarnOnAccessOfOffDefault(node.Kind() == SyntaxKind.InvocationExpression ? ((InvocationExpressionSyntax)node).Expression : node, receiver, diagnostics); } } return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall, expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, type: returnType, hasErrors: gotError); } #nullable enable private static SourceLocation GetCallerLocation(SyntaxNode syntax) { var token = syntax switch { InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken, BaseObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword, ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken, PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken, ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken, _ => syntax.GetFirstToken() }; return new SourceLocation(token); } private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics) { var parameterType = parameter.Type; Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object); // We have a call to a method M([Optional] object x) which omits the argument. The value we generate // for the argument depends on the presence or absence of other attributes. The rules are: // // * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)] // then the argument is null. // * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is // new UnknownWrapper(null) // * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is // new DispatchWrapper(null) // * Otherwise, the argument is Type.Missing. BoundExpression? defaultValue = null; if (parameter.IsMarshalAsObject) { // default(object) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else if (parameter.IsIUnknownConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new UnknownWrapper(default(object)) var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, unknownArgument) { WasCompilerGenerated = true }; } } else if (parameter.IsIDispatchConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new DispatchWrapper(default(object)) var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, dispatchArgument) { WasCompilerGenerated = true }; } } else { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol) { // Type.Missing defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; } } return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated(); } internal static ParameterSymbol? GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt, bool expanded) { int n = parameters.Length; ParameterSymbol? parameter; if (argsToParamsOpt.IsDefault) { if (argumentOrdinal < n) { parameter = parameters[argumentOrdinal]; } else if (expanded) { parameter = parameters[n - 1]; } else { parameter = null; } } else { Debug.Assert(argumentOrdinal < argsToParamsOpt.Length); int parameterOrdinal = argsToParamsOpt[argumentOrdinal]; if (parameterOrdinal < n) { parameter = parameters[parameterOrdinal]; } else { parameter = null; } } return parameter; } internal void BindDefaultArguments( SyntaxNode node, ImmutableArray<ParameterSymbol> parameters, ArrayBuilder<BoundExpression> argumentsBuilder, ArrayBuilder<RefKind>? argumentRefKindsBuilder, ref ImmutableArray<int> argsToParamsOpt, out BitVector defaultArguments, bool expanded, bool enableCallerInfo, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) { var visitedParameters = BitVector.Create(parameters.Length); for (var i = 0; i < argumentsBuilder.Count; i++) { var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded); if (parameter is not null) { visitedParameters[parameter.Ordinal] = true; } } // only proceed with binding default arguments if we know there is some parameter that has not been matched by an explicit argument if (parameters.All(static (param, visitedParameters) => visitedParameters[param.Ordinal], visitedParameters)) { defaultArguments = default; return; } // In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field. // We want to use the associated user-declared symbol instead where possible. var containingMember = ContainingMember() switch { FieldSymbol { AssociatedSymbol: { } symbol } => symbol, var c => c }; defaultArguments = BitVector.Create(parameters.Length); ArrayBuilder<int>? argsToParamsBuilder = null; if (!argsToParamsOpt.IsDefault) { argsToParamsBuilder = ArrayBuilder<int>.GetInstance(argsToParamsOpt.Length); argsToParamsBuilder.AddRange(argsToParamsOpt); } // Params methods can be invoked in normal form, so the strongest assertion we can make is that, if // we're in an expanded context, the last param must be params. The inverse is not necessarily true. Debug.Assert(!expanded || parameters[^1].IsParams); // Params array is filled in the local rewriter var lastIndex = expanded ? ^1 : ^0; var argumentsCount = argumentsBuilder.Count; // Go over missing parameters, inserting default values for optional parameters foreach (var parameter in parameters.AsSpan()[..lastIndex]) { if (!visitedParameters[parameter.Ordinal]) { Debug.Assert(parameter.IsOptional || !assertMissingParametersAreOptional); defaultArguments[argumentsBuilder.Count] = true; argumentsBuilder.Add(bindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, argumentsCount, argsToParamsOpt)); if (argumentRefKindsBuilder is { Count: > 0 }) { argumentRefKindsBuilder.Add(RefKind.None); } argsToParamsBuilder?.Add(parameter.Ordinal); } } Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count); Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count); if (argsToParamsBuilder is object) { argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull(); argsToParamsBuilder.Free(); } BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, BindingDiagnosticBag diagnostics, ArrayBuilder<BoundExpression> argumentsBuilder, int argumentsCount, ImmutableArray<int> argsToParamsOpt) { TypeSymbol parameterType = parameter.Type; if (Flags.Includes(BinderFlags.ParameterDefaultValue)) { // This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }` // We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller. return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch { // Bad default values are implicitly replaced with default(T) at call sites. { IsBad: true } => ConstantValue.Null, var constantValue => constantValue }; Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset); var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null; BoundExpression defaultValue; if (callerSourceLocation is object && parameter.IsCallerLineNumber) { int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerFilePath) { string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerMemberName) { var memberName = containingMember.GetMemberCallerName(); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt) is int argumentIndex && argumentIndex > -1 && argumentIndex < argumentsCount) { var argument = argumentsBuilder[argumentIndex]; defaultValue = new BoundLiteral(syntax, ConstantValue.Create(argument.Syntax.ToString()), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object) { // We have something like M([Optional] object x). We have special handling for such situations. defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics); } else { // The argument to M([Optional] int x) becomes default(int) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } } else if (defaultConstantValue.IsNull) { defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType); defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true }; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime }) { // Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site. // For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type // then we want to silently replace it with default(ParameterType). defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType); } var isCast = conversion.IsExplicit; defaultValue = CreateConversion( defaultValue.Syntax, defaultValue, conversion, isCast, isCast ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null, parameterType, diagnostics); } return defaultValue; static int getArgumentIndex(int parameterIndex, ImmutableArray<int> argsToParamsOpt) => argsToParamsOpt.IsDefault ? parameterIndex : argsToParamsOpt.IndexOf(parameterIndex); } } #nullable disable /// <summary> /// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member. /// </summary> internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics) { // For now we are warning only in implicit copy scenarios that are only possible with readonly members. // Eventually we will warn on implicit value copies in more scenarios. See https://github.com/dotnet/roslyn/issues/33968. if (receiver is BoundThisReference && receiver.Type.IsValueType && ContainingMemberOrLambda is MethodSymbol containingMethod && containingMethod.IsEffectivelyReadOnly && // Ignore calls to base members. TypeSymbol.Equals(containingMethod.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything) && !method.IsEffectivelyReadOnly && method.RequiresInstanceReceiver) { Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, receiver.Syntax, method, ThisParameterSymbol.SymbolName); return false; } return true; } /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression) { if (node != expression) { switch (expression.Kind()) { case SyntaxKind.QualifiedName: return ((QualifiedNameSyntax)expression).Right.GetLocation(); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)expression).Name.GetLocation(); } } return expression.GetLocation(); } /// <summary> /// Replace a BoundTypeOrValueExpression with a BoundExpression for either a type (if useType is true) /// or a value (if useType is false). Any other node is bound to its natural type. /// </summary> /// <remarks> /// Call this once overload resolution has succeeded on the method group of which the BoundTypeOrValueExpression /// is the receiver. Generally, useType will be true if the chosen method is static and false otherwise. /// </remarks> private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics) { if ((object)receiver == null) { return null; } switch (receiver.Kind) { case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; if (useType) { diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics); return typeOrValue.Data.TypeExpression; } else { diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics); return CheckValue(typeOrValue.Data.ValueExpression, BindValueKind.RValue, diagnostics); } case BoundKind.QueryClause: // a query clause may wrap a TypeOrValueExpression. var q = (BoundQueryClause)receiver; var value = q.Value; var replaced = ReplaceTypeOrValueReceiver(value, useType, diagnostics); return (value == replaced) ? q : q.Update(replaced, q.DefinedSymbol, q.Operation, q.Cast, q.Binder, q.UnoptimizedForm, q.Type); default: return BindToNaturalType(receiver, diagnostics); } } /// <summary> /// Return the delegate type if this expression represents a delegate. /// </summary> private static NamedTypeSymbol GetDelegateType(BoundExpression expr) { if ((object)expr != null && expr.Kind != BoundKind.TypeExpression) { var type = expr.Type as NamedTypeSymbol; if (((object)type != null) && type.IsDelegateType()) { return type; } } return null; } private BoundCall CreateBadCall( SyntaxNode node, string name, BoundExpression receiver, ImmutableArray<MethodSymbol> methods, LookupResultKind resultKind, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, AnalyzedArguments analyzedArguments, bool invokedAsExtensionMethod, bool isDelegate) { MethodSymbol method; ImmutableArray<BoundExpression> args; if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty) { var constructedMethods = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var m in methods) { constructedMethods.Add(m.ConstructedFrom == m && m.Arity == typeArgumentsWithAnnotations.Length ? m.Construct(typeArgumentsWithAnnotations) : m); } methods = constructedMethods.ToImmutableAndFree(); } if (methods.Length == 1 && !IsUnboundGeneric(methods[0])) { method = methods[0]; } else { var returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = (object)receiver != null && (object)receiver.Type != null ? receiver.Type : this.ContainingType; method = new ErrorMethodSymbol(methodContainer, returnType, name); } args = BuildArgumentsForErrorRecovery(analyzedArguments, methods); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); receiver = BindToTypeForErrorRecovery(receiver); return BoundCall.ErrorCall(node, receiver, method, args, argNames, argRefKinds, isDelegate, invokedAsExtensionMethod: invokedAsExtensionMethod, originalMethods: methods, resultKind: resultKind, binder: this); } private static bool IsUnboundGeneric(MethodSymbol method) { return method.IsGenericMethod && method.ConstructedFrom() == method; } // Arbitrary limit on the number of parameter lists from overload // resolution candidates considered when binding argument types. // Any additional parameter lists are ignored. internal const int MaxParameterListsForErrorRecovery = 10; private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<MethodSymbol> methods) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var m in methods) { if (!IsUnboundGeneric(m) && m.ParameterCount > 0) { parameterListList.Add(m.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<PropertySymbol> properties) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var p in properties) { if (p.ParameterCount > 0) { parameterListList.Add(p.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable<ImmutableArray<ParameterSymbol>> parameterListList) { var discardedDiagnostics = DiagnosticBag.GetInstance(); int argumentCount = analyzedArguments.Arguments.Count; ArrayBuilder<BoundExpression> newArguments = ArrayBuilder<BoundExpression>.GetInstance(argumentCount); newArguments.AddRange(analyzedArguments.Arguments); for (int i = 0; i < argumentCount; i++) { var argument = newArguments[i]; switch (argument.Kind) { case BoundKind.UnboundLambda: { // bind the argument against each applicable parameter var unboundArgument = (UnboundLambda)argument; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if (parameterType?.Kind == SymbolKind.NamedType && (object)parameterType.GetDelegateType() != null) { // Just assume we're not in an expression tree for the purposes of error recovery. var discarded = unboundArgument.Bind((NamedTypeSymbol)parameterType, isExpressionTree: false); } } // replace the unbound lambda with its best inferred bound version newArguments[i] = unboundArgument.BindForErrorRecovery(); break; } case BoundKind.OutVariablePendingInference: case BoundKind.DiscardExpression: { if (argument.HasExpressionType()) { break; } var candidateType = getCorrespondingParameterType(i); if (argument.Kind == BoundKind.OutVariablePendingInference) { if ((object)candidateType == null) { newArguments[i] = ((OutVariablePendingInference)argument).FailInference(this, null); } else { newArguments[i] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType), null); } } else if (argument.Kind == BoundKind.DiscardExpression) { if ((object)candidateType == null) { newArguments[i] = ((BoundDiscardExpression)argument).FailInference(this, null); } else { newArguments[i] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType)); } } break; } case BoundKind.OutDeconstructVarPendingInference: { newArguments[i] = ((OutDeconstructVarPendingInference)argument).FailInference(this); break; } case BoundKind.Parameter: case BoundKind.Local: { newArguments[i] = BindToTypeForErrorRecovery(argument); break; } default: { newArguments[i] = BindToTypeForErrorRecovery(argument, getCorrespondingParameterType(i)); break; } } } discardedDiagnostics.Free(); return newArguments.ToImmutableAndFree(); TypeSymbol getCorrespondingParameterType(int i) { // See if all applicable parameters have the same type TypeSymbol candidateType = null; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if ((object)parameterType != null) { if ((object)candidateType == null) { candidateType = parameterType; } else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // type mismatch candidateType = null; break; } } } return candidateType; } } /// <summary> /// Compute the type of the corresponding parameter, if any. This is used to improve error recovery, /// for bad invocations, not for semantic analysis of correct invocations, so it is a heuristic. /// If no parameter appears to correspond to the given argument, we return null. /// </summary> /// <param name="analyzedArguments">The analyzed argument list</param> /// <param name="i">The index of the argument</param> /// <param name="parameterList">The parameter list to match against</param> /// <returns>The type of the corresponding parameter.</returns> private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray<ParameterSymbol> parameterList) { string name = analyzedArguments.Name(i); if (name != null) { // look for a parameter by that name foreach (var parameter in parameterList) { if (parameter.Name == name) return parameter.Type; } return null; } return (i < parameterList.Length) ? parameterList[i].Type : null; // CONSIDER: should we handle variable argument lists? } /// <summary> /// Absent parameter types to bind the arguments, we simply use the arguments provided for error recovery. /// </summary> private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments) { return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty<ImmutableArray<ParameterSymbol>>()); } private BoundCall CreateBadCall( SyntaxNode node, BoundExpression expr, LookupResultKind resultKind, AnalyzedArguments analyzedArguments) { TypeSymbol returnType = new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = expr.Type ?? this.ContainingType; MethodSymbol method = new ErrorMethodSymbol(methodContainer, returnType, string.Empty); var args = BuildArgumentsForErrorRecovery(analyzedArguments); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var originalMethods = (expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray<MethodSymbol>.Empty; return BoundCall.ErrorCall(node, expr, method, args, argNames, argRefKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods: originalMethods, resultKind: resultKind, binder: this); } private static TypeSymbol GetCommonTypeOrReturnType<TMember>(ImmutableArray<TMember> members) where TMember : Symbol { TypeSymbol type = null; for (int i = 0, n = members.Length; i < n; i++) { TypeSymbol returnType = members[i].GetTypeOrReturnType().Type; if ((object)type == null) { type = returnType; } else if (!TypeSymbol.Equals(type, returnType, TypeCompareKind.ConsiderEverything2)) { return null; } } return type; } private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result) { result = null; if (node.Expression.Kind() != SyntaxKind.IdentifierName || ((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() != SyntaxKind.NameOfKeyword || node.ArgumentList.Arguments.Count != 1) { return false; } ArgumentSyntax argument = node.ArgumentList.Arguments[0]; if (argument.NameColon != null || argument.RefOrOutKeyword != default(SyntaxToken) || InvocableNameofInScope()) { return false; } result = BindNameofOperatorInternal(node, diagnostics); return true; } private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureNameof, diagnostics); var argument = node.ArgumentList.Arguments[0].Expression; // We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder. var nameofBinder = new NameofBinder(argument, this); var boundArgument = nameofBinder.BindExpression(argument, diagnostics); bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics); if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup) { var methodGroup = (BoundMethodGroup)boundArgument; if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) { // method group with type parameters not allowed diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); } else { nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics); } } if (boundArgument is BoundNamespaceExpression nsExpr) { diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol); } boundArgument = BindToNaturalType(boundArgument, diagnostics, reportNoTargetType: false); return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String)); } private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics) { // Check that the method group contains something applicable. Otherwise error. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(methodGroup.Syntax, useSiteInfo); diagnostics.AddRange(resolution.Diagnostics); if (resolution.IsExtensionMethodGroup) { diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location); } } /// <summary> /// Returns true if syntax form is OK (so no errors were reported) /// </summary> private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true) { switch (argument.Kind()) { case SyntaxKind.IdentifierName: { var syntax = (IdentifierNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.GenericName: { var syntax = (GenericNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.SimpleMemberAccessExpression: { var syntax = (MemberAccessExpressionSyntax)argument; bool ok = true; switch (syntax.Expression.Kind()) { case SyntaxKind.BaseExpression: case SyntaxKind.ThisExpression: break; default: ok = CheckSyntaxForNameofArgument(syntax.Expression, out name, diagnostics, false); break; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.AliasQualifiedName: { var syntax = (AliasQualifiedNameSyntax)argument; bool ok = true; if (top) { diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, argument.Location); ok = false; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.PredefinedType: name = ""; if (top) goto default; return true; default: { var code = top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof; diagnostics.Add(code, argument.Location); name = ""; return false; } } } /// <summary> /// Helper method that checks whether there is an invocable 'nameof' in scope. /// </summary> private bool InvocableNameofInScope() { var lookupResult = LookupResult.GetInstance(); const LookupOptions options = LookupOptions.AllMethodsOnArityZero | LookupOptions.MustBeInvocableIfMember; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsWithFallback(lookupResult, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), useSiteInfo: ref discardedUseSiteInfo, arity: 0, options: options); var result = lookupResult.IsMultiViable; lookupResult.Free(); return result; } #nullable enable private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(boundExpression.Type is FunctionPointerTypeSymbol); var funcPtr = (FunctionPointerTypeSymbol)boundExpression.Type; var overloadResolutionResult = OverloadResolutionResult<FunctionPointerMethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var methodsBuilder = ArrayBuilder<FunctionPointerMethodSymbol>.GetInstance(1); methodsBuilder.Add(funcPtr.Signature); OverloadResolution.FunctionPointerOverloadResolution( methodsBuilder, analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!overloadResolutionResult.Succeeded) { ImmutableArray<FunctionPointerMethodSymbol> methods = methodsBuilder.ToImmutableAndFree(); overloadResolutionResult.ReportDiagnostics( binder: this, node.Location, nodeOpt: null, diagnostics, name: null, boundExpression, boundExpression.Syntax, analyzedArguments, methods, typeContainingConstructor: null, delegateTypeBeingInvoked: null, returnRefKind: funcPtr.Signature.RefKind); return new BoundFunctionPointerInvocation( node, boundExpression, BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast<MethodSymbol>.From(methods)), analyzedArguments.RefKinds.ToImmutableOrNull(), LookupResultKind.OverloadResolutionFailure, funcPtr.Signature.ReturnType, hasErrors: true); } methodsBuilder.Free(); MemberResolutionResult<FunctionPointerMethodSymbol> methodResult = overloadResolutionResult.ValidResult; CoerceArguments( methodResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); var args = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( node, funcPtr.Signature, receiverOpt: null, funcPtr.Signature.Parameters, args, methodResult.Result.ArgsToParamsOpt, LocalScopeDepth, diagnostics); } return new BoundFunctionPointerInvocation( node, boundExpression, args, refKinds, LookupResultKind.Viable, funcPtr.Signature.ReturnType, 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ParenthesizedExpression: return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics); default: return BindExpression(node, diagnostics, invoked, indexed); } } private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult) { // If overload resolution has failed then we want to stash away the original methods that we // considered so that the IDE can display tooltips or other information about them. // However, if a method group contained a generic method that was type inferred then // the IDE wants information about the *inferred* method, not the original unconstructed // generic method. if (overloadResolutionResult == null) { return ImmutableArray<MethodSymbol>.Empty; } var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var result in overloadResolutionResult.Results) { builder.Add(result.Member); } return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Helper method to create a synthesized method invocation expression. /// </summary> /// <param name="node">Syntax Node.</param> /// <param name="receiver">Receiver for the method call.</param> /// <param name="methodName">Method to be invoked on the receiver.</param> /// <param name="args">Arguments to the method call.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="typeArgsSyntax">Optional type arguments syntax.</param> /// <param name="typeArgs">Optional type arguments.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param> /// <param name="allowUnexpandedForm">False to prevent selecting a params method in unexpanded form.</param> /// <returns>Synthesized method invocation expression.</returns> internal BoundExpression MakeInvocationExpression( SyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray<BoundExpression> args, BindingDiagnosticBag diagnostics, SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>), ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>), ImmutableArray<(string Name, Location Location)?> names = default, CSharpSyntaxNode? queryClause = null, bool allowFieldsAndProperties = false, bool allowUnexpandedForm = true, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(receiver != null); Debug.Assert(names.IsDefault || names.Length == args.Length); receiver = BindToNaturalType(receiver, diagnostics); var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary); // The other consumers of this helper (await and collection initializers) require the target member to be a method. if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess)) { Symbol symbol; MessageID msgId; if (boundExpression.Kind == BoundKind.FieldAccess) { msgId = MessageID.IDS_SK_FIELD; symbol = ((BoundFieldAccess)boundExpression).FieldSymbol; } else { msgId = MessageID.IDS_SK_PROPERTY; symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol; } diagnostics.Add( ErrorCode.ERR_BadSKknown, node.Location, methodName, msgId.Localize(), MessageID.IDS_SK_METHOD.Localize()); return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true); } boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); boundExpression.WasCompilerGenerated = true; var analyzedArguments = AnalyzedArguments.GetInstance(); Debug.Assert(!args.Any(e => e.Kind == BoundKind.OutVariablePendingInference || e.Kind == BoundKind.OutDeconstructVarPendingInference || e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType())); analyzedArguments.Arguments.AddRange(args); if (!names.IsDefault) { analyzedArguments.Names.AddRange(names); } BoundExpression result = BindInvocationExpression( node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm); // Query operator can't be called dynamically. if (queryClause != null && result.Kind == BoundKind.DynamicInvocation) { // the error has already been reported by BindInvocationExpression Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result.WasCompilerGenerated = true; analyzedArguments.Free(); return result; } #nullable disable /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression result; if (TryBindNameofOperator(node, diagnostics, out result)) { return result; // all of the binding is done by BindNameofOperator } // M(__arglist()) is legal, but M(__arglist(__arglist()) is not! bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression; AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); if (isArglist) { BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false); result = BindArgListOperator(node, diagnostics, analyzedArguments); } else { BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics); boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null; BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); result = BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics); } analyzedArguments.Free(); return result; } private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments) { bool hasErrors = analyzedArguments.HasErrors; // We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them. TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node); for (int i = 0; i < analyzedArguments.Arguments.Count; ++i) { BoundExpression argument = analyzedArguments.Arguments[i]; if (argument.Kind == BoundKind.OutVariablePendingInference) { analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics); } else if ((object)argument.Type == null && !argument.HasAnyErrors) { // We are going to need every argument in here to have a type. If we don't have one, // try converting it to object. We'll either succeed (if it is a null literal) // or fail with a good error message. // // Note that the native compiler converts null literals to object, and for everything // else it either crashes, or produces nonsense code. Roslyn improves upon this considerably. analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics); } else if (argument.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax); hasErrors = true; } else if (analyzedArguments.RefKind(i) == RefKind.None) { analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics); } switch (analyzedArguments.RefKind(i)) { case RefKind.None: case RefKind.Ref: break; default: // Disallow "in" or "out" arguments Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax); hasErrors = true; break; } } ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable(); ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors); } /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null, bool allowUnexpandedForm = true) { BoundExpression result; NamedTypeSymbol delegateType; if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic()) { // Either we have a dynamic method group invocation "dyn.M(...)" or // a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic // invocation and let the lowering pass sort it out. ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause); } else if (boundExpression.Kind == BoundKind.MethodGroup) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindMethodGroupInvocation( node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm, anyApplicableCandidates: out _); } else if ((object)(delegateType = GetDelegateType(boundExpression)) != null) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node)) { return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType); } else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics); } else { if (!boundExpression.HasAnyErrors) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location); } result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments); } CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics); return result; } private BoundExpression BindDynamicInvocation( SyntaxNode node, BoundExpression expression, AnalyzedArguments arguments, ImmutableArray<MethodSymbol> applicableMethods, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics); bool hasErrors = false; if (expression.Kind == BoundKind.MethodGroup) { BoundMethodGroup methodGroup = (BoundMethodGroup)expression; BoundExpression receiver = methodGroup.ReceiverOpt; // receiver is null if we are calling a static method declared on an outer class via its simple name: if (receiver != null) { switch (receiver.Kind) { case BoundKind.BaseReference: Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name); hasErrors = true; break; case BoundKind.ThisReference: // Can't call the HasThis method due to EE doing odd things with containing member and its containing type. if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated) { // Only a static method can be called in a constructor initializer. If we were not in a ctor initializer // the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before // the base constructor is called. We need to handle this as a type qualified static method call. // Also applicable to things like field initializers, which run before the ctor initializer. expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver, receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(), resultKind: methodGroup.ResultKind); } break; case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags, finalReceiver, methodGroup.ResultKind); break; } } } else { expression = BindToNaturalType(expression, diagnostics); } ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause); return new BoundDynamicInvocation( node, arguments.GetNames(), refKindsArray, applicableMethods, expression, argArray, type: Compilation.DynamicType, hasErrors: hasErrors); } private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { if (arguments.Names.Count == 0) { return; } if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { return; } bool seenName = false; for (int i = 0; i < arguments.Names.Count; i++) { if (arguments.Names[i] != null) { seenName = true; } else if (seenName) { Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax); return; } } } private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count); builder.AddRange(arguments.Arguments); for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = builder[i] switch { OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics), BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics), var arg => BindToNaturalType(arg, diagnostics) }; } return builder.ToImmutableAndFree(); } // Returns true if there were errors. private static bool ReportBadDynamicArguments( SyntaxNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKinds, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { bool hasErrors = false; bool reportedBadQuery = false; if (!refKinds.IsDefault) { for (int argIndex = 0; argIndex < refKinds.Length; argIndex++) { if (refKinds[argIndex] == RefKind.In) { Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax); hasErrors = true; } } } foreach (var arg in arguments) { if (!IsLegalDynamicOperand(arg)) { if (queryClause != null && !reportedBadQuery) { reportedBadQuery = true; Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node); hasErrors = true; continue; } if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda) { // Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.MethodGroup) { // Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.ArgListOperator) { // Not a great error message, since __arglist is not a type, but it'll do. // error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist"); } else { // Lambdas,anonymous methods and method groups are the typeless expressions that // are not usable as dynamic arguments; if we get here then the expression must have a type. Debug.Assert((object)arg.Type != null); // error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type); hasErrors = true; } } } return hasErrors; } private BoundExpression BindDelegateInvocation( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, NamedTypeSymbol delegateType) { BoundExpression result; var methodGroup = MethodGroup.GetInstance(); methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod); var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: analyzedArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments // was dynamic then treat this as a dynamic call. if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } else { result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause); } overloadResolutionResult.Free(); methodGroup.Free(); return result; } private static bool HasApplicableConditionalMethod(OverloadResolutionResult<MethodSymbol> results) { var r = results.Results; for (int i = 0; i < r.Length; ++i) { if (r[i].IsApplicable && r[i].Member.IsConditional) { return true; } } return false; } private BoundExpression BindMethodGroupInvocation( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, bool allowUnexpandedForm, out bool anyApplicableCandidates) { BoundExpression result; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup( methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); diagnostics.Add(expression, useSiteInfo); anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember; if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading. if (resolution.HasAnyErrors) { ImmutableArray<MethodSymbol> originalMethods; LookupResultKind resultKind; ImmutableArray<TypeWithAnnotations> typeArguments; if (resolution.OverloadResolutionResult != null) { originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult); resultKind = resolution.MethodGroup.ResultKind; typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable(); } else { originalMethods = methodGroup.Methods; resultKind = methodGroup.ResultKind; typeArguments = methodGroup.TypeArgumentsOpt; } result = CreateBadCall( syntax, methodName, methodGroup.ReceiverOpt, originalMethods, resultKind, typeArguments, analyzedArguments, invokedAsExtensionMethod: resolution.IsExtensionMethodGroup, isDelegate: false); } else if (!resolution.IsEmpty) { // We're checking resolution.ResultKind, rather than methodGroup.HasErrors // to better handle the case where there's a problem with the receiver // (e.g. inaccessible), but the method group resolved correctly (e.g. because // it's actually an accessible static method on a base type). // CONSIDER: could check for error types amongst method group type arguments. if (resolution.ResultKind != LookupResultKind.Viable) { if (resolution.MethodGroup != null) { // we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448. result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause); } // Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting. result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { // If overload resolution found one or more applicable methods and at least one argument // was dynamic then treat this as a dynamic call. if (resolution.AnalyzedArguments.HasDynamicArgument && resolution.OverloadResolutionResult.HasAnyApplicableMember) { if (resolution.IsLocalFunctionInvocation) { result = BindLocalFunctionInvocationWithDynamicArgument( syntax, expression, methodName, methodGroup, diagnostics, queryClause, resolution); } else if (resolution.IsExtensionMethodGroup) { // error CS1973: 'T' has no applicable method named 'M' but appears to have an // extension method by that name. Extension methods cannot be dynamically dispatched. Consider // casting the dynamic arguments or calling the extension method without the extension method // syntax. // We found an extension method, so the instance associated with the method group must have // existed and had a type. Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null); Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name); result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult)) { // warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime // because one or more applicable overloads are conditional methods Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name); } // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, diagnostics); if (finalApplicableCandidates.Length > 0) { result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates, diagnostics, queryClause); } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } } } else { result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } } } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } resolution.Free(); return result; } private BoundExpression BindLocalFunctionInvocationWithDynamicArgument( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup boundMethodGroup, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, MethodGroupResolution resolution) { // Invocations of local functions with dynamic arguments don't need // to be dispatched as dynamic invocations since they cannot be // overloaded. Instead, we'll just emit a standard call with // dynamic implicit conversions for any dynamic arguments. There // are two exceptions: "params", and unconstructed generics. While // implementing those cases with dynamic invocations is possible, // we have decided the implementation complexity is not worth it. // Refer to the comments below for the exact semantics. Debug.Assert(resolution.IsLocalFunctionInvocation); Debug.Assert(resolution.OverloadResolutionResult.Succeeded); Debug.Assert(queryClause == null); var validResult = resolution.OverloadResolutionResult.ValidResult; var args = resolution.AnalyzedArguments.Arguments.ToImmutable(); var refKindsArray = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull(); ReportBadDynamicArguments(syntax, args, refKindsArray, diagnostics, queryClause); var localFunction = validResult.Member; var methodResult = validResult.Result; // We're only in trouble if a dynamic argument is passed to the // params parameter and is ambiguous at compile time between normal // and expanded form i.e., there is exactly one dynamic argument to // a params parameter // See https://github.com/dotnet/roslyn/issues/10708 if (OverloadResolution.IsValidParams(localFunction) && methodResult.Kind == MemberResolutionKind.ApplicableInNormalForm) { var parameters = localFunction.Parameters; Debug.Assert(parameters.Last().IsParams); var lastParamIndex = parameters.Length - 1; for (int i = 0; i < args.Length; ++i) { var arg = args[i]; if (arg.HasDynamicType() && methodResult.ParameterFromArgument(i) == lastParamIndex) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionParamsParameter, syntax, parameters.Last().Name, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } } } // If we call an unconstructed generic local function with a // dynamic argument in a place where it influences the type // parameters, we need to dynamically dispatch the call (as the // function must be constructed at runtime). We cannot do that, so // disallow that. However, doing a specific analysis of each // argument and its corresponding parameter to check if it's // generic (and allow dynamic in non-generic parameters) may break // overload resolution in the future, if we ever allow overloaded // local functions. So, just disallow any mixing of dynamic and // inferred generics. (Explicit generic arguments are fine) // See https://github.com/dotnet/roslyn/issues/21317 if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && localFunction.IsGenericMethod) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionTypeParameter, syntax, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } return BindInvocationExpressionContinued( node: syntax, expression: expression, methodName: methodName, result: resolution.OverloadResolutionResult, analyzedArguments: resolution.AnalyzedArguments, methodGroup: resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } private ImmutableArray<TMethodOrPropertySymbol> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>( SyntaxNode syntax, OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult, BoundExpression receiverOpt, ImmutableArray<TypeWithAnnotations> typeArgumentsOpt, BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol { Debug.Assert(overloadResolutionResult.HasAnyApplicableMember); var finalCandidates = ArrayBuilder<TMethodOrPropertySymbol>.GetInstance(); BindingDiagnosticBag firstFailed = null; var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++) { var result = overloadResolutionResult.ResultsBuilder[i]; if (result.Result.IsApplicable) { // For F to pass the check, all of the following must hold: // ... // * If the type parameters of F were substituted in the step above, their constraints are satisfied. // * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). // * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: false) && (typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics)))) { finalCandidates.Add(result.Member); continue; } if (firstFailed == null) { firstFailed = candidateDiagnostics; candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); } else { candidateDiagnostics.Clear(); } } } if (firstFailed != null) { // Report diagnostics of the first candidate that failed the validation // unless we have at least one candidate that passes. if (finalCandidates.Count == 0) { diagnostics.AddRange(firstFailed); } firstFailed.Free(); } candidateDiagnostics.Free(); return finalCandidates.ToImmutableAndFree(); } private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); // It is never legal to box a restricted type, even if we are boxing it as the receiver // of a method call. When must be box? We skip boxing when the method in question is defined // on the restricted type or overridden by the restricted type. switch (expression.Kind) { case BoundKind.Call: { var call = (BoundCall)expression; if (!call.HasAnyErrors && call.ReceiverOpt != null && (object)call.ReceiverOpt.Type != null) { // error CS0029: Cannot implicitly convert type 'A' to 'B' // Case 1: receiver is a restricted type, and method called is defined on a parent type if (call.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(call.Method.ContainingType, call.ReceiverOpt.Type, TypeCompareKind.ConsiderEverything2)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, call.ReceiverOpt.Type, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } // Case 2: receiver is a base reference, and the child type is restricted else if (call.ReceiverOpt.Kind == BoundKind.BaseReference && this.ContainingType.IsRestrictedType()) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, this.ContainingType, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } } } break; case BoundKind.DynamicInvocation: { var dynInvoke = (BoundDynamicInvocation)expression; if (!dynInvoke.HasAnyErrors && (object)dynInvoke.Expression.Type != null && dynInvoke.Expression.Type.IsRestrictedType()) { // eg: b = typedReference.Equals(dyn); // error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, dynInvoke.Expression.Syntax, dynInvoke.Expression.Type); } } break; case BoundKind.FunctionPointerInvocation: break; default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Perform overload resolution on the method group or expression (BoundMethodGroup) /// and arguments and return a BoundExpression representing the invocation. /// </summary> /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> /// <param name="methodName">Name of the invoked method.</param> /// <param name="result">Overload resolution result for method group executed by caller.</param> /// <param name="analyzedArguments">Arguments bound by the caller.</param> /// <param name="methodGroup">Method group if the invocation represents a potentially overloaded member.</param> /// <param name="delegateTypeOpt">Delegate type if method group represents a delegate.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <returns>BoundCall or error expression representing the invocation.</returns> private BoundCall BindInvocationExpressionContinued( SyntaxNode node, SyntaxNode expression, string methodName, OverloadResolutionResult<MethodSymbol> result, AnalyzedArguments analyzedArguments, MethodGroup methodGroup, NamedTypeSymbol delegateTypeOpt, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null) { Debug.Assert(node != null); Debug.Assert(methodGroup != null); Debug.Assert(methodGroup.Error == null); Debug.Assert(methodGroup.Methods.Count > 0); Debug.Assert(((object)delegateTypeOpt == null) || (methodGroup.Methods.Count == 1)); var invokedAsExtensionMethod = methodGroup.IsExtensionMethodGroup; // Delegate invocations should never be considered extension method // invocations (even though the delegate may refer to an extension method). Debug.Assert(!invokedAsExtensionMethod || ((object)delegateTypeOpt == null)); // We have already determined that we are not in a situation where we can successfully do // a dynamic binding. We might be in one of the following situations: // // * There were dynamic arguments but overload resolution still found zero applicable candidates. // * There were no dynamic arguments and overload resolution found zero applicable candidates. // * There were no dynamic arguments and overload resolution found multiple applicable candidates // without being able to find the best one. // // In those three situations we might give an additional error. if (!result.Succeeded) { if (analyzedArguments.HasErrors) { // Errors for arguments have already been reported, except for unbound lambdas and switch expressions. // We report those now. foreach (var argument in analyzedArguments.Arguments) { switch (argument) { case UnboundLambda unboundLambda: var boundWithErrors = unboundLambda.BindForErrorRecovery(); diagnostics.AddRange(boundWithErrors.Diagnostics); break; case BoundUnconvertedObjectCreationExpression _: case BoundTupleLiteral _: // Tuple literals can contain unbound lambdas or switch expressions. _ = BindToNaturalType(argument, diagnostics); break; case BoundUnconvertedSwitchExpression { Type: { } naturalType } switchExpr: _ = ConvertSwitchExpression(switchExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; case BoundUnconvertedConditionalOperator { Type: { } naturalType } conditionalExpr: _ = ConvertConditionalExpression(conditionalExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; } } } else { // Since there were no argument errors to report, we report an error on the invocation itself. string name = (object)delegateTypeOpt == null ? methodName : null; result.ReportDiagnostics( binder: this, location: GetLocationForOverloadResolutionDiagnostic(node, expression), nodeOpt: node, diagnostics: diagnostics, name: name, receiver: methodGroup.Receiver, invokedExpression: expression, arguments: analyzedArguments, memberGroup: methodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: delegateTypeOpt, queryClause: queryClause); } return CreateBadCall(node, methodGroup.Name, invokedAsExtensionMethod && analyzedArguments.Arguments.Count > 0 && (object)methodGroup.Receiver == (object)analyzedArguments.Arguments[0] ? null : methodGroup.Receiver, GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, invokedAsExtensionMethod: invokedAsExtensionMethod, isDelegate: ((object)delegateTypeOpt != null)); } // Otherwise, there were no dynamic arguments and overload resolution found a unique best candidate. // We still have to determine if it passes final validation. var methodResult = result.ValidResult; var returnType = methodResult.Member.ReturnType; var method = methodResult.Member; // It is possible that overload resolution succeeded, but we have chosen an // instance method and we're in a static method. A careful reading of the // overload resolution spec shows that the "final validation" stage allows an // "implicit this" on any method call, not just method calls from inside // instance methods. Therefore we must detect this scenario here, rather than in // overload resolution. var receiver = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !method.RequiresInstanceReceiver && !invokedAsExtensionMethod, diagnostics); var receiverRefKind = receiver?.GetRefKind(); uint receiverValEscapeScope = method.RequiresInstanceReceiver && receiver != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments(methodResult, analyzedArguments.Arguments, diagnostics, receiver?.Type, receiverRefKind, receiverValEscapeScope); var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = methodResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); // Note: we specifically want to do final validation (7.6.5.1) without checking delegate compatibility (15.2), // so we're calling MethodGroupFinalValidation directly, rather than via MethodGroupConversionHasErrors. // Note: final validation wants the receiver that corresponds to the source representation // (i.e. the first argument, if invokedAsExtensionMethod). var gotError = MemberGroupFinalValidation(receiver, method, expression, diagnostics, invokedAsExtensionMethod); CheckImplicitThisCopyInReadOnlyMember(receiver, method, diagnostics); if (invokedAsExtensionMethod) { BoundExpression receiverArgument = analyzedArguments.Argument(0); ParameterSymbol receiverParameter = method.Parameters.First(); // we will have a different receiver if ReplaceTypeOrValueReceiver has unwrapped TypeOrValue if ((object)receiver != receiverArgument) { // Because the receiver didn't pass through CoerceArguments, we need to apply an appropriate conversion here. Debug.Assert(argsToParams.IsDefault || argsToParams[0] == 0); receiverArgument = CreateConversion(receiver, methodResult.Result.ConversionForArg(0), receiverParameter.Type, diagnostics); } if (receiverParameter.RefKind == RefKind.Ref) { // If this was a ref extension method, receiverArgument must be checked for L-value constraints. // This helper method will also replace it with a BoundBadExpression if it was invalid. receiverArgument = CheckValue(receiverArgument, BindValueKind.RefOrOut, diagnostics); if (analyzedArguments.RefKinds.Count == 0) { analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count; } // receiver of a `ref` extension method is a `ref` argument. (and we have checked above that it can be passed as a Ref) // we need to adjust the argument refkind as if we had a `ref` modifier in a call. analyzedArguments.RefKinds[0] = RefKind.Ref; CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } else if (receiverParameter.RefKind == RefKind.In) { // NB: receiver of an `in` extension method is treated as a `byval` argument, so no changes from the default refkind is needed in that case. Debug.Assert(analyzedArguments.RefKind(0) == RefKind.None); CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } analyzedArguments.Arguments[0] = receiverArgument; } // This will be the receiver of the BoundCall node that we create. // For extension methods, there is no receiver because the receiver in source was actually the first argument. // For instance methods, we may have synthesized an implicit this node. We'll keep it for the emitter. // For static methods, we may have synthesized a type expression. It serves no purpose, so we'll drop it. if (invokedAsExtensionMethod || (!method.RequiresInstanceReceiver && receiver != null && receiver.WasCompilerGenerated)) { receiver = null; } var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var args = analyzedArguments.Arguments.ToImmutable(); if (!gotError && method.RequiresInstanceReceiver && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(node, diagnostics); } // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. gotError = ReportUnsafeIfNotAllowed(node, diagnostics) || gotError; } bool hasBaseReceiver = receiver != null && receiver.Kind == BoundKind.BaseReference; ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node.Location, isDelegateConversion: false); // No use site errors, but there could be use site warnings. // If there are any use site warnings, they have already been reported by overload resolution. Debug.Assert(!method.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); if (method.IsRuntimeFinalizer()) { ErrorCode code = hasBaseReceiver ? ErrorCode.ERR_CallingBaseFinalizeDeprecated : ErrorCode.ERR_CallingFinalizeDeprecated; Error(diagnostics, code, node); gotError = true; } Debug.Assert(args.IsDefaultOrEmpty || (object)receiver != (object)args[0]); if (!gotError) { gotError = !CheckInvocationArgMixing( node, method, receiver, method.Parameters, args, argsToParams, this.LocalScopeDepth, diagnostics); } bool isDelegateCall = (object)delegateTypeOpt != null; if (!isDelegateCall) { if (method.RequiresInstanceReceiver) { WarnOnAccessOfOffDefault(node.Kind() == SyntaxKind.InvocationExpression ? ((InvocationExpressionSyntax)node).Expression : node, receiver, diagnostics); } } return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall, expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, type: returnType, hasErrors: gotError); } #nullable enable private static SourceLocation GetCallerLocation(SyntaxNode syntax) { var token = syntax switch { InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken, BaseObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword, ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken, PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken, ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken, _ => syntax.GetFirstToken() }; return new SourceLocation(token); } private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics) { var parameterType = parameter.Type; Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object); // We have a call to a method M([Optional] object x) which omits the argument. The value we generate // for the argument depends on the presence or absence of other attributes. The rules are: // // * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)] // then the argument is null. // * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is // new UnknownWrapper(null) // * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is // new DispatchWrapper(null) // * Otherwise, the argument is Type.Missing. BoundExpression? defaultValue = null; if (parameter.IsMarshalAsObject) { // default(object) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else if (parameter.IsIUnknownConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new UnknownWrapper(default(object)) var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, unknownArgument) { WasCompilerGenerated = true }; } } else if (parameter.IsIDispatchConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new DispatchWrapper(default(object)) var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, dispatchArgument) { WasCompilerGenerated = true }; } } else { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol) { // Type.Missing defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; } } return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated(); } internal static ParameterSymbol? GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt, bool expanded) { int n = parameters.Length; ParameterSymbol? parameter; if (argsToParamsOpt.IsDefault) { if (argumentOrdinal < n) { parameter = parameters[argumentOrdinal]; } else if (expanded) { parameter = parameters[n - 1]; } else { parameter = null; } } else { Debug.Assert(argumentOrdinal < argsToParamsOpt.Length); int parameterOrdinal = argsToParamsOpt[argumentOrdinal]; if (parameterOrdinal < n) { parameter = parameters[parameterOrdinal]; } else { parameter = null; } } return parameter; } internal void BindDefaultArguments( SyntaxNode node, ImmutableArray<ParameterSymbol> parameters, ArrayBuilder<BoundExpression> argumentsBuilder, ArrayBuilder<RefKind>? argumentRefKindsBuilder, ref ImmutableArray<int> argsToParamsOpt, out BitVector defaultArguments, bool expanded, bool enableCallerInfo, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) { var visitedParameters = BitVector.Create(parameters.Length); for (var i = 0; i < argumentsBuilder.Count; i++) { var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded); if (parameter is not null) { visitedParameters[parameter.Ordinal] = true; } } // only proceed with binding default arguments if we know there is some parameter that has not been matched by an explicit argument if (parameters.All(static (param, visitedParameters) => visitedParameters[param.Ordinal], visitedParameters)) { defaultArguments = default; return; } // In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field. // We want to use the associated user-declared symbol instead where possible. var containingMember = ContainingMember() switch { FieldSymbol { AssociatedSymbol: { } symbol } => symbol, var c => c }; defaultArguments = BitVector.Create(parameters.Length); ArrayBuilder<int>? argsToParamsBuilder = null; if (!argsToParamsOpt.IsDefault) { argsToParamsBuilder = ArrayBuilder<int>.GetInstance(argsToParamsOpt.Length); argsToParamsBuilder.AddRange(argsToParamsOpt); } // Params methods can be invoked in normal form, so the strongest assertion we can make is that, if // we're in an expanded context, the last param must be params. The inverse is not necessarily true. Debug.Assert(!expanded || parameters[^1].IsParams); // Params array is filled in the local rewriter var lastIndex = expanded ? ^1 : ^0; var argumentsCount = argumentsBuilder.Count; // Go over missing parameters, inserting default values for optional parameters foreach (var parameter in parameters.AsSpan()[..lastIndex]) { if (!visitedParameters[parameter.Ordinal]) { Debug.Assert(parameter.IsOptional || !assertMissingParametersAreOptional); defaultArguments[argumentsBuilder.Count] = true; argumentsBuilder.Add(bindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, argumentsCount, argsToParamsOpt)); if (argumentRefKindsBuilder is { Count: > 0 }) { argumentRefKindsBuilder.Add(RefKind.None); } argsToParamsBuilder?.Add(parameter.Ordinal); } } Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count); Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count); if (argsToParamsBuilder is object) { argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull(); argsToParamsBuilder.Free(); } BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, BindingDiagnosticBag diagnostics, ArrayBuilder<BoundExpression> argumentsBuilder, int argumentsCount, ImmutableArray<int> argsToParamsOpt) { TypeSymbol parameterType = parameter.Type; if (Flags.Includes(BinderFlags.ParameterDefaultValue)) { // This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }` // We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller. return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch { // Bad default values are implicitly replaced with default(T) at call sites. { IsBad: true } => ConstantValue.Null, var constantValue => constantValue }; Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset); var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null; BoundExpression defaultValue; if (callerSourceLocation is object && parameter.IsCallerLineNumber) { int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerFilePath) { string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerMemberName) { var memberName = containingMember.GetMemberCallerName(); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt) is int argumentIndex && argumentIndex > -1 && argumentIndex < argumentsCount) { var argument = argumentsBuilder[argumentIndex]; defaultValue = new BoundLiteral(syntax, ConstantValue.Create(argument.Syntax.ToString()), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object) { // We have something like M([Optional] object x). We have special handling for such situations. defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics); } else { // The argument to M([Optional] int x) becomes default(int) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } } else if (defaultConstantValue.IsNull) { defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType); defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true }; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime }) { // Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site. // For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type // then we want to silently replace it with default(ParameterType). defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType); } var isCast = conversion.IsExplicit; defaultValue = CreateConversion( defaultValue.Syntax, defaultValue, conversion, isCast, isCast ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null, parameterType, diagnostics); } return defaultValue; static int getArgumentIndex(int parameterIndex, ImmutableArray<int> argsToParamsOpt) => argsToParamsOpt.IsDefault ? parameterIndex : argsToParamsOpt.IndexOf(parameterIndex); } } #nullable disable /// <summary> /// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member. /// </summary> internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics) { // For now we are warning only in implicit copy scenarios that are only possible with readonly members. // Eventually we will warn on implicit value copies in more scenarios. See https://github.com/dotnet/roslyn/issues/33968. if (receiver is BoundThisReference && receiver.Type.IsValueType && ContainingMemberOrLambda is MethodSymbol containingMethod && containingMethod.IsEffectivelyReadOnly && // Ignore calls to base members. TypeSymbol.Equals(containingMethod.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything) && !method.IsEffectivelyReadOnly && method.RequiresInstanceReceiver) { Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, receiver.Syntax, method, ThisParameterSymbol.SymbolName); return false; } return true; } /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression) { if (node != expression) { switch (expression.Kind()) { case SyntaxKind.QualifiedName: return ((QualifiedNameSyntax)expression).Right.GetLocation(); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)expression).Name.GetLocation(); } } return expression.GetLocation(); } /// <summary> /// Replace a BoundTypeOrValueExpression with a BoundExpression for either a type (if useType is true) /// or a value (if useType is false). Any other node is bound to its natural type. /// </summary> /// <remarks> /// Call this once overload resolution has succeeded on the method group of which the BoundTypeOrValueExpression /// is the receiver. Generally, useType will be true if the chosen method is static and false otherwise. /// </remarks> private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics) { if ((object)receiver == null) { return null; } switch (receiver.Kind) { case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; if (useType) { diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics); return typeOrValue.Data.TypeExpression; } else { diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics); return CheckValue(typeOrValue.Data.ValueExpression, BindValueKind.RValue, diagnostics); } case BoundKind.QueryClause: // a query clause may wrap a TypeOrValueExpression. var q = (BoundQueryClause)receiver; var value = q.Value; var replaced = ReplaceTypeOrValueReceiver(value, useType, diagnostics); return (value == replaced) ? q : q.Update(replaced, q.DefinedSymbol, q.Operation, q.Cast, q.Binder, q.UnoptimizedForm, q.Type); default: return BindToNaturalType(receiver, diagnostics); } } /// <summary> /// Return the delegate type if this expression represents a delegate. /// </summary> private static NamedTypeSymbol GetDelegateType(BoundExpression expr) { if ((object)expr != null && expr.Kind != BoundKind.TypeExpression) { var type = expr.Type as NamedTypeSymbol; if (((object)type != null) && type.IsDelegateType()) { return type; } } return null; } private BoundCall CreateBadCall( SyntaxNode node, string name, BoundExpression receiver, ImmutableArray<MethodSymbol> methods, LookupResultKind resultKind, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, AnalyzedArguments analyzedArguments, bool invokedAsExtensionMethod, bool isDelegate) { MethodSymbol method; ImmutableArray<BoundExpression> args; if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty) { var constructedMethods = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var m in methods) { constructedMethods.Add(m.ConstructedFrom == m && m.Arity == typeArgumentsWithAnnotations.Length ? m.Construct(typeArgumentsWithAnnotations) : m); } methods = constructedMethods.ToImmutableAndFree(); } if (methods.Length == 1 && !IsUnboundGeneric(methods[0])) { method = methods[0]; } else { var returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = (object)receiver != null && (object)receiver.Type != null ? receiver.Type : this.ContainingType; method = new ErrorMethodSymbol(methodContainer, returnType, name); } args = BuildArgumentsForErrorRecovery(analyzedArguments, methods); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); receiver = BindToTypeForErrorRecovery(receiver); return BoundCall.ErrorCall(node, receiver, method, args, argNames, argRefKinds, isDelegate, invokedAsExtensionMethod: invokedAsExtensionMethod, originalMethods: methods, resultKind: resultKind, binder: this); } private static bool IsUnboundGeneric(MethodSymbol method) { return method.IsGenericMethod && method.ConstructedFrom() == method; } // Arbitrary limit on the number of parameter lists from overload // resolution candidates considered when binding argument types. // Any additional parameter lists are ignored. internal const int MaxParameterListsForErrorRecovery = 10; private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<MethodSymbol> methods) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var m in methods) { if (!IsUnboundGeneric(m) && m.ParameterCount > 0) { parameterListList.Add(m.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<PropertySymbol> properties) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var p in properties) { if (p.ParameterCount > 0) { parameterListList.Add(p.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable<ImmutableArray<ParameterSymbol>> parameterListList) { var discardedDiagnostics = DiagnosticBag.GetInstance(); int argumentCount = analyzedArguments.Arguments.Count; ArrayBuilder<BoundExpression> newArguments = ArrayBuilder<BoundExpression>.GetInstance(argumentCount); newArguments.AddRange(analyzedArguments.Arguments); for (int i = 0; i < argumentCount; i++) { var argument = newArguments[i]; switch (argument.Kind) { case BoundKind.UnboundLambda: { // bind the argument against each applicable parameter var unboundArgument = (UnboundLambda)argument; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if (parameterType?.Kind == SymbolKind.NamedType && (object)parameterType.GetDelegateType() != null) { // Just assume we're not in an expression tree for the purposes of error recovery. var discarded = unboundArgument.Bind((NamedTypeSymbol)parameterType, isExpressionTree: false); } } // replace the unbound lambda with its best inferred bound version newArguments[i] = unboundArgument.BindForErrorRecovery(); break; } case BoundKind.OutVariablePendingInference: case BoundKind.DiscardExpression: { if (argument.HasExpressionType()) { break; } var candidateType = getCorrespondingParameterType(i); if (argument.Kind == BoundKind.OutVariablePendingInference) { if ((object)candidateType == null) { newArguments[i] = ((OutVariablePendingInference)argument).FailInference(this, null); } else { newArguments[i] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType), null); } } else if (argument.Kind == BoundKind.DiscardExpression) { if ((object)candidateType == null) { newArguments[i] = ((BoundDiscardExpression)argument).FailInference(this, null); } else { newArguments[i] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType)); } } break; } case BoundKind.OutDeconstructVarPendingInference: { newArguments[i] = ((OutDeconstructVarPendingInference)argument).FailInference(this); break; } case BoundKind.Parameter: case BoundKind.Local: { newArguments[i] = BindToTypeForErrorRecovery(argument); break; } default: { newArguments[i] = BindToTypeForErrorRecovery(argument, getCorrespondingParameterType(i)); break; } } } discardedDiagnostics.Free(); return newArguments.ToImmutableAndFree(); TypeSymbol getCorrespondingParameterType(int i) { // See if all applicable parameters have the same type TypeSymbol candidateType = null; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if ((object)parameterType != null) { if ((object)candidateType == null) { candidateType = parameterType; } else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // type mismatch candidateType = null; break; } } } return candidateType; } } /// <summary> /// Compute the type of the corresponding parameter, if any. This is used to improve error recovery, /// for bad invocations, not for semantic analysis of correct invocations, so it is a heuristic. /// If no parameter appears to correspond to the given argument, we return null. /// </summary> /// <param name="analyzedArguments">The analyzed argument list</param> /// <param name="i">The index of the argument</param> /// <param name="parameterList">The parameter list to match against</param> /// <returns>The type of the corresponding parameter.</returns> private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray<ParameterSymbol> parameterList) { string name = analyzedArguments.Name(i); if (name != null) { // look for a parameter by that name foreach (var parameter in parameterList) { if (parameter.Name == name) return parameter.Type; } return null; } return (i < parameterList.Length) ? parameterList[i].Type : null; // CONSIDER: should we handle variable argument lists? } /// <summary> /// Absent parameter types to bind the arguments, we simply use the arguments provided for error recovery. /// </summary> private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments) { return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty<ImmutableArray<ParameterSymbol>>()); } private BoundCall CreateBadCall( SyntaxNode node, BoundExpression expr, LookupResultKind resultKind, AnalyzedArguments analyzedArguments) { TypeSymbol returnType = new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = expr.Type ?? this.ContainingType; MethodSymbol method = new ErrorMethodSymbol(methodContainer, returnType, string.Empty); var args = BuildArgumentsForErrorRecovery(analyzedArguments); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var originalMethods = (expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray<MethodSymbol>.Empty; return BoundCall.ErrorCall(node, expr, method, args, argNames, argRefKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods: originalMethods, resultKind: resultKind, binder: this); } private static TypeSymbol GetCommonTypeOrReturnType<TMember>(ImmutableArray<TMember> members) where TMember : Symbol { TypeSymbol type = null; for (int i = 0, n = members.Length; i < n; i++) { TypeSymbol returnType = members[i].GetTypeOrReturnType().Type; if ((object)type == null) { type = returnType; } else if (!TypeSymbol.Equals(type, returnType, TypeCompareKind.ConsiderEverything2)) { return null; } } return type; } private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result) { result = null; if (node.Expression.Kind() != SyntaxKind.IdentifierName || ((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() != SyntaxKind.NameOfKeyword || node.ArgumentList.Arguments.Count != 1) { return false; } ArgumentSyntax argument = node.ArgumentList.Arguments[0]; if (argument.NameColon != null || argument.RefOrOutKeyword != default(SyntaxToken) || InvocableNameofInScope()) { return false; } result = BindNameofOperatorInternal(node, diagnostics); return true; } private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureNameof, diagnostics); var argument = node.ArgumentList.Arguments[0].Expression; // We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder. var nameofBinder = new NameofBinder(argument, this); var boundArgument = nameofBinder.BindExpression(argument, diagnostics); bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics); if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup) { var methodGroup = (BoundMethodGroup)boundArgument; if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) { // method group with type parameters not allowed diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); } else { nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics); } } if (boundArgument is BoundNamespaceExpression nsExpr) { diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol); } boundArgument = BindToNaturalType(boundArgument, diagnostics, reportNoTargetType: false); return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String)); } private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics) { // Check that the method group contains something applicable. Otherwise error. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(methodGroup.Syntax, useSiteInfo); diagnostics.AddRange(resolution.Diagnostics); if (resolution.IsExtensionMethodGroup) { diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location); } } /// <summary> /// Returns true if syntax form is OK (so no errors were reported) /// </summary> private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true) { switch (argument.Kind()) { case SyntaxKind.IdentifierName: { var syntax = (IdentifierNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.GenericName: { var syntax = (GenericNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.SimpleMemberAccessExpression: { var syntax = (MemberAccessExpressionSyntax)argument; bool ok = true; switch (syntax.Expression.Kind()) { case SyntaxKind.BaseExpression: case SyntaxKind.ThisExpression: break; default: ok = CheckSyntaxForNameofArgument(syntax.Expression, out name, diagnostics, false); break; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.AliasQualifiedName: { var syntax = (AliasQualifiedNameSyntax)argument; bool ok = true; if (top) { diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, argument.Location); ok = false; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.PredefinedType: name = ""; if (top) goto default; return true; default: { var code = top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof; diagnostics.Add(code, argument.Location); name = ""; return false; } } } /// <summary> /// Helper method that checks whether there is an invocable 'nameof' in scope. /// </summary> private bool InvocableNameofInScope() { var lookupResult = LookupResult.GetInstance(); const LookupOptions options = LookupOptions.AllMethodsOnArityZero | LookupOptions.MustBeInvocableIfMember; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsWithFallback(lookupResult, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), useSiteInfo: ref discardedUseSiteInfo, arity: 0, options: options); var result = lookupResult.IsMultiViable; lookupResult.Free(); return result; } #nullable enable private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(boundExpression.Type is FunctionPointerTypeSymbol); var funcPtr = (FunctionPointerTypeSymbol)boundExpression.Type; var overloadResolutionResult = OverloadResolutionResult<FunctionPointerMethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var methodsBuilder = ArrayBuilder<FunctionPointerMethodSymbol>.GetInstance(1); methodsBuilder.Add(funcPtr.Signature); OverloadResolution.FunctionPointerOverloadResolution( methodsBuilder, analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!overloadResolutionResult.Succeeded) { ImmutableArray<FunctionPointerMethodSymbol> methods = methodsBuilder.ToImmutableAndFree(); overloadResolutionResult.ReportDiagnostics( binder: this, node.Location, nodeOpt: null, diagnostics, name: null, boundExpression, boundExpression.Syntax, analyzedArguments, methods, typeContainingConstructor: null, delegateTypeBeingInvoked: null, returnRefKind: funcPtr.Signature.RefKind); return new BoundFunctionPointerInvocation( node, boundExpression, BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast<MethodSymbol>.From(methods)), analyzedArguments.RefKinds.ToImmutableOrNull(), LookupResultKind.OverloadResolutionFailure, funcPtr.Signature.ReturnType, hasErrors: true); } methodsBuilder.Free(); MemberResolutionResult<FunctionPointerMethodSymbol> methodResult = overloadResolutionResult.ValidResult; CoerceArguments( methodResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); var args = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( node, funcPtr.Signature, receiverOpt: null, funcPtr.Signature.Parameters, args, methodResult.Result.ArgsToParamsOpt, LocalScopeDepth, diagnostics); } return new BoundFunctionPointerInvocation( node, boundExpression, args, refKinds, LookupResultKind.Viable, funcPtr.Signature.ReturnType, hasErrors); } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/EditorFeatures/VisualBasicTest/Structure/OperatorDeclarationStructureTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class OperatorDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of OperatorStatementSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New OperatorDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestOperatorDeclaration() As Task Const code = " Class Base {|span:Public Shared Widening Operator $$CType(b As Base) As Integer End Operator|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Public Shared Widening Operator CType(b As Base) As Integer ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestOperatorWithComments() As Task Const code = " Class Base {|span1:'Hello 'World|} {|span2:Public Shared Widening Operator $$CType(b As Base) As Integer End Operator|} End Class " Await VerifyBlockSpansAsync(code, Region("span1", "' Hello ...", autoCollapse:=True), Region("span2", "Public Shared Widening Operator CType(b As Base) As Integer ...", autoCollapse:=True)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class OperatorDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of OperatorStatementSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New OperatorDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestOperatorDeclaration() As Task Const code = " Class Base {|span:Public Shared Widening Operator $$CType(b As Base) As Integer End Operator|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Public Shared Widening Operator CType(b As Base) As Integer ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestOperatorWithComments() As Task Const code = " Class Base {|span1:'Hello 'World|} {|span2:Public Shared Widening Operator $$CType(b As Base) As Integer End Operator|} End Class " Await VerifyBlockSpansAsync(code, Region("span1", "' Hello ...", autoCollapse:=True), Region("span2", "Public Shared Widening Operator CType(b As Base) As Integer ...", autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Tools/ExternalAccess/Razor/RazorBreakpointSpans.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Threading; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal static class RazorBreakpointSpans { public static bool TryGetBreakpointSpan(SyntaxTree tree, int position, CancellationToken cancellationToken, out TextSpan breakpointSpan) => BreakpointSpans.TryGetBreakpointSpan(tree, position, cancellationToken, out breakpointSpan); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Threading; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal static class RazorBreakpointSpans { public static bool TryGetBreakpointSpan(SyntaxTree tree, int position, CancellationToken cancellationToken, out TextSpan breakpointSpan) => BreakpointSpans.TryGetBreakpointSpan(tree, position, cancellationToken, out breakpointSpan); } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/EditorFeatures/Test/Extensions/EnumerableExtensionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class EnumerableExtensionTests { private static IEnumerable<T> Enumerable<T>(params T[] values) => values; [Fact] public void TestDo() { var elements = Enumerable(1, 2, 3); var result = new List<int>(); elements.Do(a => result.Add(a)); Assert.True(elements.SequenceEqual(result)); } [Fact] public void TestConcat() { var elements = Enumerable(1, 2, 3); Assert.True(Enumerable(1, 2, 3, 4).SequenceEqual(elements.Concat(4))); } [Fact] public void TestSetEquals() => Assert.True(Enumerable(1, 2, 3, 4).SetEquals(Enumerable(4, 2, 3, 1))); [Fact] public void TestIsEmpty() { Assert.True(Enumerable<int>().IsEmpty()); Assert.False(Enumerable(0).IsEmpty()); } [Fact] public void TestAll() { Assert.True(Enumerable<bool>().All()); Assert.True(Enumerable(true).All()); Assert.True(Enumerable(true, true).All()); Assert.False(Enumerable(false).All()); Assert.False(Enumerable(false, false).All()); Assert.False(Enumerable(true, false).All()); Assert.False(Enumerable(false, true).All()); } [Fact] public void TestJoin() { Assert.Equal(string.Empty, Enumerable<string>().Join(", ")); Assert.Equal("a", Enumerable("a").Join(", ")); Assert.Equal("a, b", Enumerable("a", "b").Join(", ")); Assert.Equal("a, b, c", Enumerable("a", "b", "c").Join(", ")); } [Fact] public void TestFlatten() { var sequence = Enumerable(Enumerable("a", "b"), Enumerable("c", "d"), Enumerable("e", "f")); Assert.True(sequence.Flatten().SequenceEqual(Enumerable("a", "b", "c", "d", "e", "f"))); } [Fact] public void TestSequenceEqualWithFunction() { static bool equality(int a, int b) => a == b; var seq = new List<int>() { 1, 2, 3 }; // same object reference Assert.True(seq.SequenceEqual(seq, equality)); // matching values, matching lengths Assert.True(seq.SequenceEqual(new int[] { 1, 2, 3 }, equality)); // matching values, different lengths Assert.False(seq.SequenceEqual(new int[] { 1, 2, 3, 4 }, equality)); Assert.False(seq.SequenceEqual(new int[] { 1, 2 }, equality)); // different values, matching lengths Assert.False(seq.SequenceEqual(new int[] { 1, 2, 6 }, equality)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class EnumerableExtensionTests { private static IEnumerable<T> Enumerable<T>(params T[] values) => values; [Fact] public void TestDo() { var elements = Enumerable(1, 2, 3); var result = new List<int>(); elements.Do(a => result.Add(a)); Assert.True(elements.SequenceEqual(result)); } [Fact] public void TestConcat() { var elements = Enumerable(1, 2, 3); Assert.True(Enumerable(1, 2, 3, 4).SequenceEqual(elements.Concat(4))); } [Fact] public void TestSetEquals() => Assert.True(Enumerable(1, 2, 3, 4).SetEquals(Enumerable(4, 2, 3, 1))); [Fact] public void TestIsEmpty() { Assert.True(Enumerable<int>().IsEmpty()); Assert.False(Enumerable(0).IsEmpty()); } [Fact] public void TestAll() { Assert.True(Enumerable<bool>().All()); Assert.True(Enumerable(true).All()); Assert.True(Enumerable(true, true).All()); Assert.False(Enumerable(false).All()); Assert.False(Enumerable(false, false).All()); Assert.False(Enumerable(true, false).All()); Assert.False(Enumerable(false, true).All()); } [Fact] public void TestJoin() { Assert.Equal(string.Empty, Enumerable<string>().Join(", ")); Assert.Equal("a", Enumerable("a").Join(", ")); Assert.Equal("a, b", Enumerable("a", "b").Join(", ")); Assert.Equal("a, b, c", Enumerable("a", "b", "c").Join(", ")); } [Fact] public void TestFlatten() { var sequence = Enumerable(Enumerable("a", "b"), Enumerable("c", "d"), Enumerable("e", "f")); Assert.True(sequence.Flatten().SequenceEqual(Enumerable("a", "b", "c", "d", "e", "f"))); } [Fact] public void TestSequenceEqualWithFunction() { static bool equality(int a, int b) => a == b; var seq = new List<int>() { 1, 2, 3 }; // same object reference Assert.True(seq.SequenceEqual(seq, equality)); // matching values, matching lengths Assert.True(seq.SequenceEqual(new int[] { 1, 2, 3 }, equality)); // matching values, different lengths Assert.False(seq.SequenceEqual(new int[] { 1, 2, 3, 4 }, equality)); Assert.False(seq.SequenceEqual(new int[] { 1, 2 }, equality)); // different values, matching lengths Assert.False(seq.SequenceEqual(new int[] { 1, 2, 6 }, equality)); } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./docs/wiki/images/fig7.png
PNG  IHDR hSsRGBgAMA a pHYsodIDATx^ `T'>oyۿ>Oyo_bA< XnHhmKŅbRj+l$$,dOf& "nIs~gnnn&2Ifs=w9wܹsG7mr[q>|&fӺu:fGևnѓ>UV0vPنfc{gD=̣Sk!GP/~ٶg/n}cTV0sqӿ7jJiM>vqh)3S1VJم5]SKEc$XAhQ735|zeHUfiN״)Xx {(X(fVשu)=22=q.IlP|E 0Z]aj^wDNh'"ŤomphdPg@Bc&48nQK65~D{b Y۬mZ뤞Fi:34dR#j+gLHmzpfYmzp*r,UY/sދtQ%'PUp2Cm6  n^F9pBӚ!Uh&$| >c}tFalV[nZ"pf$Uf D8AH*zj s#nImnZ"pj6eę>#%YB-AO&MYeEpcCE n3S&mPKڌ۬%N!+AZUmPK٨͢'0CS fL@-50;Yv 4 ҘیnW*F`[v~tԄ{]I >2td 4颿̹ﭭ1ڬ63I|Vy7ӃIb(5bMU0B#,55U%f6RZ*Ն\ MHciIJJR)WVV];e 1\a=ILm>ە*ׯW(((P#mqu6GvC5EHg}{,3-FڵKMcY<~ ^=jrZ/)-ՍLच/ZPISz܈vŽ=C;Xx*W"w˝t,Sϊ []R*u6[5U,j:t{I5O%%Y1O'ojMCD%5h^;U^$Q sUZ{{vY]]KM`*$ 0h5{`ޔԌ\Q#Zrct: j n6͊_ݽgݧS 55Z4.=v;Z.119HSf|q c4hS)I2"YQ__GfTCmj܄*]ȟL dfVJjT `nٲ9>~K|||BBBbb b(3N4eUk7nlܴ&E`YY9&2֬m+5hQQkٰy-7ǯݴf t닋@[:]Tu6SX h3$ ߂i9Uș(Alr|kcҖ6Q oʭ]F~a>צfj34,HE;hE-Ml,<;fVhfM~b@?T9CAؼ`֓ۂ3G4mоF<J .Q}90k\Ĉt:}֬v k āT%q9\NWJu{-rr9RN81ֿk-yScEr/ --M1|Yvy,P)`_]vnRRu$TWW:EbjhhEZغuJu\ظq7lؠRvVU*S8M`j7;#2u TRRFZc Vzܧ[4g<P^'QETUEeKJ.R}D͝;/6&n<+VF`EUTʸ?N1ֻۛzm3,S>>X{彯<w/SU9f<=7^kBBMm5eqצ*~)'םl1/UoENvdgoWE#/_pt7d|̸Lcg11ːnltcZru$T!cv_MFUjX};bڪr;W -|{ήc,|fi:_.^n?;ftkDAl3r׾8;p@=hS@%TFL~P3O?4,r %LVL'?wÏi3쫅(L6f*Q1>d_ڬ}3CD>5]Vl"}9mbhKӥ)_):' YJ/^qIm5jjjՈ/P=YBej/E[?qIn8<q/͝@4-۶mSpC6Gr:w;xu݅ VnvZSe$D!&S]xȮm&n>=n=!hj-AGmR4r%>Qv ־r` b"r"!^L˕W +BYZˍs; efFENTxjsrݗҥ&,'@iH#G|ˍ H@&mjnVԹj`E.%>6s"r9km<N K|tzWȖ(BNdÒ>h3qQsa+ qa#gjK둁CYwٲeJ̦MT*wmV^^~uWkT-/Yr!HkdqU_b)Mr!Hlnjǭ!Gk3CBVmƄfY =BnЃ,6 =BnЃ,6 =BnЃ,6 =BnЃ,<CnЃ,6 =DBK=fl+'DD=.}I[NbxxC&Lu2.'!mFoIӳ<o>_Ъz*"ˀhT:iOqsc72m_4$u8laqi2|aMj+E oIٲeofM4 jTMCiq6XVƀ4-3V5iV)z卍:tFO`k(sqI,Rmfs9#rYΓo6vn5z |"v@EoI'0nbE+qòFjjXF'^JH3a6Nd/Fe@!-CTb(gh3,6 =BnЃ,6UV%tGT Yry颡QsLu@p*6'~nooo@y$n^ڠP%f~B*6UO%dqYpcЩ~\۬fNJzjNT Y3lpůR6cGP"j.Cp*jw5f >}+n8YW vu P>jNnS9 jN>}DqÙp*hX-7bcJzj}<rsȘ{]W1ޢ|&P3tmۨ}Ҩ/L]_t^j|֙帬"Ζ=21IW-Ol=U{= ~t=5O&Haubg_wV3 ]5MeffTmmRRJܹSc AԾ !4j6ۺuJyi Y[U* O 96op~s;e|63Ɠ~Rg~ۦ ?hwU;N{Si3I,b@rz-9P`BӠ5F)fsَ\ϊ:G#.9^+s~Wm66ca6цyibEZDgی ~ˡߗy&l Z˖fYzvR+IO׵n]qZj]rkkw*D5kҍ3TN# 53'%cgjFNjF@ߙf"mօT66MZEWM]e(rr=x ]5LlI;`mmU[[W%fh .UU*`<(UXWWG0ϋܲ-> j0 Y c[&vqffֶmbwdefz˥k-[lO9ܲ MOObvǖ7j͚o M"enRkYkv㌻k$'ٸy6oYqMs5?ed`8Sc'XVd۫k6l֭ٸiM.'o;;</}-"9rXD}BQ)o\U.K0^bːʕW 5 ZVR<a5DɧZG%JKJssQm_ִ6[@'T_Qk䀹UugJ{\5^Ե6s:Ye!m2Cy"+#b mֲs\wѮ2 S11}E.BHվwDխkZ(pu-q?"UYYEq@=6 NLi+UB6V.!v4%j1%kfj)m1@lInvDW+W-T&v+))DFB(q9XkQ9Ou`7oܹO{11TF'/(TE1-5}Uu*W[x%)$dѣr.5^tI$.nN\Yѳ絬<IlNLm|eJIiUe*gm.z,j3,ïz'//;]uz+N/0UTUO{5zNmm:m[6[v=?[^q6&&u1g/;eKZ(6 U_~M5kyrq~܅g#11 olTgS[ܼl%ƼUW\Tڋ/~k/Ͻu"iߞ;oʼc+3\x'H7,u7dN_4fb'1;Դl+*jrթ ?~BeCáêhGK2%Xm#㥿kpߵ٦MTyyy*563yX[rTѰ_QLgG6^j}5I=Rh=<ۧ40lذĮoGZ>4Mjj1}f# 6tDpm&2!-luYktmfp\} L5e. -5uvWQfsZQ+nk6kYaCjZ)D ]&:؀{4 oCTxm&>|li,, ̀LF!>]{J|Q%4b+6+])[4W M LG ֶ|nRLex1/>>kE2ݠBܟp"jV¿k/;x񝭿+@9Xw޷6IM7m-l6G}q =d)5::hȅч3V$䇌"%GWTA1,\Bo Ζ.6UUU]-[Tn<뗷^ʅ pa/+@Xp|I4uq_]]>qj*62fL?,hfLmzpfYmzpfYmzpfYmzpfYmzpfYmzpZfԘa7-r#׏y(j"O;E !1micF~m2ͅD5C4K/KBkCv 0SM;2<_;??f@$U"%ΟҞAQo{Ӡu)[E-v5MC77mn.~ݢkNqVY:j)ߏ ߠQf-1D3 =̔O1͟8;G{ ];a'^):=jO=Yq8bܴSac1& L)ȏbD5_XRk ]˰,VU-&!d>Sgfwf>~nX]}tߝ(Le0mq6ƕ`["̬S,+Hjf[wAyV \ V{ J*P<WhK(:tF̜, ьgD9$乸/YN9SJ.<`^~e,ju"\R¬ڹ ,I _;o4xx衇Qr+HTGQ|ټyaԴ+Q̙;v45QhEmKl{!0cuYmŒbT;0AÌa3 :f t8&p1aC3&l#}áQ<dvLB0c x0cu '4(WkÌ [!%quz(pxD}zWL/:fMVc FO,qTa tx0cuf35(_3&l#J\tƠ9]:\CbvzP:8̘Aaf5aƄ-tSA "p]GJJ- /fLBG裳.Ӊ050a}Z/fLآ`7m 5aƄ-tz*\؂w}`IC*LۍK90x_LOp OkT.#>t1j&\#OPA50ìRu1uʧPA5L=ImtKU#_#}¥=]^S S&ԅ3r1Kx DKvO?y0 Tf&Q> f%%%j˶mTΝ;UKEEJ%33ԨqO#> Lg_ʧPAafSSSՈ/TmLg*UPfq&h= 4=EoifnȧPAap ݵkJuU/YYY*unZ7Z*wEZ:Tr@?.,mC ace=;0^QQ6$W%UbdCfӷV ޷JWܻwowD7|npHe>t! fN~5MRZCǍ+3I7t ɻc=@Ҟ㵭rHWϽwC\I+7U弔zkQmޒBSyW*'ʊ8qTc럪0i af:MRZJb_]gZQ+7QTTV P[TA&?Z˃rI%<d*[.q8Nyi)@=z"Hп34jБE9EG"]10ja.]Fu~1v5{yKF?<? R͏R.8"xjk?.gpe85C =`&&&Sn#U9T^"!xݬE}7 v\0*k $20TTBNH gS%% V@0Į'C)a:4oo߾jLԃFi=AM`b~~>Κ@FnEq5b{חY?–x?ӈ[b8 Yj\K(]TBD B1C b(Ձ 0"-fAJRe<{;S$*~%$'FhCe9tu,%5{ys͛;gbc>=o옘ٱ'zVttt ƢgώT$bf!'nNl,R(3gnM`}m?ٚ%ƢhHhHhYz~*,> x{ @{HfTݣFXn,Z,-bE"üACc#pA1`kEKa czҢ?9i2XbPY &|8bU?׿:D\[4;_q(p_\(9ke8r䨪}Ygڬ#g;'ķֻ^c݇H.ue 0a*iTUdwXnW[%L,>DŹJ:XW:B?}J2< Nqr9&;yæ7dj=uTf{ôTN"Nf5)Stcq<C{1qqCh@pcff 6ӂbAZ$j'0oC/@f&ek5Ol 9<F=. p! QI!#ML!936oN\ȍԼXL1L4cDѹ͙;m9U%5pTy05HORj~[  B(ed |od*Ip8:jWqF%xX[gfd\,d; Vy_5UO W`wD0++kݸ O*!D+ORQ xttqwKUB:g..cj:Kg5EjDՁl*;jу*((#ى , -'N> -Dh@aa!uhUUUj-Cvqd0WBĎ:ff" нuXS,S1kܠ$--M"*B(hVC|ڬX{ǫpruHߟ_WhU@K? 6dff^ٴETN4͆\;jΖn}|]XC\SAdff΀٣?,^\\LAUhbjH- F~y E;R Y^M6#;W_h(mjyqv)_u2;QxUN926ZBQmG쪘9p,Fb8iWg&ļ'c UpٲŇ#!Ӟ↡sG<HPǀQ[avGc ì?k~5Fy_n8yǶ?(I_66ʙ|Yvvx/7'=6>1l>>xTQ /_9z<ͫ2@ظ̙b|v"uЀ %|Ƥ.Ќr9VV۽WXZ,HO~KԶn,ehZ RӉl=gyvӄeVNդ719?孃v S 11Ξ5Ϟ=]HϞF]wͨj ϾYR *8̺IrrJ1LTPqG^^^AA }vЙ fo#_vM6yyE4ϖ@zNi˅:&QA5ÌniJ@u?Pw;HOnuSDŀ.њ.jU?Fg,5UL(#^a BƩ^}|(³zx/ꨠ⾙Zvv T!ė) ODzXӉ2~2k. !3v`r233$i =4#V  TPw(EPPBx4f1&O;jEyPO"FĜ5YYY޸2*abk֬'u0q.,8JL/*,⩈!OoyJ6hH`T{TjUU(펜,Y?2Ԣ~uMޮ4b`"_9"[<o$0Bס܄Vܹs׮]2} 3mUE=ӿ\:=99ABJhoZ 61e{u<Fi|=8oq ^/SB% uc Hh:rGGb,#֭:ӺqC5AX#˂Kƙ?9+уj*۝bqO~|AӾ>?ꪸn6d`DN" \J,-3Aꯎ"ɦM" $USTP-Ӓqėbpx_B.qAE~C ={!yeẖ֝.Q^j޶0! ~s"4NgPgTP16lEQVVRLBY{DE W^'-j"SwPu1 *Pa6<Yx#FX!cA{rE>_xȩ\cip|!f$^P4(2b.O;?:wt W|X2?8/ _̟lʜwbcR(G"*8n?S~FAkV^_wY^Tf <TP 3^ 8j6i3 :f t8&0mc&p1L0ca0AÌa3 :f t8&p1L0ca0AÌa3 :f tDc&p1L0c쯫vX IY*Ɂ/}c 99ǔ<ErmS|í?-}9RHO;mX1i׌yqu(._|K];66IcGMSf ŒQc&mygߺx#'G:|7y&\]֡ =j}ht!XH =3k{ѣ[#>*<Bq`(E)̂jcoyWo}7;jc{IO>?QsF1޽XMTbe,!|0kc>1 hx*]{=S0Ca񌣲pc4 CaD[ZY-}٨ t|^43_oyC;SGchw~Dڢ1ۦ^">{g ?96[6G#GtO|뇓+œշ2X&x#D 鍛E)N+4yH !}A-Kӆ9"s 4|7M,VHIkOdZcҲ1MeBD}cHʰ,VHXq3S;ך>^ܔr;21gjߝzˬ1 @(Y^$#W͟q;di=X0~_Xe7kn]F3?Ӱ"Ƥ(Ɛx(6$b̔.5ƵaX-׊N>ҴPփ Wi]:b!W}W؈CgNF{. DEXUoWRY5}$\qBb*?e)߿2s dGm{*~aQF~1 m1'cWcVnX2d|I* !c<Q[q0r5G!$CCbsH(|+(Y"_@qFD;Bw  Ra,LmM5`-ZblJk^mdIcDcuYb  &#bL-ҋA6qX1BUO^@TOnV{`o9jg9$SjDQ[n}lYC榦M DIQ&hcڨ%O2B1Œcucsr0xe `B ._+"Z)u/X,VGR1 4c \8&p1Lpc10ca 1 .c \8&p1Lpc“U 9}%^8Ƙ|ߡ VCGRk]74jtn7TgQkc O1D҈411+{/F ^8Ƙw>62f SVYcz^8ƘD}Z/cLx@1&<Q{Ѵf6@Z/cLxB1l8Ƙ Z3ں>I1\CwAPlh}n騅4Wp1D }2)~}CE 1fB1@t!xcP ITkc O(^8ƘDAF)~H36cb? rc [>8Ƙ ŀ s=nIz,1&?={މJLp1`1 \( $d51Ƅ'}Z/cLx c21j p1 @Q 1 (>!Q4=2UV5"V)c*ja^8Ƙ@ϙ04ꞡQN%<[@L۝>JȸrOϹB.mA<&aȾБ14 c@P Ng9FycF- 3xcuITkc O(Mlk8Ƙ5A}0>IiQTk0(?oDŖ1fA1N%̧B{~Bk]lqk$=}P<S\,_>]|n*p1@1@?MdFp#>N@:rb Xi3(-/k&,hMVcLxVc sdе"nj @QceM/Ov)T2 ~JB6<S<*v5*?#ȏ{"䁘9}qS1jBGO?OSc'"B,nIXzzP 1KC!?%[~V|%=L>#1D t_"$TlykIZS&kIMH}nkz H$AϪ(ҋ5m (SFPcc=!~@APLZc[{?gϞjU5Ϡhhv5")))QٶmJ`֭eeejSdLcYYYUUUj@g-RSZZ8ӋP cP#\S.hONN޿gXauӍDq~ɴWhmcV clDO\l66*333//Fe0VF%*ԝwq}*+Řݲ.ZH輛V Lb fR#CWkSSSHP:0;;;''N+GiUC+*@1>bпVĉ_. 6j ^&`t.D]ꨳ;l.^6r8j0c Lr +/̴$qT,STYYŀnB,8VÃS҇M25Fhga٨|?ek2joFblStJ}Ȁ)LR xNK`qrFawKx$#5mPAUU0 c21G á| q@oh9W Y1&pn$*=-#OUd@-qyhT!TUSZa*qB%9UֲnК/U1y A⪶0bS~cs?$)9:1ohyq$!yr':kO~b]ų[G̘x~q+t?"c"1 1cYKeO <+>ucUS^)853N@W,\j~GvWpK!ለv_ oqS#Y3y^uuIoCUd\T!:?^e 5UCV[ueEEfFFee%͂x#sӡ! o-8j)|=6tO'ѣghAPYWlY=H7{6&n6Rdd槧wQ8Pl\Q|ZmV׺u}zWdeښ;~֣Un'bJ+++P)QXA1U!p]M9X;}u T*Dرm?[+,os"<m60t50}EĬV+Nyyy:$gbB+(Zλ.8bi@>˅8/hcB( $P2Qg?9O/52r>{BoB1D jD=䢢fuvÇSRR 279233hijl#yRbǧ=Eg*?WIERZZZUU\~ t4MD2B E h:1# n=X__YYKy rPiG3m! @1n i*4XvNNG\;P*sz$ F%.8cuɽ2DdRQxKopjZt0ՅDyGUŵT{pwH+q;+3 BÌ eJTZ'%mھ3۷+bGnߒe <'$o޴)=} 2l۶UW"j5-XqiCBu7I\:k6\m{nU@Ee嚵&ZmʁE%B]Vc=cf7oMYnúk7m^qmNToc̈ 7T7o߾QC*s1ڮxنDVBBjӚMWqV֙ϩAˢJc _~xQLkjn$/cϛ=(Erϋ=oϙ3̜93fvЬٳgP(z91;3g̈ ";6.EhW\Y1㫖%Fӄ,lmA~>ɲuYjU9O6eZQ\٬t+,5얈ٚ6 %VӢ53{s{4|@M'0DǁѯF  "ڎqZVk':{ c2R1ࠠK@Ud`Ѣccc7}Xt곒#Q?}0f<=)b| o!ςTxw[|ℂGj^q>\eĀ!ӧ4 ]Oe4_ZQTiZkZeHL-mZM,Uե4Týw@tH+`5o}qs3byehV O Qs WUdb .e_9 jVZҥOhzW?7 NG#gC5P'cOAhP7AS:cq-Vj<M1q1Dy bL{-8]Ę.uuFkу K~G2KDث:Z6L{jHGk] 3ueĘJEUd@2ǘIrPGblũcQ?1<1Z]ZGͦ=,/ WκB"f *-/t[ j^FLR{$6V 7nYZ}23+**(`j/(ƚ<M0)zDO ][hjjlj4ƛfxSӥKbzΎQ͉CJ΅Ɗ:oΜyzgظ9m^uл߈86bEGQ4U U##Y|*uWS};MԞ jR6-Ũm~EaWóuR/4oʵl:q;OԻ J5m=Cr%-f\!O .lu:9򻹈1rJǘfEXz͐0Ik.-s!+I莭JL&da5vM<\p[W]sޡczUwzjj8\Es`h}"' SR%Hc+VYsՋFQ{#i`Z8ƺ;UBqXyQ#xxID2НU3D8j:S>I9r$99 l&O8C,NHJ+ebBkvޝ qC4Hii $;1֣g@ɴfEap#Scwl1!4$.VD<Zs*M`%`\i&}cAD6ZVpP"M ZYlqL`OETVT` j}%}^D:r1:ǙDTWlܸZnqj U|SUg;,;HJLLXLѨG | aUU7hWQ1@Z:e:WX)c4j2['uy0!cZ8>,;p٬z \x#UKt߄Yp3Ӂ@ˉV$LžC {jmڴPa~6|] 硒RD^!ETVVKB ȕuVT`jI$!*oq87ՠ;P5s,1{snysCbVAUgS/rSؖc޴J3VK<Ӫh˗/_j-RV.]ψtii9s9g`(w=a\\S+Dzb>5ߢˍ)))NuQ=TE<ꆍ[ԾVϏAc!&bH(ˀ)Kc aU*|a׮]ƐьZ N'b11$c1.qٶnuUg}VmOPhfĬq@$98s &}yr?bs~oG}˗Ŝbc{P)!|c)dz/V^V~54~z"?&&\5j@"&0POڍ'?ʦʿLJp)Jj^: ~@4_\[q=3-!q+-qYəב4/9Dط'rBﹿ(9s^r 9G$UZx_55L&b,ߎEb9o;&gzϜQuI>4=4oχRn-7`e"F%s|TUv w'v76/~턻vHprT-c]kDѥp꣏>Q( 􂈱?yU](xOyz-=+ 14`uJ$f<rucB-8{l$d"R)A1jLQbX:/XO=(Oz1rEHJ1L0"b҈7{j BkaLg'r]˫?1y t 1vłěe[؝g-o݉2(އ'5c#jblo!`]l].`CD 1Qkދ%$*T-!cAe'y ڼɧT9jU5_w((4 C-K$ u =5 ?m>BF/cݢS2fǘ0c'WO1(,,ܵk @~, puMTdeeugv&<_{W]?} Xd/%^SJOo1}Xj+UԴ=2] e8T]ړ0]eRBW<a@jntavO{Nn|U$VxsoF&k&Rc8=k/?$^U-E{l+!4"m1EkӨB˃bTc,lܵ@Ę!Gb@1/Kb̔DpcY;` 5oJvAژXp~2aX 6mӦM8x'E#GҐkmk5ٳ{`0pbLZ]WPl/檪ÇShU^t $"r!J݋] WPC}}=/d:$cL$2D B!c4 * kK"|H ?'^ gh^[~JRjD8ʄ!0P$Q=zʕ+ۧ2DqQYxѓө 1a Q%\֯B26;N!Z1f?`+=`wmr(CCú`ol%F8w68`Gvg$ ӌUJסÇoݚp$,СC2E=)2j+(tJ@%7 2}BXS' !5I-1gݷ\W Ta\E(F3ٟԾ);SvlϢW7"iiiY4 $_'(QDqZx$vJ$@m9f ǚi_ӴZ/=*z'ZdnYI/O_rXx/`ek֬X,WZ6$"kr ~JMbߐhW 1uE6HW& G˕ϐ` Hz(ME0I6t=L1r?Y"<.ro5(;=U?Q P?! k׉= .\~?mG?|ȡQ|Q{u0mb#O8*I Q/.b̸bS9c\_O<}H8K.6ǥ*g@Sc2*!B_B!>| G[CQ&~D1@c"'&SjyL?Wmٝ?y*~'1ĵb…q]b2Jm,OjڬAH[b5/"*S3O*A ѓj!X,zP*R$F._Ř<h!Q46II] NίpӪ׻l.(w7d2xqj:GY[笮:}*#ޟ? n\R")?p]8=Ee\urF mdz1.] )nӋQz7 ?3U29zի>tHfPU݂c1r"AD~҇c2b_] {cv j2ˀL :k9ry \&pu?tu_fZv~{^c'S}ZWwʕ>~2 *c@{h&ڿ/x%7h""R%: aBοcGH\21pu*}br6";'#e",M GDlV򓲗1#MzAfT@LҡHe50%&%.5H>xntzYSC@1aRc29zýOPk`AM8zx<Stw./x˻#UӋp1Lpc10w18&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca1<iQ㦲XcL(_\qw(}aQޚM@Fb8vM6j6G#Qvnr-Ӈ0rܔȱBN&S3uiM7m2!fytVϊ/߿~ !}PՎ#F]m˷r2Նz4|`,i-=o2;2>6ŔiR+& iҖSz3⶟P難zlmkK_~d-?nݱ?M=baL9ѓ7o&׍vݸ~w#cH?zV\qW2QNgF Cc?w<L@/fQ ݊jbtUPSck@z<zc9"*!7Z{\@NIbHcV׉!CJޭe >t[\YKn_47=E57_^o?|RsQwE,4bφѢY, jds[R fun%SI3f ;i+26@Vb+'z!1yQ-*-cM8ٰۦFOK};aOaM72麻}i'#n|47ylpG@D©ac^777}n2?tcً&a),u[M!06nOaa=|ݸ"ljpᑓ>8%OuDd>5qȟ2ơ:=rToCn-SsRX,Tuda?cLSn?mO;u8ܴN1~,rNQXfDqZQA4|t51ƥX,+N& dX:QƨiX,+(N|aqɨ˘ @>3Y,8YuWc􍚩}הcM?̺b))Sh^S&4ͤ̍ ~qY,2Fi̛А iL]7Q7 C`\P^R&T9͵fTtT e).Fyg}^`T$S>LHƍgX,Vi q͔og՞̫˸,  X,NRNUSS=+S,<|;Yu;6=U[wf9vO' S}+olӽ/ס3+3ie\xɼy8T(z¸i=zPz,ldp<:)t\,/޳rcLPUYANE'j綗ZLCX"gE rG ꙝ6Ll޸%tЧ5혹ItN6Ci.~ u2]p28{s5dm WᲿf NV]VWClhԄoE>'[yo!'N濪uIO/ljK1֏Xb\"'٘'io!M3вQ%Fi311SkjXF PgђS"@'MTc)^?Ym/ TbX?'#+(i9UVO>vzPp/|J^|wI Pz,lu'czJs2jdꊝaaBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2aPDm|;1 Ä>Pd 0:{q.Zau#q`-)}*om'0\@t* FMoooXkCov2aPBڽu¥)L{dH` d'Qd 0:0Ʒ;0L(N N0 JS{sDREa uj}`TGd 0:{9S<>SO5ޚ9Tk}1̅'>}tJw&1 ԩ5Q'䈇1$';0hLuLV⟑1'AGL3 AafN(\Jd 0uj}a(>Pd 0:>ru(Ua&PFa&<Qv!ѯ8S\>8c$'^afNLTOÊ >>]'ʧ|$)#f?]LzzD= ;0EڽoUG`BdZ4!aR贽 4p,a{^'3~ SĬvafN;0Ejہa&Pv`'c %ԩ=9pBmR;EaDCv2a:{џ-tO09@H<O?*T.}dh=o-8 dȘ9EJd W.z䜄7b0j0_!a(Ew2zFGGs*adxu_K'_H0D1*AK&Cd~zNuj>y'v2a:w;>Ԉ v2a:>01 Ä>Pd 0:>rd 0:>d 0uj7p*aJ/O|a;0E ߨ[~E<./~EO3Kh4=Tb^XxpT=9UKu"GU5z^_mv2a:wΙ afNCq2 0 uj`Kya'c %ԩ=1u|Je'c 'ԩ=Qi~a'cǚ3ej}^^p<sZa5{#]UYW4NOMF֏aΣN^*`*K!;uK!py Q {`9 rZ&Z>g?B?B?r-E?ׂF!Z*fr2~ND+'xξAۛ<ՋIMf}ͳXk%=U |,N0Aڻiއ '{OS!!ϻB_{0z@ ͋+˜$rW3 '(}[$P?SΫN0ACv2& UB;SCml+pUv& L9&XݔcU;L9hjUkf߿۶m[n˫P:>ru(Ul@QVVKرcAeOeeejj鈝;w_vQ8B999*awlZ,́[ഞRYKLLd:YYYj@뙜YPP0a:{q. M3==y G<yH}ϡx ;Y著Ss~~>[B UUUjKtɌ:jݻ޽ZM`l@Zoc5RXzz7}呠gQX<X/_r!|ަO*q2΋5W/a'7-5mEEEjtt"[n ~ҁ"*?Qˁa-dlHPPl@<.XڴVX݅KAޅ2>gO`+r<a\v爯G_#QXm)--E`ǎ=(..^~=:=:8l߾}ڶπ hvhh'`WsƤqacPD@8}Fav2Sf>ʂuQξCn۴q{bΔ={;e?>ՔC٩E(.IO'KLܵiӎk={ HMMݶm{Ķ(ַ41-gkΔmeNۖ+%5/9%/5 SRwef//9lְ4ds; v23+6̴tM5lڴ [k^_',5=y56SVl^jixK*!qZvMAAAff& `:ggam44q-~IE4j˚&eib^;NLvݘN|wC59NS#֬5zz[~s6m`Zi}JJKM+lmޒRЅm/Y|K\5(tc-v<Ç|{>tGx ;m?{lG&/6{f; u\q$SgE8הy_fq'wRӘm 4}"^LFg/Z1TznКξ;&ʿqf.:Jn-s;ԫOy!/R;Z>X NYHg!ϰDH# B$DxNl 3EWL5,"lL'==߸KlJ9yLl{'HLg!Y".GXjNQꔉ$"}QLA62_o}`> N1^)>y9Oq,l0;ri,ڥ<(+g`amޝ#g{ee01t'r8#m3$ː 踽/\:á/:zK(&.(G--\4ȔOGO%pU9nYFhv)-Oj%d-TTT$%%/2k%mTuuN};aC4˚ PW;<WL͘YmZ/bOx6ʄa`2x /!_<Yr9\´ZNSx]!''^fmҪT1D>IPBe1:F'sL'0-YD9Y=2kduO9 a%ůѝLHɬ61NfS_?i[T(M|[{NnGC|^qj0 [N$5 W]S#Ät. CXpl߾===؁bTĶM#YV]kW5$ F}-]YmeKy g'u`' hho>N!0&r^|X^@Cߣs[L%(rVuuΝ;);v(//ԥ2yie: @`2-:>|xQm$ܜ ݷ.d=Kee%wj$`S#!BdaH 92[MhQ%3)!H, b#݊D>rJ𶌌{W) Z[5dtɂ'ñ㏎` Plr]aRCCr/!\iԀ+M\ff&NgD B@TR_sr8`EC]v_1rf=Z8&0ra\1NzRRRГF 9r'ֳ֓V:#)!;|²j%=dn?% yp|, -[0+;29U`I:TJ.S 6b )۫0MBU8"!g S<'(Nzݺu6mU%nJoSnc}js|Co 6PqsՊo??!Qvk87Jtc!4*zy!d<TJT^n}*ijYbW%-ũ2:0KzɨQ)~TKP#&a 0unڴ lX"a-KBsIp*LӃ ",\bz>T D[_a^Zrָfb5*Ϊ 7LeBr  QYݦGlLG_C5oJa$U[H6]ᤏ/|]} WB83+%a8ꗈm -..޾}{ZZځt^2ER26 ;!chNp2{ӎP{P֪*5ԩ=SҶ=dY۳0iqA=<(IȁD1147z.7z._܈?|$J#e-QqWT aqf=g͚/9sFtYg͞5k v11ѱqOLllLl(iq(i1c␏,bvY918~B&@Ypݹڣe E{RאB9OĠ'#LOC:{M\́AZ݃ڴ9oZ66 .yĥeuT}ߵZ"C!H<&8`Z -^3 $B^zLpctϞ=))) /r8Š熃\3^3$fYEɝ]'Č됏 __qin/@#whN<̄셶'SӚ/7?ϛE x2ao6~ÄI/`N {LFwQVhF|w^p1ua8dupd/7'nv,>01s͋33:zΜsfy".n.4Ec>09F(M›Psbg|y11ѿ|f9ODϞ'll9@Yqs3N%$媭ݛE$h‰@3xJ%yߙ\o4aQ 7{DAΑEө@ 3o8"6(:B,V#LQ Fq@'{m޸yݚ7OIN֞}AFifg~A)_^GB3d3b!~Å"E +33:d`m m;N&MFK_Ycm}:.ݽ5y8hͿPرA+#"FaƯ YT- wß̘;;;7;/5<7zԃQ#G:[-ZfZƜSų><șPr>YG˦O񋋯H`ꢸ/\n}LtjX!NG۾Tֻ\Ǹ?<F2jm,24 z{^8?R>9H|~Rd9rꚓ~ID?l:vsfH;y |ϛE, FQ /ߤgq 3ezN&>ӲˑBNFV8SmXr"DO e%b K;\/1;M@1x'ulJ`W,=-&]9sq8aeut,u!lL~N!GrRPPCm^8MjBK['0*1/KKGɮUXKvW,G߂2(D8qv]p27°g0`Wd%r,\t( 벯c#'ala`(3PuQk㗶Nf9ߖ62TD'~j}S!N檝l1N5MaQw{=. {cސ&'k<#ƪz2Ore'LY㨩s&Hx έ0:Gh#V 1eLhENV_b WHU>P'ًr2`XLuؙ1d"`)ߤum =Vkm+OeGGhim{f=WSxI8g~eytY$]B'zlƦ/=͗'fM6 x<PEe4Ț($2m9:648z뭹s̞'?c!bgΊ5#vsΎ-> C-ngbfŊDGϝ1;nVظ1s0ѳ1qyscf̎*0wL8qϊQ rKWt mHFNI+qm3#Ѥֺ?Vonx۴ʬ\h?=ɓųbjӚ[j38m/)# ,hOj)?щ!{!N跉~";Qt"npҥr{_3kuXڦN]?k+Ǟ'oSU`}% kMe[cTUUѻv?$k#M"@}kEj%=dhVRZ %e d,\. 2eR z'䗋gOSYYyyER2H>TXy* J~YjЭи0v9UUuuⲲr9,;PVzvAEIQqQ~! z(:2%%III)) Fa S&Pu CוX˪+eJ[Rť ,/æ^qQ*ʷ&o1:=+AȥBzUU^e(.AW+-W@Iy ȗ]Uc OB'%%@{ Np 8p +++55lN&.TRg:)GrE/ ˈcLyi HVĚۋko,]"Oa , e@܍kŗY1"bh qAN8Ů]HWUAqHp_8$Q<= ;tjĬ58蕌CfPX8Ԁ0AZb ]h913v b:Df;NV̍+\'@><v慥aOgyQu"Q1KNNw}\#z?tboeP GzzZ*6V<[mQ r2?V#^̤tm*!MyDBt!,EEEg |0O%a-G,k*3T;I!f(9VAA]Sdi8pE x( 1TH@ anG$}dtڠyTPwZ*t%ѐF~Τ44Ny9DN 0/l6$.`_vTE.~4a_aOsd! b#o 9VkZZR8Yqqu EmIݻwcU+**ЩO=^:;wBq|1IH|E~޻woii)v&OM F?ӑؓjqlavQ:vM@[`u󾮮~ㆍk֬?4;:NDm}Q9JBtusv$<Z31rխ]nÆK.o!S=fyl8AbDءCmسgoffVjjb1|zBV."BnLc=dZIL6X7 ňvee+WZۓG  v%ے MLL& DdEF x)_1P6߸a&h˖7o9MjӦ}iaڼ2 =zM:2sشf妵҆jع+o^ 6oIW`BiY!=}[ZZJo- ct[zfzz^ؿRSSSRq^RRa?4]Q^rxun߸aӦ[6n,rCdTPXX=뱒X3SӥZmI-JaAٹkwZz&)5-CT%3`z8qٳq񔟜j:{AIɴtdE^)pR/R/fXA}LlޒV/oex_ꔾT-~Y~#}ANnrrvSrss23; f͚3g.HF9sm8DhތݒRgmݚZ3l(ߢ'ګ455={kKUj?Xw>sF_~P J`'= U;HN}%fϻ`n~Wg"s)uP.jĖ-?&pՋ3LuSOfzG$XOILWcbRcҹWeccʼnH1rr4c윞O9&=';;j*.zo@ + |";$*c Jؿ~|BVa0F.:k=&&6=Ecjq$b0AitBEcbK|@Qıwc<j2w[,{߯ƼUFeƼ JX}(fA[ wŋ-tf,sϝ2/KM'n>cwJڠA6ְWT>>Zp]X.vzr/6edr4z!ȧ zyçOŬqGksE&ͱ&O˦ĸ1 z3R (i͈LԶOkQʬŊ.8U~VxZ 5"2Q2>Iʳ;#&R K['Qu[xk g|P7X ꚓT=Wm^:03,xU9򊳰(I=8%c)Yi1DkbF:Hz{_ZcMD&CO-8[AQ$8>QCћV꾈QjX-N(q֣%]p,+9ᙳv\$d11`jH/#'[V'; 8  PL4悱ds0ljrÁXVO( j[H9VOA M;D9bwR=H@rc(`4.8;W,{' |Wh|ߞ{l=>0 n83QFӐ&_ČD :j*D?*)蚓QNJ_nM8 23{Mirvh?Pȱg3ԃDs\ zu ra˖~f=~?˹F2-dLOI_!hRל邓ud*myTdL邓u rjmbtGv^eͪ)W_]V#6o C7t|6} L>ٻZn߫һZVDGU#vz'jz^ZؾWO?-tȾ_~i^?ߟ_/9;~iH\\χ>ɘ>`׮];vP# 0݃{vޝ 0>a'cOOOW# 0Nw轫μka;]KH)..NNNֿd 0v2THHC>x1<W+ʪV@7gr )dteKjn\}5k0OW{SwsAjWwF 3"Z$ht~1ZS=ʻ<HP=gSg~O%Fڿ]ɾꍢ=Nz\.EۧxliҮ<.ߡu%?Ek:G^K/ZSCS(i7zP?jw-ҚjSoa'N7L'Z:?,&|'C#Daj%<ۧ/,:+FCMbFdH(pr4|o$'&  iɐ5`d `'c\$z['j%r@i>WJ^r )dLdffvK}BEE֭[EE1a> o}}]8&:+, VRRRyyE>12.f! )$5R8#<ŋWi]UUQݽP;_!E%*+>>C!ȧ QmL'* Dևa>,9ZU61y 5O T/ax^:@݄ f'CR]BiT;kjj*:0 ;Y8Pc%ցR8L Á3XVFSRR 鞺rFB2,%t“jV; 9X3 .݆S?9u˥c(**T scBeddڵ+'' RX+ZyY &dCxΨ*`!B޾SDV uir:#I3Q 8qST&;JeJEq1]8o]2cK4 3m{f28N=-= ˅YGUudlWD0LN8ش?qϏ-qo1 F^0z,/`FMݨ;ŠKʅ :0a::jЙ::6n[?/O;P-cpHCX t˭Ғ7l޴iG9NN ?OG?G;B]wM㮻 E提$GTP ݉9o Qnaq2;<bF ܍yׄ; 0ꞻk w^z]$ ꅿx ?wfK?<0a;Y8+YfFLEk,L!F)'ZD[㚽`v1=8tiC4,fGIr)b5mfvZ56.GA faM a,iCPY2#bTJkn]M=mPQyE׭ ,3-]ֆ U- 3a' Vl6#=e]'MAlNN0J3SsA]Nɭ7Q]MX?D,&d/~'m|)5vIMe;dMԞDO+L#~=DDsڌkMƦj'SIr2ˏ~ oqR x6*8Le.|7闢 7Bmb2r0rDyNfy5% %)-jb2&O:OlB̅i떈#!ZYw>br/`' \2b ImpWMVq-DOMw#;Hsgt$E-uk˴:ɽb'c,:Mz Z9îaEF>w}{>}kC<YZQrԺj.0U!!?&O!*NJGn~u=w5ϿVaĈFL\/q v:V9rddaQÆERaC(22rH|Q4e({f~u()*uUGE0vmc#D1PX%UR&ZHޢnoP%%-y|oFtJ_pʍT 3a' {K8fC54&;1Dy6xV9.{M悽8"_~K^c[5V['yFOcx>TcI5Ho`Iy| Dk&"`J0:}UY] =}_ @uH(*mVK<NliV5 g*VZP]--x߿_ivN⴪7nL~2< _Vj ` @I#*Oa'c@`' M[BTr/qV&@HVTT7w v2 vn֚3KHH@;; 6ω^aӦMׯR ô;&TR ô;-|)Daa@?$=wؾf-jm&|a'cETpuvHuVfҧ\_;cv2[lJT[YD\PoJ8"KNEXxDq|cZDdhDy$}I0fDydT4KTR *pX"}X. TR+iX%2P#KG3TL=]uL]hcs}V)"pсPL Nc<|ds/}hG?X^e/_vtHS ݕPrؘg6̏b9IF>rA& ;3`'cEdp 2^ }ޯUnN ɘnʟ@\m_~生 jm&|a'caBv2a&a'caB9_|90 'Mʥs2a1 0 ;0 ڰ1 0 ;0 ڰ1 0r&1 0;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ('v2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caB'cX,+tN&y`/߿~K?6&dj_\q^ثknnvG~e6nJ丩7z 7mXd|ĸi׎r1)rCrbR㑖 M.45J1vmFrim#=g_\Ma/6 445 D4ec&Ɔ{dmo ?äagS"NfԘ)cdQE>l&0nr؇FzNϊ/߿~ Gt&'*7/`oecںÔ6yЋ9vx) S)ǧnӿ5a,:.YW^?'gnp'_;#E"LqOq۔aGny rܤ'=?|eHYq_aS8 Nf0lcq|JcI]x SfgusʔVe66|c&wWTvsw{57bo{dm6瑣'0vꍣG|ؘQ~ݸ;emomƶӳ/߿¦6FC33 5 ?NA~o3i$4Ȩ>&դ-o]a.Qrh8iKMՇaNc-i0 R~ie?gQxnoLO]76?ûYuƵNo^t<-Lw7_=Io0rHYq_à^$&MK1د.%ILE$) r&r)[W3E}e`9duTVFJ4;R]uicQ2p օ!Ik" ȪO=frSc mr1wo<w] /ް8 Ky͟Z\pPo>!]Y[oϱ?1@,ҕzs)%I<QӃ9 lIrl%„|y-NxGb*ocSFrͥpGΝ5;ou'K\pWzwM5n.g]D-;׎zUǾۃW>4/F>P9bzGl?~JUEץNƦ<M̎u 2$fTCI1/h&{c&u5ۦG:{lϣn6'1=qS'VnmSț^~C7/>;\s[n4l#f,bzAl:ImH^N[[c;2߭2<s#o}q\sǔ1uc|o7cΘI#?4|׏y˔S|6KaX,VԁAϜMa"M1~ʍ ^?nxCLz0rp/F 9qBs(J|'Z|L< L7/bXAS6.<eQLۦG¥+9Ta ظi2+qgRؘ3`8赣sb.bM},1^ES㧍@ N6v:lO;^ GM>%zl-`X,VP5{cFDѵB|A["A٘)·s& #99cX,Voh@ۘpsH갌*ZX,+6|aqI*^>b 1d2Ʃ$,  e\bݎᲔ4jT,aw g0F \gY8[4n<bB]-66Sɴ{4Mx1& f2}t QtXu:c.j)"ݰXԀ2&S5< ͸XYnGǿ+v 8 ƳX,+J_}0  lCx%"3G%(ilzydcrTiW QÎǿᲛK>o[eLhY,2zbcT%fe`4Tr;k!$ i8z](@9*olLS) 1 C %Lrb|?A&=uʊLμbXP!ۆ]в=@LJƍgX,VwobX/ecV)bBNlcS {VY,+x_6:tƔkz卍`SKDa X'%<X,Voʧ)9fٚkOArZ躪kѫ-RSlcؓL]%f/Ab_s޼y4`cX,ac8fb8ԕY_l6<aXldPy i^=֭C\޶Of۫(\lc,7rFO펍Q6Ithƚ!=D'oUG $IFS{mI ^bO|<x 1Q4mJu cmb|IK<Γk!h=z2Y$r/w)-|qP,bpo- r0J6#ېm(7U!$٘sSbYHj V p;䴷D^m\"߂ҷbH+qSukX6.$!1sGSSӎe;DehhihX'%t ~0ІaҨ%fhj*Xޔe;n<J+r±DCGEz۲EZI6)NLƪ׿S0 s{G ȇl S[zc=mqT;"[oX L('acUL6ƚF-ke-$^dlLMX43L1[l'*Q^Mbg$mbػ>-Y//kҺae[3`c4ۿxQ͓|uODc3. dc>EaAi1d4oaOZ٘ Z@'œDgc`0 \JtQL?6fX'%t!.lQo G-QDKt3NE6bzSɼ~MɂwW j10O>^lG0I ݁Sz]6bzSluBSfJtMd1tQ; Hy>[X,Vo]c+rzJ!uSlc,76bX1uaaB 1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a`UBv`c pB??`c |60 ma&4hkcK]QFMvH@V{DX#T,uEz簍1 Ä ~lGQ"ja.%> *@6* pcrba˯ Hb)`c :YEQ =3!'0ؙC'3y`c :76f草6?9d:lc 0a)ӻbCES>#U290Llc 0aۘOaB11 Älc>ac 6PTma&L3Ӵf?bc 7|60 ma&4hkcw~÷r|S>W4ש)HmafƢ:wP<s|sG|gJZ2>aTdcKAjH ac)4z"oaJ[IuϹ^^@! h,ByQ>1* "'H1 8bחDЯht}r4l sc^+)!D *lc 01S60 3hat0`cp鍅lc 00E%a„pac |60 dc ƴ1 Älc>ac |60 S K/抖Mamm^lmc~0 tژ[|{W赊K&n]bƼo V]$;S|mK&{Kz= lc 06FuIҦ7όo3!A{cd~##ӻwz=4㰍1 8>rh?b$ s_GP,ZvC2E>l:1agi7ޠ a~l,`cpu(*60 &0L61aЀm'lc 0A8٘c0lc 0aB٘ڪv`c 7|60 ma&4hkc,5ޚ¥TkMjK1 8XGFM9-HQ}a9⭉o~ Suaj'71Rɡ_H/·6F?*A 9ZQ0̀=%]6F1 Ē34g Swad=FP%:lkaۘz=ZH@SaCGmz]3ǐ2㟉^P9*$$r^BD~ >acp._/dQC1a#6FwԁQw`cp`oacpu(*60 &0L61a ltЧ$0Lf61apm'lc 0ۘOaB7W)^S;jԷ5ЂzMK&R0̀go8~7"G{5|Ugacp1ttkANǼ1_qKی70#^ntw-b^b1T+^,Bv/˂60 3kc6dc7֫QL]aXoOa^¥uՊ:S.3QZ|ަ0̀CuO6&/`W\QE yKC~[C&pDyϰ1 0icCggfPacBO @X?maff6֡dm ɵ 0L"l,pj%mⰍ1 Älcma&Talc 0J8٘c0lc 0aB٘1apm ,v{Iii?Z'a `@ٚtU321 yؒ˖o>S#ZGJ'y۪Pzq[˨L/o46tj5HO&֫cz<^Bo;+j~x)zt  z7-^2uFhc-?]>]$^L Dir,,G G̎u@&rL1PRZjg1 y|:Fd$^;Mv|z/M eId6Vt&% Ƽ9aF*FKքfxR`cdIt6F>:U 1It3vc >Ba(^f/ %<C^"RƘdczkMH=b*4Oboҁ<$J>{ҷ=dUfot65ސS6t\z!rk=dcLo}1|\XMGd׮`uɉG&;%<f2tۘM[6t@[ͼWbc"CN{6&k'bc_u {2'}ؘmazƘG<&3PTmlR^^n#Oc󄓍;1Hkى;v(**Q0Lź׬ͅy^D{ۙ3QWxrss333 a|N6fSTml bwܙZ\\e***H;tXIeeezz6X[n۶-??f 3 33߮i-ݻѭ?uYYY`]vjҦ,݋Q5alcm,ؿ?:.8Ɂ娑T^TTFhdtmp*5a16यFS6FVWWާn7gffwR Eژxozɽ݉{_*ʹ**>؇wm,L())7|::m]ľ};vذJϘLJB1sDm,@~tm,)++KOOlj;TFDl^0=K{1z/@Lrͩk¥ax!LWCyV#bc}lc!Feee U˷mۦFAwl(,, ƆkzfOOm3`=ە ]LƼ' a?zI ɮǨ19'C=*)lc!Buu5\xԍ/p^V#fuf8YHtpAF QSjjUkǤT1!N{1 LHĪm?uW)vIp81sdԯ_B} *)>肛m{@' 55*'@IIIj' }Dwl2=XB_Z{MKKWOWKMTRLzo7{;{ lذ"11ǻ8öl٢{ cUVZ>/#V'c' Qdc}B 6vtm?w;ծN4p25Leo}vv} 333ܵkCM5.ewٝuBv2Eꪷ;X 󱍅.afc܇I)--)wܗB r[z~0es&%JKgTRҹOۛVi;rtfgf姧+%'ٲ%g̔zfOEEEi\YVV}c73)mgRZnrڮyivJNKIݝ;5-/=}OZΣG Bp@8>G1,_e enKAi+JO}6mܮY<}-WDG๛Z o*o߁!C6֭<̌uд}7ӣiإM IbEW6+-٪h5Sh6{ca2N)7w}؎;"Lқ Ӳ49uJoW TTT{'`DCնLUK&ҨY.kBe!KePs7v)[d' U'#?'crN)99EK7 &kMW &gT-~y {SppuՂCݻwضmۆN0ސ?aQ6JE| iKؔ]HEkh 3!K8٘c0B_N1٘ܡRf1NƳO/m,ٺu+llÆ 999&3](<ݞjg٘xQ%a>Xgc%\zڤ.Rw/xK^y޸ ?uƎ|v mSW&/m̳Hkz6u\bQs 1٘kG{Mͳǃ!:vHAfZo93]EacdEO\C7`]"N o{YJk/6{}HgmRwl=gNjyN$ƐԾ!JRW\jmLcsVO㙤5h}r_N,M~]=cb҅G. Zzzok<Gy'QX12Bĭ21,9偐6IQ ac`i", 6&sdEؾWvpPYL6VHU_^rAy?Go %LK;I\plG׷#m<qCݱ1H!m1H1aKu =´6F%uuƄ{p/t˾85!my eVjcH$Ð^6~R{i<kM'1H1|K1 17}2CtAZ/q:RNog&PL; r|)ޅ(^(r*aJ(Ww ^ h8pzclct)ƄyЧT-~ƺOO5 xC}&hQ@?HHHoZGyaVf&->)MfYE} >ޚx:)HAZȌZ+O&0:RqX>*Ӟq 00ꊑ3^mh86(q]^{٧wIɦT-~y"ӊUԂÈI6aK1EtlrlYy՝VgYǃj-߱}{fffAA}=5ꬑ GVcz6F"cE 0ژ[ژd 6 &N˂7)Dw wڬ!0qSXܹ+_15FUdO+?aZ _~״jꥪdg-Z*|q%~OͼGci_Z΂t:ctA W;pӐ i! ʧF( 6m,ZK$Mœȧ̻Fl,~=6dȤI z+-6v^|U⳱g }GT<C***/rݳKRM9@a:RSrԞ='#'˴*84!)!a֭MlƍM9$mȰ\̔])9);S3wZ-;5#JȅRJٶ?)#jk~A6RX]]]}}=j*&|̨{6}MZUlhh_ ~זF0@? ߆vi 946n܌QG zOBGf7jjkȽUG K$$\EIHP 4J9LY+QQ^uAtg:L6рݯa *iiipW uVHg%sNWFF&p[Nt0C#“01?ltS۷ohDt cF*FX_ar,:Gb_&ƂDAAA?[棣c520? S2`۶ei(S,iWE >2 -gr),,޾};\tQB3zZtgc?裁2tL88Sk251xxˑ?sEȍ0Dm2J@/泥B8X 7*X_&z4OBg7u c0V!^ҴZY4vQYhH`*z&@[߿^rii)P>Y-!l_&z.u6G{"oEZdGҩEF9H`X]]k.ݻѦ(&ge:1z7&wF)0J\."_ƷT\i\EJ#ES"Ct䊫51N+@SC|g"莋䔅=Fyt+D2j\B%uCO$\g ~SSSj=tX= SZ *`LC@g 4#B7F 6=%>&anw +$L`&f4rA,EZIda` ???^ӱH6$;:EG/pdeeaQ9/y(j[CYQbC!!Jci^4,b@hי*lcgl=:X$,Ll@Z[email protected]^~, 6 kj8XZ=C9Xvjk͛6lP^^5cx* 6_w8"zfHtowq"dj8q%fDlv:Z$uQ!.3$H(@%HP)-' âu {eY^7a=`c'"?`|[0g=lnrޛ\H{/\$B/ $$iڦm @.7ErfV"b1 cky{fvvVJڕsΜ9sfym+5iiKKK1'brDJ5Lh M& R`!H,[ lǎ])̾uv%/NO]z8(ǻ.%5e7Poddd`2_X LA֭[WVa^=u u'<$5c1ݛ;f|/ƿziA<op?dqx4荄["ٞ*fXRp }BxCu`k4F[ká`Eze=a-Zr%1CK]\} <!Wp}nf;N;j]^ z_-B7?>\o/΁F Yŋm7iz^M6L\= c}]`LѸs"CQ}8.\0Dgi fA"z7XCŹZ~ %ZՠB+ ,c0DYʫW3jZjW1Ы0˟2\bظa#Q %%HQ5Rs3֧aFLߠ[߸ itC %("nvvիSRR WXK{V\NU @ _UZfZ l U YaM;z#x ޚW.YjJ˔/ZrޒТ+}sbVEwnsm_] ټy3n+6l,|saVrUHA0k7BZne.d+ǽӝSlEVd9I +ѹ.~s2$h@he&gcCmmG *:ƒZIU@Kj\`v@lCC* %F`.q![V78._o1FNeJX V/)Tx=>]Tu c03uuz"a #om=ڊGZւ%ӊ 8e+ET> ŭUBEl)bSp߬5{VRrRRRԩSCDB|\B<O( dP!>.DJTxފ6@kIC-%&}Q>wpLu !Bzҭ<]B7>^fK 3=\lyL{tqt]k|:f1u+B-|C֦lꈉ4Hnq15%1u_z"5mG(ڸ~c2+*XHr QuЪUtV?6[qcxQ1c To1ҤIɎةGM>?ӶEsd/'a1^6pz"a,==:D?E,D'ĶL: {"W 5pk˷hdK~5~4{ZZZzm!Lx I3mڴ3fSRL+> n*T |ԩqSi8ijĤ8ȩdXAup)t tո\)b刏IVRB -tYʤ?9 \B-Q>:҆䏻fV'g(AA.&z8=2rWo 7 ʕ 3sV\\LIO/ܶmkRS lϛ~^,<qXB,*Oo#f/{wzpL:~$^k:NR^xՂH50j$M칔3eE+P2= WAMINmdeexݲ1utIdࠔ}P6mZDD4*O45)>)UIPC؂!˅qHH8%qz\fLON"FގOJ\bZo[c$qp.U.ջ27fÁwbgl'Kֽ<;,Dy|=:3RCE a$8@<i'㮫BA&vͺ%.^8sKwS5էqN#pT}0x{Nq0eۉ2jw 08|0 c)F(A):ri: +\*s()K /x;[C鏄{s8ս{6d=eޯym>PS-|nNYXbP`Vӹ|‰?Xx;-{6z&fӈ|4{0'.~ME<s=;tlBT !Po8M-M*=NLqSɥF\z#OQ@8i*{-DwgO238'7auR%^Sh#[+ohɛtE{d}3߰.I?bs:s.A!"އ#EXR84b:>cCh 5/3_> ט~cx†>;Qs AbPR<yqnD[:t#ȇ%C#(ծ{>G4}'dׇ8X[v cw߻1Sʭo~cuyXճ0;>Kc/z--(׿N4Gk>@o^BPﷆJ0Da̫Øi1N(KSQH7{bbq_{YcjM^ K4'Uq?Lԑ(؛lڭ1SÙ|*ұX>3>KRь?N)+ c0:%UV b!!.iE!&a8D!!zR I-̿ȍyk1lH-lж{ ˜ #Ӄ01O6|BD#ĭIApVjbζ< *h-%haa q{!D#ɦ܃T5-oW=vc@C wP~Yz}, qa cMɶߍվ/hCƉ`|j`\4f|UrV_'RyK$CΤ3(E1X`[_8QQ1}&Q-_ppA筣@Rcv 09 c)& E0,1D#,;n(DedHڰ{`7FƎ[`Ucǎ !_ crC4 $P>,B. X!CC8<a cW5FE:/[u,0f/ Ve~rcĉØrcʢn &_1s>{1=\:c+SEV͹TOĜg+k*=ʓ ?+ 4f;3cTUo7u3 SUQTa ^Jm -gUa@UK].n,L u vca!\Ƭo-C&5ME=cUXsV w7][]2Rsz%a(raюay mןusԼsn?̼3q;] $uщOQqJqe2D s<곹[s˭7o+,t_i 8aAUĪtb+g9i;ʟBTx3j!U큖Tz䛃-EEeuuFII-ܢ>0@R $L051F- Eq^IqӒQiS⒧zb|B2 ԧ gO0&`O¶ɉI+Vj]r;񎊝8j#/ h>%(kP";c=aTqqH߿u[ 7\}L]D)æ Ũt9n,&n CY5&vQ/{SCO§0F_}P c8VOp&9Ov ;tv#L~Il<*ʛs<^G};Ńrmؐoj" #a *" =i:FA:]oL֖Z64UGKZ FLK/DKN!TRr2bN2Y}'LKN"Iu3%ᴤiӓMCJzCI?``zw5jxxcG}*;'A76b=ܢ랺A7>^^m/!*μk &O dO缲5[Cԟ\7яx뼍ކG%f[c(7 l7"/GEyY7nCs QjWͳCjw4^~~ttwc_Jpr^Nr }mo-,*<Uo<`ƍ[l>t?z&)}ކ1rUoN2l%-+!٠j*h[xsI5+Cq~U HJY Ue.$N Wj.=/G=|n]^VQah{v"er#apt:mR2ݜT\Rb+iW@Ǹjj[ 3Y:7=جP(-(C%eК)xC\NUo஭q9ssrrs.'1A E2ok<ʲJ:]+(/.ؘAgWS'C)@j́ iD,~{zoxXjYL}. tWR͹! Nt=E-t ᱅ &\QkOʨ@V$r(JHЃ-E!3"i裣\rZ36gPu3 x3::Տl@ F0o}]}WKhdPV7ةk5{FtӦ5Hcޢn;QjpBjTgR@\V[·7%46[XPG?GA'RTTe K38@jTNIIAl'^15Ì gt}-Mx큑 yZG5 ?4oSӑ@N'Z?]V65ͥ_꼩(%555w1zq:u֡9Q=]]+* qwÆ D㗆 tF#u|yb>ݺu+2<eM$zG7:VH!baFA5[P-u}u0Tjκ1ieggsRQV***233׬Y .tI_ǻ淮t)N۠CRU >e  R^M,M[XX3]1 a `VҩT4#OqhЫiZjSe0رc^-[+ ˿ UQpA9#QpO T }Ԫ2= u4Tӈ˂͛7WUUYۙ쾼|ӦM֭ӥB{*E jd-Po]==Bb R cWw)"s`R-4SS-̙28bbcOgVY9Ϋ*++q& w9YHIII"?"H` B.HEC] cu{BJH$7FB8` # DLD5^o t>bT#!z!P0m `;|[email protected]rS\\wuPEXd#y -).ƛ?ZYg@1+(]1 a* /U  &\$0c4WSSq/k Q:a}>  s0kvs),'PgB zk֬F}b9ba,ZGxԿ xw-E8"X; k$6otׄ0d+yiBAcKsbiV6 ]TO#РL#*++_ǻ,//Qm|_Xǖ-[oߎ1^Ulܸ7AװN@իWD*V ֭i 9ll /H#Hfvp|&/ xD5 0™póGjj*?L<0և Bًr媥KbY]]D<I,//D/Y7|' *uﱌzLުE-YX~;!_OϮDcӴr5Ͻ 3p'[1Çٮ`C,X07\>K@=ß~=ڑ0WY~/Q>ܥMaBDEWVV566|k^Wj7{P*UˏWS[񌩇 } Wqx32jGgٚK>`Bb4bLm^ aT eզ:^{ i+TCat;Ђ)QBU#Zl92CkѴC;k5kbuY OD¾]!aѪ@r<[͡H=E Yr/_ƸBT|P} @];0Ž̒3́.| $ݱc粥|xTǬߥ9-Q0f}MBDjUʒ%[6441u.㍠! i\!Hs]io H{:cC*PG˦+D`6+">X¼N;gӦM ~(++۸qczzziiu+WvB z֭+VXxiHZ-!-^d2L ˖ĴT,]2tNYo7co4wކ@v^FN.}-DZ4oiś +WNQ?hnּii$Y(_F6@ε.mݺקܹӴbvSRR/[QJcU%x"K PSGtA$7jIIqɆtcRS8iiӶdn8%7eOZ~)]X(..FHCLECLSD!j._6Z˖/hK/c IIIӦAIJӦO6cXVyuܥ).n{T|Az{ Wc橧'zd}wp P mR˖~,Rw}FFF/ච;wq$%Ĥĸ8ɣds@<MB4̝;NrxC :I ,ɺe+7kv*7|IMpҢ~|x@!̤_  c}]t:|I0DDY.)*UHM=@SMޘ<Fn)Dӧc x衇u?:ok.*ú[ `lūшNiDiXhK8ZE JqOv1egg(ԿRؿ'%[Prbix$p$!x񲩩[XhwB^϶p -}t E[dB c؅>AaLݻw[aLPԃ<I^cg@Yp{ Ϝ}H c3Jv=ys֮Kӯ@ al _EX ˢصo*NMNbϗql='to:M. sYVduF7 :]U5ZL:;v}MZZ>F:!a)ԮFأxk~x ׏{8Z%r/Gºsot>0Eªu^|X8@gED[=Tvgjs==/r地;)Yٹ&DQ63ḘF*POD6AvEcr.QPc32Cup?`z'G?+RSOnVrrru:ƚ[A1hޱ2!%4r`}ݒ<X]ر<\Ɗ|DX?a c OOLzWԔwKpQ[BW߶~gBۯ>H`-Sg<k>8(یOk3?wBI4!ѽ[Q_BԾz,N3h\Cs.UsG_hʍvՔni m=csݚ7<?jmiVGa},հw~~d`~'Jټ~SAS `(yv*DtD /U5F }B7<\ytW#P%bZr?E1l6<>vدvrPSڸιꀿ;ihYez8WCKHli~3G2PX^{VhFElJkP,w4GYu?DDl1RwSlaMW"Veo-_\9gE26d/(&ƚ E1cp&HvGs9hbdw0&LzwGz cVݗϻ1l̻8f8Djo܋BD&d)8& ϋM/OCh 5o?eMzWoY!V+{ D51 QAˋ9- al_(A96AKuf{Y};B k#n a A'!  kEw|lưD h Be<T8yMto:D}[GSr9*Bx !!]O,06yS7x9Nvx?/@a"Gg&EuEg( %d cH 1B<0fn Hma c.`j>ꆛV"aBB4B0CUȢYlÁ41lH#?Z&*\YUC\zU;$5qƐh~/ ;U1{X$ ې0ѝ蔎_al2g0*Yx8EH6hQ !b!!yūKxMLD!.E/%*ƌ UWs0 ܿ{1DCPG7a wWDP[߬a A%ǖPa V0gc5p[’h cZ`u ؆sn b-! أOnE>nDMBb^Tc0+k9KC1c7v4!҈^-_쏝<菊Χt7UL50򖏝06ܘ` ch^ [!Ae;r3 ]`؍oZwxdQx9;r&,3Ɣ91DAApxO=/0@RpcXARՐEjii1s"*6P?*|a 3 cz_į;ʈjҐ1$ Aa G^"36.=c6EZZ1tOcƌ@!*#;v?>˹ vcU0vV!wYjQa "Q ݑc\fkv&BX` cn,\t͍u:zokW=cVa4[){nݛN6@Nt-3= c!n,\u|c2w|: 3fн锅rm'\0l[ں~K}y݉N}7p=}d֬;SwS6na %]]2?=lk[Y6r?\cH'***R IIIkBnEt]p[p Qn+fLn-8|X y@8p@aQMlڔ1m4}Hrr򺐟>:tEqqfV ^c~ '|Z  cB05YYYo  cB=1555W]!\HzEwØInnMtFHzErRSSKJJt^HzE/ØI~~~zz7~D0&p1Y8OL HzExØIaa!Z @˜+(mO cBXf͖-]f/)--Ŏn Hzŋ`tٸqc^^Ԃ HzA;X۷oOIIq:ػX4AHzN;.a!aLK]ߊs{JVު{oplTsfG(!r06)=?qcHB|ۆn=a06ԙ7mOC`m9 N70&B/06Ա1ro-:Uc-u`5|ԡ V1Kδ[--.~{=Şgm{~/tAh$ ula"SipGH=:Zp 6D}1|Ec>WT]z>p)}_f Ԓit'5޴_8B١=v϶"!1:>!!=>ZFC 0&N[7  ٺ9~D mbG|e0%V#\32˩uϐe$w0`(U0! A5FxC3m~dUWQuƖ6-HDP7 cuȄn Tk9ݛ5~amnY$}C=c`́0Fk?%v%1*n~KSn,M*'s:ƍp1Ɣ!KEP(D5=n]ču,8fu*VYȊ ǟ 0H\>Y.蔛o6Xy{g 4Ƅ'zчm3u_먣ZhRVVyιoZ(df 0HrmܸQg"\銕+WTWG! `E˜:1TUUv1YD D.; WQQ^SS55xA]__ B:4ɺ֭[αSqfPΘiA c<Ac@%_=Z1A&EQQQFFQЀCM,?Dz͛7s<^" c f$*v90YcFZ%s0{:ߦ 0x/j%uA7],l˖-#B!a, E1zM*0H aFYSw.ΚVaaaVVVii)E b$tx1#UUUfA$E9A9[tJE2fI<AcvH9}Xj?Ak0_ٰ_Hp wp˜mM8mӹP~FXtG!ĜH=Q}`,0# \n7aLx)BUT=?D"Pk @RRRQëLxU-a+VAޖCh#u։9~FXt0 |d9̨B$ Q_MEfVa3F7Wi[mAʇPNT-jbHCB>r,ںu+*#*p .ؐ7ESUkRW+͢ X%L cэ EO( P!,effcݾ};t[í081Jdϣ>WVpkT aYTT]VVFEuuNmp1 fYVKZl5kPvUځtX`p:/B a,dL.f^3%6z <q+W?>["uaq21,!ʚMT!qZKuf-:+)-&X3~aW(r i@ASLpn` -Q5܁*,,LKK !Hn|&மs"VxNԫ*ܾJB)h᪥[6ecVWQ1\V@DNࣿau_EfZڪQ>oߚn͛7[~ . ! YUB5*a\PT]"-_U0ڧDngP=&9Ȑ\ B0xk˷zދ>o33vg!:3g>nig?pyZƩcVÜ>O]vQ宸{;~EƌyXYci9:s3Ϻų.zv6ܲ| x}gIL J3g<.8‹.",.| ߅^!} Pv!_SQ1c󹐄.9ywCۢUj 5TsІfV+n .8KKIۂ]@HCv%<|/sOee7(覴w1qԭ-&)dc4Ygv͎:;Nszzeat r6_}yEE˓T=ʱp6goڒQRNSPVݩkǰaða2@&(b!u ހkbZTLuQCn#Fq0`)1=nQ<Ƣoc} 0qǔx%$咩1:{cg?o}pCj8sz<x4՟<\72bd\㓋Դjjjk8~qG!VKP?Ge}x| [pt+00aTprNCԔɱQב/X1:@o^B0fd[[չj==Զ:t!@s#61, Q7b)6/ z'b9"5aÿs`:XGubrwh/Ço8P#vw}K>oj)Qh b'/haGƪ  ף];G˜  cM}SQlDil%VznSvmC\^hj޲NӿW߶bA:ՆVag;?nΟVݥFgoۿЩG)KV+W_p-tY[!nFZaKKˁO=?N{VϓP~М(Okl%V wvoz@?iiݽ3 _5ϵU܅[X kZ}u8-dQiU-5d֎25Ј:`w`6GuAH'ܲ>N<9&_}d-tY[!(;f=s0ijx?XSoٿOVyjDYXXr[U c " ^+c-G&DIJ?Ci9x%?UB>}q8{el :6vpVmY̐Ua=dޜDUt~Ջ-tY[!X7|qkڿ]O{ᘵiH_4\06kzGE ?a,fDABCܘ$N cX? ]ih!tyƬ:l#RSbGvP9!0*,m*݊ y$E7ޣnUNh3Ri "0vy^hQXxABL [L:0z#a ]VVa#a,q6V_4%Tg|B}4?1ԧeuz/=MQh۱k'8np$)o)vZDGl#f{SmΊ%FO=wC]<쳿[O)W8þp 7*ՍGObXE۩?HZ+c#v~_AuNFF5,uKsnE<ƢZ|{\5f8GF@#=4 G<;˓gtm_ZB<|>lK~ux=<n9aĽ'{CO%9i&_z5NSm߾k=z􈑣GEihGĒ4rHCH#Q45BU5r448)tMUoQI#G>qP4z4 PeD>456+ں5_[Wb!Oꖮyrbq" Ƣj_vz<Foc#eݍ$ u&Rȹ3aMFOz|zP_`訄v !U{5KC]hiE=ǃ:v=O'꽴D mՁUƦ;֯__S]vXPXjZD^L̵hJ`ͶmtJN0)_m1㢟Y!# qRDju^=>ixjQHkcu<.wcG" {Q UZu(bQl?ZZw@HZT[PP[$v˂~y(G: ǶMV0z-^k4BUއH0 d` O&z ]zVaL)fd#Ev GP(ڎ*S 8A,YGQJoZ6C ݐĶ cmCC#lSYYyYY L{ ָ%Tn°"aLBD s*gV!ӹv̮vxa>SdMf@ (!D$ CT\ W t°b:-0333WF$ BHۜ@.1F l׮]wE˜ 1!a+zrrrڇ1!D$ U]]]SScF˜ 1!qaxY&55u:/BHD,IҥUUU4ʁ\yA:F˜`߾};f|8lzuԂ#*..A:F˜ZBg >Q8Ƅ ;c W^y >X;LO۠" cB)..?L2wʕ$AHzȲe>5j>NYp&1H coHz-;X>TgT:6&vs8FٵZGZ:ՆT/8ffN):Ӄ0RՆ%W$&RNΚL]!aL Hz-QL?9G;%cLfE/+F&$ƨ(;Q+#жZ[}B^P GT8p`_p*j ;=e6:^:*L#!rKyX?zk#VKk5kv537I3ʂ>nݎOLl9~'oyȢڎV&%Ʋ$c*_{VH1a( aL!;@1/ىsB f@Mäݘư-1 0kC6QY{f\>Gp!-aO)0n(i~#!?n?mׁ {'aL HzH_CLҩPP1{cdF:k$ C cBYbڇA4$ =ROCzX]NG;нA1礥ϘqۭL"z7B UVK/007o~YY j$ Q1A!0& D1A(F˜ HAnoA!5 ڗ}  c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!06+uNA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ P:' Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B D"H$:0&D"QJ˜H$XDZ#Ͼ2d<duUp:*Dll"\C .[![ByV!e<duUp:*Dll"_Ǟ|iqacs~sUՉc1&5'FzkFZO9Q;Ff #N8~' 1^=rܵ3j5h T$蚑Ff4jhiulkFxYO9;zęW8Nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[E@c~E߂(d9yտ0cgN:qμ~O9zQg^q˜:J8\DK75ahXrkJGrb'iWF1c~u'jWs nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[Eݑl5{'^Zxek!(*kUK1h-ȉ1ʢHEw~u'“.3~qaUs5z0WWx3SN=oo8n#sҙ̫N͈1W闟8]q9[N>Qcq'qZ}hX>n{% ؈Zל4c5\܉tc &ӯίzY>N.'#[ByV!e<duUp:*Dll"\C .[![ByV!e<d_LVʺtbVO4\~ïXW_39:c`6F޴w߻&x~ȱ,|/z,bdWuBGdNtŊ֎Rogג/:>~1q5dv9N9y3 9Ѕ?q_FFN}U2u/?|_~}DxL1k)g&17̫N:μ3=~so8kO>>W?>x∱W8ˉg]ukNwͩc97rl,{bBByV!e<duUp:*Dll"\C .[![ByV!e<duU|/ ]12۪!dfN(.w$ke. E#Ǿ2,=:IDATa+mZMN'`ta7 ?Q&ؗ 5ݑy}2VtOj8ض>e6fV*w X̽3]'6O{_sx1ן|an۷7__g%>E<wf.xጋ&y</w9w\vM?SOdf֑x:λ_{Ÿi'߼fug༿GUyGw$kis=Xl"\C .[![ByV!e<duUp:*Dll"\C .[![B!.V7ꨵvOO0Եn<gއ_1kBzuUboi] f؞vW5uݕi`^XK Ա췓cU&*[f/F5⤱N?Mh呲L8y̕9׾mn'={3>+O=cם0_zq]8/yzW O7wj¹W>z`:{=3g|ziy:RK//μ1W;m<sNU*J?+jCcHel5Y]1o.+ku_&v:yˊir6VUUzGR6 3T%AeF( j|aQΛNUωe׺Y*Ǯ߱FH3ړrC9_믧>|eSŋuMϹq#μvm9G{9:r ]pU7,y+ܫոko<-Ly3.}5ϘvٓN?Gbę7ܫN: r۾}D"H$DC\]l߇ߐu͕}rGzBs`ДؘfUpPD6 D>|üp>]1càruhlhG\hY]V1axȳ9Qg失W2~ c&Ow ;a#Ϲn{OU?>sՈ&fm;cჿ:S~w֯-v5꟏iNċ?z̯Ϻᔛ|hi8;1&<i` 9a~A]xCy1GvFβ[wE"H$DC\.ʀfdu6ud3g]M~xg_F?ixԱ7uʸ^?z'qbiO8gԩȎ<Ϲǝ&;gMy{cI\߿rٗr'r~Gvoߍ<~_'1akO:lI㯸+O8/>?7g'?›Ko8ˎ? ϾӮ;+1c"H$DA1ՕT'N!~ ¡\w4w?Qg_7 '</|oǍ>{Gϑ/9g0juN=n&pU߹9G~׌>ʓ^s9'^yOwco^~ܸ+{3'SιnY׍ȱWs%-M<iܵOu6rhc뿞z֟Ν0c.\$D"H$$ENgElm]qTFyͨ׎>g]s+G~7 Sն^4aX+.fx%$E1]ԕ> BkGv8z\>W{v::tWx'PMޑH$D"H4x$~l$.c`cEOr'}`D\X׌׌ JY5a#¿M1n"TRv_lμjکmTaxM<鬉'u-ވ3qU'Ү5H$D"hHIc&`4I9t\UeFj? $2N^Uc#NF[^ʏY-lưV}NN+GȒ[gYq]" D"H$ *bD鱆bҕZX2ieTSFK2tqվ]mh$dԆj[]SUTD"H$;śA)vl5;m[N'n}H$D"(J$~l|'5u.VmeorGVeH$D"(z$~l|2Mр+Ď٪D"H$DѯXss2>_`[wj)y=\*̸qOVo5^]gNƥL>h]BdQUB|ȗ"H$D"Q?FvwtKMA}Ǵ/RH[BmV*ve|E"H$D"Qc?oϔʽ[I*f*T~vyvEnw{YW{P|;%h70*m GM v*SIm4`Lw.vb^U+-D"H$SOm Y[R}g *4nF)k.3E5q-loU`/ҝYۦPe0z^]ۥVm+=v?2_iH$D"H k׉"y qs k4Q[w=g ʲ#G҂i'&vRNʹJY@vhTo\ٶ(H$D"H$4uqR?<^Ow|8~$ŏD"H$DEWZ$D"H$EďD"H$D"Q+ȏ0?UW$D"H$D}-/c"Q8K#PN+taH$DA=n߻n;n}4]Ռ ut[}Sp((ZxAIU]cZeSAW!a[BG"v D"H$uÏw㖢ԴmN؄B<m6@3κ{[ZC"kvBbK®?pӆuTۮcz! ďďD"H$Z"](3 6nmmyL߆e;Q5;:.cΛĶ!Kv/7> ~ᤤm%Xr˭(autscG l7|{T%c'f /+WgM? E*s܏x>t)Allg]?哓#sBKH$DA1]W7py[oӑӉ%pZ]l=J6`^VWf=tRi{ǬmY] ĬB_<gZSpsynW#(Ѽ'S\̏2Z 2hm͘B^UtIvBc-Dh^KZedYVM7e\tlYm+c"H$:} ތ֢"clB6lSWA-1mj|K7 QڒMKR:t-V%Z󸚥tS|o ۪Pt׆?>Q&Y4T9=^i-\hȮfLaUdXG~ j׌AhY E+&;ڌYB[*=$t]ue)nyJ~̨N5KSAl;IH$DA1w?qkhqֽݑہzpY^PD~nmK}66o膘at:o֎:do뗔Uf:Ť$ȽK{0cEmU'^ 9AՂC{Lg}^?h&l13aBGymn ފ2QQ:D%['!ՏQIY2yi|rV57JH$DAmn^Nĉ㡫]^[%rte5gb1˼KFQ,v+٦i$m3crܷXaF5cd2 ,wG^aeդ!kB`)lUHcݕ-?^D"H4(ճcm2s誗,ȎAm~G==DU>PS #,6[ d>{ezs?9KNB3c?~KH$DA(%P8;FmPĀ.: @XďD"H$?&H0<.[E"H$ďD"H$D"??$   %AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AA!_SahZ=B   cCc  Y:AABA   D]}%O^0լ~aKܸ(in޳2Qfw=v[Ur%]:s.lޓZVF=j?ws_yc+E!V|0AA!Sf,௬tPM.0E%1ls'ƈAAȢ/mrM'tUz0s?'㞛+k1AAA,zչL.[@/7:vOO0Z?&  E~L4AABA   DdžAA!?6t?&  i{an@   D"vSǑK   D"c  0$?AA!A(~l{u. g]n>,zQhYoLwN۟jď  K?36,{V&Qj^37LX%~LAAP5+ys5n^5In57+V+kcT򄹨Tp1ՌB=Zw`D~lWBAAL{eNz0Ț.˚:"bY .4q[؞Ɓn*G`l̊1AAAt5LdgծC6Lo'e3m1"ec_l٥`~ұKzYoTԀa.ď  [L,Eۉ|ď  g~LSď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c)G%~LAAc1AAA@ď  K?aKxfsJ>g %ByKg\I󞔩F+AAaHХ#3 ]:ۼF=Y<yyœԗ.urVHq .Yv{a`m:vQcc@5^զ?A   c&)2]۞0UF Xbfjɬ`x9=luMXZ&iצ?\9*?&  C.Uhd3F&G^|f^թ n*ZשFdTH/k5@   B?fż[BX?&  C1e~P ď  gDŽ>E   ďE z/ݜ1AAA,ď ď  Bd!~l ~LAA" cc=n@   D"vSAA! ?AA!D   cJ<al@zCtsNU:yOTޅ3l쫹y'w6L?&  Cc:#`.q<· \`37:c  0$zu(~Ye7hk6ԨxhQ5u3Jۍ)vw)kǰ-ZnU칹[0mB;L􇁦Gʹ6%!"~LAAc~p1=afcQ1Avd^hOJ"X#1VsE.Q5k-T5>؎3@f>mނO]AA!AH~2TtoJ.{P"=r50xZVwՌ:v?40<S̸|T2njoFY@F{5$AA#c9?3Æ2Q &"ݏ?AADď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c^ ~LAAc1AAA@ď   D?w=ҙhnWMtG47Y|17tˋ\ͼKz^n좏?&  C1..EN u.Ԅ2 $-XSff f Ǟx`ʦڭLVPmwh7{bcYǂv7+k_ YWuYgAA!A\f!]1j6Ɖ}m[ئ}2֏mnS6gl~>T!~LAAcM=ca_؋ <;0H;c{W͚? ԹkY ҏۦ̸m^e14y?c   tE~П4Q'^3?&6ZÁnKÀ1rV3~!}R3z?&6@% & c9x7   tT拏3k_67uߞ:AAA:@~$~LAAcCc  Y@l;tsAA!?rc  @ď  @X"~LQYYhqK/guwwnYSse% N~y_ɓ;,W47Y ?,z3יC i|>ItHj6Ў:@VEp!cې/O^ď /}puaZ_x1t& HH~)3n!)wҟMZ_w,6Lٳuɍ\̀edq\&Zo?&~L\6!jWFVO  #18a_w=1eWo+ɡ[L.*U4w5u?~;'  nM )賉PP<N.ښ:.;4! rf<DJ 0PǴ oc9Xu:Tܬfw0yusz[#/~ѲyNal~̸?fMw1A@g~,ƿlk?PoO'Z%v(Eh}_, ,7R~5^ď E~{R +Ə)륾DžrInywC?FL;5<ڱ1VZl=a+hsi?\e@rNpx_[ v*~LA~ ?Vύl(U-]x H&u[[7^ R ?pI;TӆتcSuhGjj[lnud̸:ɿؤ&~LA(c y'et~H"~L0Х{B"Dz NRj }5 ;KA~K>,ˆ:3=~]̛iܸ_՚>.W$~LA("͏ @ a ?B\Hly4MYqm^oXwǨWTrȿUTcM<c B$#~,a7{ ď Bď 1AZx<ȰQ8.3sKYYҧOAcCc0p=KfpĆo:ֲJ}pe۷o߲eKZZի׬YiӦ]OAz1Ax<XuZ;-!Y :M`2334>v؊Bۍ7*WUUYYA:BXbX3?&۷_e˖-al z,Gzz:ڬ czǬU^fdd8N]˃뒒 m6^n[A*"vStGa0K|'|\ه[OhCqq. c&4p;W.((EQEmm-N8N ^̴4x6XMq\0rMa#~,?&]B+==WpbzuME}CjWTTA^ <n`sssaqສ m@ď %%%[l6 n%>8ק~ \ eZ$cIUcé[m F~y_ɓ'u577+~Qfcn&w<׼ҙ[&/F]uO({ 0BknO>n#4+~L۷!tB /٨`ͫ~c&. $55T mpBp* iii(A=+ 'es%]l+(UrYv>,zOFKy7.BTG.vO^v}j+6 Pzuv!~ >FKOO~k/sq+7ߏYy+Op֏Gfdd`TLa K~ i @{W2Yw`}6f ;xG6ȏ{'Tux.ԻtHda>?ŧ~٧͟} ?&a fퟯxu2Gyy.֏ǫ.BF{QQHPͬ):ܱ鬺 7z-I#A1}[J3 6qF +x2[`eU?vL߬T@MjZy#OSc[nwqq+^09|ohJ@ouQdfff¸br8i^p=_O\+Wt==Puی֏yL?zWI~K?{ma0?c&tfP~?1A X,-W"ײ+V*шW%/LϥK.6(,,+"Rp -[,ryJ0].G ӎxR坬hTBXkǨdʛ3%B~,\ ]'_4ܧrLRQQ_JIIxIdS]] 'Ɩ&55N ײz]ăkn9 .T `Ƹiii?618xE-**˜7?w.?̃ezjndA>W-\ %[(76oa[YY5ڛ1Aȏ >O?yPpYիWWpUWG֭c{`WG8 T0l0`)?9=?wqbYj}zw]Kתk}nwtעk*+kjk;w6x몼}Z~k??>䓏_͟QZZ6قiO聋/}aGzꍧ׬Ymҙ`+^)))Vt\Gs/9uޅ潹Dp\׮G;Tw3^}eza"'hk[&Mv{[C/]60?f-X?j>y}Zs\{mՄ.: {>};ߟ/.>}磂ҹ&U>_J>8o{~ |qKla 3^MH~E cfcBYzɱӏϚr}秪 L|. QW 05짟/[Y^S\\Bc5⮑֮Н5g|{|` ".?񿰰NO/--'kQϿc{w8ZԲ*\\ b-éڑ篼^[p]^zJ #147+67DŽ˅g?gsJwqFa&*ҝ>o.᏾y!{&׬:f16?lD(߾[<Js`'}!\TUUoݺ 0eeggu%Ŷm0}-[ Nե{[.H1G1Qxr ;vd#1(9#1!xb[bb$ G ?Cu>Ta.Q}X п@l;>}g~N?&ct? jjjJKKu'w|\.f 6_L7 :c>,V"8#d8Zeqeaj99 B#dwm嫭Êm>YA">?Ͼfŏ =s?fVE~³'j=mJo.uyi[m{o_۾[|r6N}b=aZ>_G^??6oZު<ɚm=> T A?@#V2v=֗cEqqesrr.vqƤJ;hSӪ??2ZeZ2lXX;ce55ʏѓ<X&#U"B?lUvtʟ4_?&.؈,-mo0~򥛛) >i|w?򖯚ۼi_ܬc;ˢe~Cc _"m[,* `Ÿw[:N QvM?rel_K Ul 5\e]ׯ~,bL}qY;+gUi6f' w4K3=UfQ?zm~`]}fuzٞpo=T/oV/A?5ʹ /66at Y,}*~/ˏjӬ~L*iFj c4~ֿW *;; ?@~,&X,؃NgӏU㲫- cSYnSN-|০;x-ώoQ&͟~)YB؋a.vUkrY(y=ZxLϕ-?fz$mYb`x`u؀}2z{*m13Ktr?thm~z)ٷS³c12+\V)^w fUm Y}D1ub&Z|Y'?(,m& ^W~9+ ?f3}9+cQA~~?f?t bi 1͚+?6JbcZ ?Ì sŠZv͘RO&ݢK?ּ肞SfnF.;QZ߸L-47Y|q۟xS!?!mT`vx3 Ī'557ia ?<C119_Xo}K{ͱ)qiiܦb_vlcf% 1ldU~w~csv_1uNobS1w%t}9Q>ز?u@SYla[1Κpڭ~,plF1UISz c\Y|'hW\XT+ǐ3-5mǚZ84<eX,5 ?6q7f<5:q\7BOH¬Q ;aGJ`:A7rS?۰dffSMM O؊̗lj𔣚uC1cBOo>g&X)f1ZcP~^$QǢxCv3Zw|ql =Sqwa1>`èu0F٬' * ˪J+k*ʶfggA ''#n,M? pK9A,.1:f}ccâ.dMLZ;Anm{*5 i[7n{Rx ǘ~,xAw"ijY=US}a⍫L3f}^(>5xcB/A$.,,|c$vYB\ii7xy2t| }zͶ¢kz~~/.՝5qQ?)'HTW<VkCX6]t[1d9bհluh{β1,x9a}Zuy0OC<Ǎƒ•¡)F(VZYYc Xejkȱ)VƊ@p1E |{010Wftljӈ ?FI,.P/pc-`${ }(m1kM?z;vIU/K+6uyEc?&t B# غuqsY[s?/'sʨ{FΜ5&V/  eN<=F8uxYs232|iNqՒ)ǝ> +v\Us[ᦰ>g;l-zQ=ikA?~%D,u-Ͻofe{5t/ONSY'qɟ:/,:)'4}f{{v4ռUO㯐_!=C{-޺\.d;f0fׯ_|yJJ bǶmPF ##Yyj.AD-;?5˸٥2ifa3X`Kge'X2Ԅ_Џ4hgK!UgFl~*Ǽe۽!f'ڏ ґ 6mљ!γ襪 `FFGuQw_RRf͚|j]>u o]ې!<>7YTB nO]_n4Vzk\;vԹ;6l7x})pBJKԮbC ،1YYY6lذu۷N'ZFi%\^!QH~, d= lUS[5`kM4맟Ŀ>5`6ďY?RPP`|wlm  zSSx+]0'>QzkYP.JP]qֺ<XWO C[[Xk04>d1Ϧ4H(V Ӫ:1e˖ eD%sE ֎뛘mҎ8a+t&5[~&*Pfzf>3?6AOfCc5YYYk֬-E*b`'D(ʃF0;Z>x 6\ZǬU oF~JhKZ"%JU oQJc 3v:%%% /QHὠi0-^Ĭ̘upVcVXc͟ K&~lH(5̆1+" xqX\\Lp l`E<p:OO'ԓPtUr2SJ^JH*kKChSez*΢ 5}ZZZ GqF"Qެ3̅XZ(Ag}٧cr, %HD!~̊4}WUUatݺH<uRDZa kHc 3=Gp>e t dQz7 iFXbEjj*N$Nqe_uC}ee|bsnj?;21}A""ր?fEX배"sCpavHpNuAoQ]"t>v#fiUZaXKiK.ۺukyy9V>6{Kդ޵ 70cǢXF!~̊[xaX*McHj 6]ib=@2 mO 1DR77ӍNf͚͛7íVݣp0?6ig+#="zN,RP<,2AWk"$ -Znm7p7lܸ TUU1zp;ՙ>;X]. ܮKYYYٗA_ ϗuu|Xг7H]ó@,L/9%YE_/A3fkh7,/8H#QPPrJ8a8R8Xkmչ4^#P(t foN~X 3]vt.z:C+k&7s,RXXaÆl$pd~#kM mp6Ph-mmu a*j*`wjQQŋ'-[۶f}AnUN݇W :;j!]>@ D榤^|媕[/󎄰WLx*//Ex/GOvXt)L^7`"ڲe ::%]ԔBp%\g m۶Z /yxŔ[]]s53'RmyodF=sV*NpDFyee4H~H^^?_.m QbWE i0``⤁#*@aG oc׺Z7?6t?S@. R{C d1r!fqܛ6mM=?!?ȎuNF- 5BF׳@!44Qջ`tB7a#*qP[fLzEw[+]TФ\ 5S-,D!$Wi)VpoO.˨΁ g8UD 9^;{+՘ +yRRR=t z^YAM k:x}Wxl 5>hѢ%K,[ qQ</&'u1*TTΏ!K41]~6LA60K%Z WVVV Wqq19 644 j\yC $8*1!YDXUCG&@t*VO6T 5]g Cwcх~,!~L74CW`mѭ oG.K332Vez%%%^_0U566"`c'NJ^:ܾ9SG/C-!X- P9]0i{ m^mK=Pز x ;a^KaMky:su!LA8)E..)F9~FaKཀ-]#[ 8 !\TBӁg 9kj}d0 @D`U>"^)-[ M-b@ރ^„CW4?sڿ9p8k^\Sŀxg%F\,_n-??!T꼅{B#:i%<$}skVb4 0u0I5Oy/rǧZV.oY""׏]M ڡ[@h Or(zPazث_>jd2&說*ӱ`BBԫ 8и;p; ȾYf,ྰE?z iTK+{ sN q"Xsz\ ۋqJqUUJ$]5:oÎթӊJKvxU6^└m#/^lP7n܈K^wfGp9H]RG\!R{\;]. @ݞ:TT`2jNW[ K+*Qªr:Tr54j+=M LeznQD ꕖT (Q,afDDB9H?b \NExCACVoK/ؿюU}:`%91Z>SX]]qa061cV]:[EfaJp!ɬVT1")syKSJ9?]%VL^01 Wt޿o?7С|{|"M~{kX|:(B1":ZAh5m7oZۙP}:T+>~{C_aWTC%Fj޽.q5'!0w*4I|WclфIO?=k;w߽BݣEkfbIo=3gђ(3gB6PSB{Il0s֬\ +yWEKNμY @uʀVsU ;>}w}_0?7/M s<^PWޮ;jkoI{tsϾ_i;?]1Hɝ?TK]?=?9c`{~[3Nt'\E!NE07?:g?Hwg&#s<c91n]$OfenxbgqwwWrqee;Z=nxW]e˯yn/9fU81DSd~{~{1Gm??M/c~r69w~w}l/~۞_;뼮:>UB7kA*%:wY ._á7ׯ__#D>*< ZV>PuB.宁7ĊzoF-ϫjO_߳;~ EWHKU?GJ_jI⑌H~y19߿w 3~yL;}CѺJwEc>tU (s68^!z\?VYYw^ّ#-֖hA[[[(?omEi*J*U MKkkK zGVf#6 Kq60bęӳ.v*TleKĤ3%%'%$'%$ģ0!1$&&&%'c5T< %$OOLmh $aK1ZEۉq ]Mf29>$, TPaZ7-Jj JKA&I^>O]HP2Su{=Z]zu'>q0ǤXT(13r8t,Ee3D *e\.|Gۺ Y0V8E9 w}fK$%wQɏqYE齯tp\p$$dBSDS&0rdG MAjm\@̊w8b7|]UWΥa-.oשl6ap:UUUl6ꢢk!`ƊV^xť%Ӟ?[j8@W$Iة1S1nɑ*]d6w8s |SP뫅% 88Z7RŏE8x T֛Gu> Ë9t .:HSE07䀈aB)B$o}PFo1:c( F;:|TB=7Pvؑ3w \1jnb--+}@H$vvtz%O<ddP4}dxرIq:QkpJJIq $re d5R{ӕQ.(!.))aZ2 wozXs&'?5)ajR"M1kD 6DnQY>e-_\<'V;_ .O9*v0](WB:t$!6>m:ר{FenН<o>{f^z9v"_V^^>ށ7^uw~[_qtܤ̕4ԕM\_a3YaP\ .+D0Fן)VWct/^Dp 6`ҸK ,';'---5%u \kZ*+gKqi1u)ç|7fB 9xb8M6<4PcIʦ8^zeOSuM_5ďE8uBYЛG5k'9_}?푯ߑͭG_~CvЁo:@Zh呏t @#呕C &-Pu y-K+}klD7P~ß}`7G>;DLA[}SgQOUo>#e![hT>#s7l'dee' /Ubοn4yrRr2Yq S&N[oMI.iw:%i n6{=0)9뮞LNm7zԄS>yZr\|RBrۦޕtf$N:=iSfLK>#a ࣦ݊OM4 /!qZ|iIw$'NJmjRoIN@mq>eRҭS<:ۦO8-qj3_t9n,)nzҔnN쏉HH4=!I{e p._O]дo**}U. 3. \QM…cdpI)$_sKGlWbDG̤PHďE\ u{ݦu={LJ<nNr59qKX\"n5gUշmoQqPYSNzEW` ÄC_L+sUw5e˖}c%֦۰qÖ̒r(9LCRQ ~Fш8MG è3Gu׬O%${y&8ӹvOЏ &ďExɴS W@)عŕ rտ{%c_9 OGzv/AniZ -+>YZٽa***~衇.V+w JKZkWͻrzg?ˬ'tUi/}Sϼ6fi'{s3cŊu VCѠʱl﮿{0 coۛu%nlHUy~7~n)r؉5% CciQ|&sk?;}/UjUؔXDQ*I;5ZJūr\r#HeecJ,9xٲWP\1fKtL wv97#= :sWFfMP7Wyԩf [nSO55?ۇ5A Džan&\YC|v5r۩m?FiŨ6x c^2m!~lUJJ#p@oͻ$qre6J4-S ۡޥ󼗲[Iv"զ.+\NۨYXKYo le3^¤}T;ßս:{>7Mضa[ _}YT{9ߌ60iq'{ ֿ_rr ~lK~M=Q͢f}cf5g?vY;oW6f=_|^,Żէ[צ=3w`c0cP1$>1d}_?&Os [_JޡzCU ~,`VUomcmܽo9=z)Jle?36ɸ`H1Q8l5'_w#j-{0$lǏ/ݎFs<3۪Uu<ά 2ToJc;zkӦy& uHjU9O*Bj.oq9)qg K6u8yㅪ2|GvgcJo)]:DT 3d3{ƍ>h[A>iӷAwִRI=~׾rJNl]~cʽ߿C~O?j#-Ok׏YjXwhq=vg3>6gҼ4kK{~ջ{v2t$Pwɞ}\Н>zcov`#H`àp]i/ YlYmϴj u>˴a䲼mcJ V\wvk3l=k6?.ɃMSȭcNkةڏ=1XeMe-݄bN6>H [չ6nXȏNLɼ5 Cc,bG%_ Ҵ}3;SϽRuM_'#3?N~LQň:DKM]dZe钾 `"~c}i"[_p5ٮ͏E"ďƌA܏)E#]`zZ6mKf_B2o2vb&8&:s0N }q敮юu[L2惈|ٲ5:U7؏׼ꪗ/)1:JO_?cC ӁOuLE?xٜ6a@3E~1НRRgn\RZZY]wu>VNZhUpCR#~l~,==p jQW(4?8{+J {**"ߏ=C>{f^~%v"_cϼ 3C'\cz啕6nCQ1PDUNJpz>5AGƌ Q ϾbUu]StN] SOXZBԣ^fܵngYJH?SiP)Kd:+!a's;f؏F.hB^ca }鮡_Cj+*p1~}ذ!=77nvm566Х1(tN ~l~o%TRO!T?(!OJ/|=4-exK DkkKkC~akl*IJ-8]ڝIe\Zܢ*[Q-}]yW\\V_ E7g cϙ>mڴĄxуy U^COWOa,ȒU$oL$K>-aFRz$=HNC(4Ӱ={JNH^'&HLNާ_F qjvt(9@MQE*KHj>jMm-A{=>o}}KS:<<ԞrZ@j4%v.6[<? E?n{f?Խ6ႇkY~'Nr?osۯE4d F_uUZrwFG>!AS0Vfn9b}0= 12.V87;boB oϯzKT~1~4%JbY+:%D5+w~]Ɲߣg$5eÆoÉi@Ꮙ]5Pgcwc ssBeT~wں.g "OOu[>8 n,'''==}ʕk֬Aْ*Xl`:4@F2lސď "׏QT\\ZV" M PY [*h9ZC/xbWmDqj>Xxw֍S /nt}%nkJJ22lnڱs]55NL4jnÁݱcً/3g3g- ӎai\~VI3ƿ&UzNI3Ocst;1S5WzRT%QFM@Ug{_3g ׭_tt} ކzO}.`>8s&͙j)Ι|SL|kqW>qX[1i򫓧Ι2Em{s:ҹ27D6^r#|{ݙ[8' Lqr]|K`u]ߘ9#H;|TVV-XOu[m%i+dtpaK5,M}|}ڿINVDO2HsCM S^25OBL2< Ug汫ng{zs[swhlUWVmڲnݺ|$u!L 31!やTkhB6=uŅ|N럹o@:U Ec44eN\IX{+\ ^haG q :y>q͌|^ZIU;UU*..˜ܺ5t]4$a5 #A}z>kHcí/_|Æ [nݾ};g,A  .=\&i_.f5kj\մ4Ɏ~Wm>>`}Js5܈~t" =| 0٥$`sS퀦jtd\nt,놬ZVt*lS]VԺ=8 zhfZtG BpPـ uiXTUWWT9k0Yz_BSVVx`gӦM8]:#𕯇 BnzpA}SmC& ,tr䂜NL#C*}} ו QME ZgYxSlNvKr O[SZVZUUi36% P0rNBQKQDTW_8=7nWWfNFgFۃUU28aLtQD^Cx=A}S)((.)),q (tbX˜?-W+gd{kW6oe @1E.`Y1 SЖ/((zv6ZdH]tJl>j(TaOEF!N)tWV3cp@mU`1 QR3QC'?EBB;ק1zk. 6ioʪk ȨN!T|OR~ Gf"Xjvz25YBrd1`B1|/'\#_!5ݣ.t:O==ռWKuЦnXmOk(br۶mŝ4$X]be̽ 8.7B@Wx(`41rTchDTCǍÃixM7AC.;Lإv׈F+i@ tÆ k֬ǀ4"aubu MVTTe 4NMMŻ Qr[A 0bFŵLmVfoU0YBsPe<*FO1v fG}Ӡ2PoCq mR@Iگ"9n444lݺp:@"\qfdd_^p0[dvxR"?A4@|/SuesR__%6\'j˜5xS@ K${s~R'5_aII?k0zqab g;vE3^=۠ tpG?J=ԐF<1H8.8%c fu4 ƴ[GKOۍh4Y Rnna;wzo mBD!艮$=ev OkC糽v g q]( É)"USW?7mJj{Z_B[1 ?^[d@ *ғ'Wq}I4 X )xkjG TTkV\⢶V Tpii).7oތW|L]vʨm! @P9=x+ِ!Cӹ~L#(lW=IcTDsNII $)++j< MP;۸qcJJNg% J؏ a{ХB. Bzە~2T|d@SXXzj\P|0[d!I#لeu ݣsk3t.t8|R`n \v܉,>,Y%(;؊f`=n"_0K2fLdiDzNg 9Xzm;aK.ci(ڲeŋD lᐥ- 7QO[KOOs ٟ"c 5_itwA$ }U@"UVT Lyfa avvvjjjyy.c[d!cL:11%x6c c4}5,zqɋ.d}mݺu͚56lpIIy VH2ՠsnW62MX$+^< I"3mTCax08R $Q~~>͛sssj`AO fAfddxDN?F`C޽ Nvq<@d@*((΢pl эBrZZƍOCЏE}#%o#ko=HЍZW`fcpz۶m=~HS}nѫHc:;xHKB{Ӧt^&0eܼAhVcv,A9&0&a~081~Y1=t"az!bFcVIq׮]|͑]TTiT@$PL?JJJRRRrrr0M?fEW<$"pΝ 6== .myb5,SS?컐4QQPP܈'7͑`x[.rNp050_ N/W~xű ڢB HE(1u E~((ā o+oB?&Ⴇ}/իW\r˖-[jUn.=3B:TUU"///Aaa K.]x˗,Y^7پ}&Ś5k0qz B]:F,T^\~m+؆ W)HbccTO&=A\*JKK11j 8F!AtƵ~?_kK_]D:OoӦx`û/V5w뼵 Z@mۆظq#^ц﫯\o.&dĬ6 9G󚾐z윥K.YdѢYYƟ+z Bqa2IOOץCӹb }áqf*({$\ c|vkk6oXM-8yy[U5wBI;Sr%i= ,FpܹV1UWWÃUlXf-Y8;vNE t'\Bg>LJvઝ-g[+RMS CZff&E-[:[6} B9abiy`A,(( j?&D%*T嘈)7!ruNG 'hGWjꚥKeg \qӥf26zܗ_xʕ+"< :?@DZ/]Tz72.q5Shf0ŭ%cu\MoiZZ%K7m\SlG hH38 fҏZVP:%e[p))o1D]3*gT=3O,Km!SS9%b+|:/A bgz-MQnMO5Dq,k׮[@]japT7H_?4}W'%&TMt䤤Clܸ1\G8\jC 8B5DlS'&}&VN׀Xuǎ]\dTrw[|[ ^:==IkD 7ocǙ6oF=@dWN#}"++t:3JlS<X\aH766 NS\-XYN Whtnڹ{ݕ9ٹ+V_dҥ^ܚtaPg]cwא1!NnMT1'sGӎF>—>C^/@x𢘃A$J<H\ʳsk|׳dF,ǎGlv|vNAA+ϕ R5k`WݨrJLPc AY07m۶-\GMLL#ªx`QaB<%'"BK#$tk䄋ッ?8BV+KSVLx%|16u؈FۊԵ=Œ3X$%%͚5{eammۊo{tzݻ7???++ _ ͟=~nj*ةJH Ĕ)qS iV3mVZWB}|7nܤ>{ٓVy2x[R j>gWq|Z08cJrr67w3裏d唔3x U6f.Zry˰_yuP ~Ln8ϟ0@RRr*Q'%'+%M X;0g,Z_|fs>,,S'&wl*~k 5^x|pϞFkMZ--\ o߾K ә%KIJL4JD̙Iw\H(ߝlνFF\:^qΚ9+5uMyyyBY 4* FwLr<x_WdcxYN8"uPtHƑVUU)x;i[a8rV\5~|^G}g!.VgSď ^<<]}"`OR HTtXͮ~`U ^϶{;px9Ѩ{Fen87.#cCgfø{OFfuCݻwgggiիW'Ӎ#L_xFE23(&p*=!&Q!L9e(SRRps9$a1dB^ґeўeG X>!=csƖpC}~KX.;#0cBb",9tcc#&?PSq/Վ68]/?{;ďE;z ]  \4 O|9+Xӣ1yͮ\ cEi{ҪV?f%Z`[999]^ 2xُ$a4 ‚1aRTTk/>=Yp2B>"Nڷ౅X?5EW5HH~f:w,ߗ΄+Vk:cG7_h ]?\߻o+ďY܏󩮯g^ڿ5w6ϢMT1".^-fl ܢC~Õt%Zeo|fלΧ氪i坴nZobn}Vom+WN/UVx{xT}H@l'q쵝n46n}M>>my6q}_c 㤵_i':N67#W$>3IȀ`L93 0+_F |>9hV?{HVJwweeJUzNJ'fQqI f?7S'ev̱ο+yZ]t j* l='jܿf$,})644N&'7|Z9nz,#64w_>?y敵,ím,ylOcoLؕYc+&J?.c'\i/;[OcGaha1,417\c^%KW _n'f[Ap *ҫ&oێ=n4M+7$D19bkȲdfQ[6䓁3NDUxvjQNFLm' Guϴ<fݻ& _H|%U!0yěGƖjautN >c;CջL<ƒ8}TĪ_鴥b4yKo q b1Uënj<:OS$a66hhS" IŐ^֤Oos<fb6N?:Tyˇ?]*~2+527e!-TW:CfXY;~c$VPiK.ipޢĦcF}5jP%8׹yN=nr4HĪ鴥b4yKo q b1Uënj<:OS$a66hhS ):\8sPOǡt:OS>w<c͕}N,t$o}7ުVnVQ3 򺯸FcZ;wS3aLOjw-c+gy ~\ҖĪ_c4yKo iq b1g>^5LRu7<gp w]OG"5K^9`VKۑcst\'Ti&7 ܠVGϔRy}"g7[_xwqwc&M<d'lRz\%<K+7L |L.;˔<6k45VֶRKZ~޹\Swn0]|LFdc:[cN2KSTFӋfX4DG=L1^Z dP7p%D-oNTyu7cL2_>mse1DcfSRqvz^YzL8/ܨcO K*yÒ+3<1'kTdV5ljGuffg&Sd,c:[cN2KSTFӋ<f~\Mmtgn&SN/7y2N?_VKĭ6%ɛ1Ik&hgc<f1߯KksOTKS|̍:6J$eI1|̮|̓ǜeKP>NewX4vLՎ\HL"a=] npy o3b*T;[߱O^XV,]Np/7ylaYtM[Uy Mww~C`ۼ%kylڦssg\rSOg+E"+cfkj9ujρ-FDzu\V^y}"SR<hС7(}=;&)5Km|~/2s #a*.)_OO~o;E=3x.ۿw[yM!#,]ʿ;MG"vV[[X4Fhs|rͫs"&t{M}8媮]g?{z9Yt5:6n?Cӧzf+ tX0o(<ēs|H488XQYysɦ͋ l).Ӏ ֮kz-[֒2z֕d$ٲgiVY_q=#ERٖҌ/YJ*z{gOwwO}C6-ojhlU,.)+,*<.s3mi7y_ںFe|^]/Ş݋N-۞=kg׮]%/[J6<gUUUv)vU]]]YY!)se>A 2l߾BY4!YȈijZgܑ̗<AYooo]]]YYY[[[~`v1>T}}} Z[[l+@Vc˛eٶy .<appP3 i3pc|K臇[ZZ./ y ?6[0IFY[[ij^: fΝ6ma[H$^YYY[[w^UXc(aL^B'+J0ATTUUXc ee\sg{ G"V}CCaQQFޝsa 0(EM'xs{yX,f/A6˖8Ʊ[y @|SaUW"z1eHf¼u/go[mzs-͋Um퟼pf{y eyE y lylSgd!bp|һiZ69vha (9|^PcM7YS教c]vd^5/?)W8n/dO!8QW_}( y ,4lrdWB]'R+:erx)O8ylrE)od̓sr^2`fs&;poMfg:̐^r&L*JIX:[ӓ5EO JV=>lFnf<M:) .G?=yR69H(}RɮML=RLR^y !S>J-i<fܼ{򘮳1:Tu$ج<lcO՜HcLdG|-BvlGfrǞհ̡H*J1SһUgCpX*Mɇs\=;r9+lV8 M/kF3ƧuumyB]΋񟺻{zUX,~C|?()O?808h pI*+-P<Z5u[vo<"Hն Z3x֒7fϧXIffm,dl:[u< ;[^^i1X,UUUU[[{!JJJR544gmxxضsD0/CCCv3MpX<`N$?Hd2) vԴs'9{ =IEJ@ww$՚IbH$eI$gyeigsssOOYvXc"  ý3ve]uAnii$/7gbbe[m(g=qi*dA`0888::*;Jw G253 3\9ؘz%ʗMQQʲLlbbB.Xv{,7W[UfF *}U$IlxxJ6Z}7ijeF s6\aͲeY޽n۶m4$ʵa.fL`3±r̰rF!dr5 $W|-u/nE<mTIsJ– cBY▼ʪ:n[JH3}f6;zkV ɟeN<!DupsiOOgAɂ_c[邑CL$9;6yȔ F ry``\*?{Xlckk*ؒFYʓd0Y*wƒ:${DigfW>Y*̹{Kg6ʬ ,54LWw0>3Tr,ܞp9'5e̳XVͲxbrDݰ۴UxXTcb1&;jUrO=*&IniLiP)nRFvҢPݹsg}}8p@";xu?PsHhI?HԢڢ;)\zƶdF"tQF}pFZ.*s4}Z[[Qڄcnq[\1gP sHg9ICCC^p M_cvb y Ylļ !rQ*'KXa1˫,tKH]vͮߕޔ,;m$SM-Mt;-uM/%'iݬLL^r(Jjfs@#ǐe-rޟ3tPl̲jC{YOc"Uy5oذaݺuɜ9!@<,01g*/V fNhl,≑[?*}2{ɂP!Fr1cǶmUre˖[Jܵ˂7& =#j~f5駷32ۑҍNݒ4eWԣF %MJP1$wIr#~~ *en1 S3]qVEF{Y+s.<n#={JKK7n޼}.s`f>;un>m7g&ǀ\ZcϒH276&͒:~H$U U#2[ᨳza]5qo(2;Ըy-ŕk[f͚&I&rKofFrnT2Uf9EEtUʨH$S?%dP}PۻY}䪨$l3@^*,̼?:=Gڊ "&*2:<t42[IbT\GGGaQ|rMP[;Ȃ08e9.Au/Id֮p1!>KFG}P$wO_WGwGsw[ݮm ]mm m;ڛv7WYnloƆֆ憶FݭqG,4JշJiټaƊ[6E41_RdSOē Uevyli'# 㣒Hrbb|xdu{WuEC}up:T5e*g&Vj)}wIuu5h9kp`h|l_2ݽdg6H6{1d1n\ooowwwMMMyyEʊʭBWTy.KS=Y)+/.UqұLvUTa#zm*J 6%ܪf_=RMDJi(DuuTȦ5TssK__ʍgś*Iv?޾N~{H<cckC~ pg pW^T,rp*YW*ɭU% LYki`U򗬼{ oJ?GI3 b 5OFQ.9"alt_R%nO<˾]/X3%eιM|UiyEo[~;:jJʊ7mX_^[⒒=i_c~z$=ǯ⊀ )/ٍTiWtɺU͆:\8 9m1";Zl'Z6a 5,OPRQJw'4W]uO?s?0688yf\%o]կF-t V𝁐`kyf@p-Yv0Bw_ ^ҊH<WOI$;[715^Wew sѩ,kRӓw2MvgJBK̗T%PPe8l867Y[K{:zyZ̷I0z% S$C=rZFޱ+5Ť2:Z68C8cϳsr=sw.Ɇ 6o+\꺌l<.1>̺Cw=*WC+B*{|-;yLrGH_K6 ޓw #K$\kJ:{K((+GcilLQ?#K]'Gb>jd9p@"Ӗʹ UMet6e&/H:8|K,P(Q\D2P*$1%Xl|||ƍ_B'K*ErP0\ tȇt\@^~@dP@ͰF($?^&{Tg7,Rj|PNRJԫCpn_9XXM;$3LuқsPLv`0Ofe6 p^85[i / /P8,ȓ m޶l)HJ9"; cF\$A4$wɫy tkCYnp+KsSk7gɆM 4o%_EQAkEx%%=]9yp~X~շŪ>X,~՚ϭ R2=yX#~У+B?[.g|d{"/ƾ*y5gQ:hW.>Y|>6<}<ľIS̕fE7}o╡/[#eG(=);pjZr?>f)uoxf+y,HOZAӟ/K*e=y+j `< f&cﻯU|FISQ=|U0Ѵ( hN5''9j<W)ofNߨtÝ:uZ3~tP?9}j/T=tjujsCR*cre/VP'ފ#X;ؙYk.Ex%ş/|^:7|r*{g3Ihnlr/~_^'L3CM"-}#pLʏcN(rH*2<fd\8E fn.NtE_1eFpZj$2 Q*\ y<K}("c_4X1y x|5wm U]yUiS{q,SE]8sh<k(] R.fMJqQ=8~rZs,<l ڻa?0f_1\^w)\Ἧ,yMr(#lkH?x7B+/ K5;=p=)ߺ52'}fg63鑌F##cبoɻCRe09)3=~~pO^w}^&r=LT{T |-bҕ)M#X4GbIaNV_F֮]{׆60N( ~A]P3}p~^=E0/ f|dn ~CI5ʚ #yy]ˡ^Wqj%"2T>j:yE! ]C^!u~GйXsa}ւwqqɕ~$#). Y; @|6t8[ }-``m%÷Ic xzzYPnn o 6%Vmy[7n oܱ4|{xm% 6ǞDX<%wwWqF'ɱK_xxC^%w.Z~yr\ԩu ʉHo /yiޭCyrBaNSޙ@_=;wGbDlDzgL$s{zzJT KvW̼㼔,H Kkl_"]۽6U ' $ՅJ,&/ɗ*1IHPRٔӲ $_,]Y4?򥁥A~8_jjG&ӑ,V^$/5KJ{HVwE W, ,.CK+< X* lաɫk/% <搯:f:Ղflٲ󙚿H$~ˆ|=C+?ls[ y Yr$>7_bپ:Z뚚kjZZ[ۤNVdAZvW#=KmSKMSv]P"%:Zw3$abed{l$UGL21Lcc}Muumu- jkMԪFUMu͵RҭAtyRWCIM3Hݶ]uc}0i~c~:.n*blhhؾ}۶V-u9)Mmj[U%SmQSuTVTTlwӣT#!͂JW63oQn۶JFeKjOM1Y689.Zv5<1O{ϩ*+VTTf4{ј=03 hl(Ehb"OFbG"%.r`褖e4ϷԲ4d2:*5*K_jS<&;9D6H8'ۤWt$E<d\桾w񘌚2GJLUv%c#17g-#8#ѸDp,վ#J&q')5܋ }\Y h}K>nJ:~K؞{zaޮ.m; nYm體6ZQA<%3vpKҥ<My(H␈B\rN䝘eZe#InC+'bⒶd<nT7UE&&LtTL1՝ G>[Q̝nfqHtUVoiN1h(r[zaZjgJ`Ӕ3M3ԜK.| 2,?Ǫ'TO,툆^-kʴ/E 6AMMuI#<ޛ\[Vzbnݞқ<*QVD <S9{fZTMft L쾗 g}O_ؘ_,IdՅFdy ;iRԊm75eV*K''ʍRs8եO2- ]H$رaϞ=c:y>|9 c@N%̚!62%J0)8u#YڼX~V,Vċ/811Q[[k.Մ19Fdy ȉ t O=L 3y̴G_XwwwMMMkklZ}  [email protected]$1Y%ݫB  c@.$a$IFv񁁁uɫ,9{3"9_ 'Onv_򋋋+**zzz|wy\w*cGss"$eEѡ!IbF+((v`4440V]]m[/HH}aE1dJv!Č-%7d\%Vʧ~<UZZ&јSop#ܦo,tu `Ak$e1uu|gV-zO>{Q2Tm=;O}5k'~~$nd[~ y 6oO^ooر'z۶ď6,zk׮#@+_;aaz{q:W˿d(;/o?z1xc{ޙ(g|yx_~6f<3ra<σvP-Gy7}+dohZZ_8z;Vy[qª<p){} Kt9Ӂ՚cgE<GQ>^+cc/JL+jLLW˿eZd *U~oѐJ۩w'^x ;R!ʉW&^8:u[1vMOĥƹсC}%ϼdFuN::d>'чNYf{;}-ԝ up苧Nx3IRWe>d<fQC!Js;+<mPtyssZcCCOܻj}vO `+<ěw_EщH{T=a’Ĥ㿒ɟ␓ X:y'MOIPr엲t^jz:L>oV|Л'N79T6ܺCO KSN 2y GSroVu2Q]RI_}OF I5H^8Xy 9 W .=<.Đ!-i'Z }[y]2jXA+m(QRݼ֧_O5tV咭%J9z>f.ILRM1=%YI뀥IzD3̰Al5%s0QMx&󘙒;H7ԙ< y f~E?Ǎ Bz32StA>qV;g\_)˓܇BG1C}NM}& {eL hb]_jV~G=qjQm<nw?g|; oNSywyA{R=UU' ~Ly'1ϻ;\v3wƹcӳ]rXO(y 6\C,ߞ7_02]np , 1>hjl?_ g?GMM?o[68mTx~6 cQVV/dٱ@}K7'~ʳaxxp<`Cɢo~`coo(Ky bX__޽+^Ч72Hjpp^@1y A$Ktsy ;s)< ?c< ?c< ?cTWR1 < ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?Ry| @n1y A1y A1y A1Gf(((r\1(((<FQEQEQG-ve/m[IENDB`
PNG  IHDR hSsRGBgAMA a pHYsodIDATx^ `T'>oyۿ>Oyo_bA< XnHhmKŅbRj+l$$,dOf& "nIs~gnnn&2Ifs=w9wܹsG7mr[q>|&fӺu:fGևnѓ>UV0vPنfc{gD=̣Sk!GP/~ٶg/n}cTV0sqӿ7jJiM>vqh)3S1VJم5]SKEc$XAhQ735|zeHUfiN״)Xx {(X(fVשu)=22=q.IlP|E 0Z]aj^wDNh'"ŤomphdPg@Bc&48nQK65~D{b Y۬mZ뤞Fi:34dR#j+gLHmzpfYmzp*r,UY/sދtQ%'PUp2Cm6  n^F9pBӚ!Uh&$| >c}tFalV[nZ"pf$Uf D8AH*zj s#nImnZ"pj6eę>#%YB-AO&MYeEpcCE n3S&mPKڌ۬%N!+AZUmPK٨͢'0CS fL@-50;Yv 4 ҘیnW*F`[v~tԄ{]I >2td 4颿̹ﭭ1ڬ63I|Vy7ӃIb(5bMU0B#,55U%f6RZ*Ն\ MHciIJJR)WVV];e 1\a=ILm>ە*ׯW(((P#mqu6GvC5EHg}{,3-FڵKMcY<~ ^=jrZ/)-ՍLच/ZPISz܈vŽ=C;Xx*W"w˝t,Sϊ []R*u6[5U,j:t{I5O%%Y1O'ojMCD%5h^;U^$Q sUZ{{vY]]KM`*$ 0h5{`ޔԌ\Q#Zrct: j n6͊_ݽgݧS 55Z4.=v;Z.119HSf|q c4hS)I2"YQ__GfTCmj܄*]ȟL dfVJjT `nٲ9>~K|||BBBbb b(3N4eUk7nlܴ&E`YY9&2֬m+5hQQkٰy-7ǯݴf t닋@[:]Tu6SX h3$ ߂i9Uș(Alr|kcҖ6Q oʭ]F~a>צfj34,HE;hE-Ml,<;fVhfM~b@?T9CAؼ`֓ۂ3G4mоF<J .Q}90k\Ĉt:}֬v k āT%q9\NWJu{-rr9RN81ֿk-yScEr/ --M1|Yvy,P)`_]vnRRu$TWW:EbjhhEZغuJu\ظq7lؠRvVU*S8M`j7;#2u TRRFZc Vzܧ[4g<P^'QETUEeKJ.R}D͝;/6&n<+VF`EUTʸ?N1ֻۛzm3,S>>X{彯<w/SU9f<=7^kBBMm5eqצ*~)'םl1/UoENvdgoWE#/_pt7d|̸Lcg11ːnltcZru$T!cv_MFUjX};bڪr;W -|{ήc,|fi:_.^n?;ftkDAl3r׾8;p@=hS@%TFL~P3O?4,r %LVL'?wÏi3쫅(L6f*Q1>d_ڬ}3CD>5]Vl"}9mbhKӥ)_):' YJ/^qIm5jjjՈ/P=YBej/E[?qIn8<q/͝@4-۶mSpC6Gr:w;xu݅ VnvZSe$D!&S]xȮm&n>=n=!hj-AGmR4r%>Qv ־r` b"r"!^L˕W +BYZˍs; efFENTxjsrݗҥ&,'@iH#G|ˍ H@&mjnVԹj`E.%>6s"r9km<N K|tzWȖ(BNdÒ>h3qQsa+ qa#gjK둁CYwٲeJ̦MT*wmV^^~uWkT-/Yr!HkdqU_b)Mr!Hlnjǭ!Gk3CBVmƄfY =BnЃ,6 =BnЃ,6 =BnЃ,6 =BnЃ,<CnЃ,6 =DBK=fl+'DD=.}I[NbxxC&Lu2.'!mFoIӳ<o>_Ъz*"ˀhT:iOqsc72m_4$u8laqi2|aMj+E oIٲeofM4 jTMCiq6XVƀ4-3V5iV)z卍:tFO`k(sqI,Rmfs9#rYΓo6vn5z |"v@EoI'0nbE+qòFjjXF'^JH3a6Nd/Fe@!-CTb(gh3,6 =BnЃ,6UV%tGT Yry颡QsLu@p*6'~nooo@y$n^ڠP%f~B*6UO%dqYpcЩ~\۬fNJzjNT Y3lpůR6cGP"j.Cp*jw5f >}+n8YW vu P>jNnS9 jN>}DqÙp*hX-7bcJzj}<rsȘ{]W1ޢ|&P3tmۨ}Ҩ/L]_t^j|֙帬"Ζ=21IW-Ol=U{= ~t=5O&Haubg_wV3 ]5MeffTmmRRJܹSc AԾ !4j6ۺuJyi Y[U* O 96op~s;e|63Ɠ~Rg~ۦ ?hwU;N{Si3I,b@rz-9P`BӠ5F)fsَ\ϊ:G#.9^+s~Wm66ca6цyibEZDgی ~ˡߗy&l Z˖fYzvR+IO׵n]qZj]rkkw*D5kҍ3TN# 53'%cgjFNjF@ߙf"mօT66MZEWM]e(rr=x ]5LlI;`mmU[[W%fh .UU*`<(UXWWG0ϋܲ-> j0 Y c[&vqffֶmbwdefz˥k-[lO9ܲ MOObvǖ7j͚o M"enRkYkv㌻k$'ٸy6oYqMs5?ed`8Sc'XVd۫k6l֭ٸiM.'o;;</}-"9rXD}BQ)o\U.K0^bːʕW 5 ZVR<a5DɧZG%JKJssQm_ִ6[@'T_Qk䀹UugJ{\5^Ե6s:Ye!m2Cy"+#b mֲs\wѮ2 S11}E.BHվwDխkZ(pu-q?"UYYEq@=6 NLi+UB6V.!v4%j1%kfj)m1@lInvDW+W-T&v+))DFB(q9XkQ9Ou`7oܹO{11TF'/(TE1-5}Uu*W[x%)$dѣr.5^tI$.nN\Yѳ絬<IlNLm|eJIiUe*gm.z,j3,ïz'//;]uz+N/0UTUO{5zNmm:m[6[v=?[^q6&&u1g/;eKZ(6 U_~M5kyrq~܅g#11 olTgS[ܼl%ƼUW\Tڋ/~k/Ͻu"iߞ;oʼc+3\x'H7,u7dN_4fb'1;Դl+*jrթ ?~BeCáêhGK2%Xm#㥿kpߵ٦MTyyy*563yX[rTѰ_QLgG6^j}5I=Rh=<ۧ40lذĮoGZ>4Mjj1}f# 6tDpm&2!-luYktmfp\} L5e. -5uvWQfsZQ+nk6kYaCjZ)D ]&:؀{4 oCTxm&>|li,, ̀LF!>]{J|Q%4b+6+])[4W M LG ֶ|nRLex1/>>kE2ݠBܟp"jV¿k/;x񝭿+@9Xw޷6IM7m-l6G}q =d)5::hȅч3V$䇌"%GWTA1,\Bo Ζ.6UUU]-[Tn<뗷^ʅ pa/+@Xp|I4uq_]]>qj*62fL?,hfLmzpfYmzpfYmzpfYmzpfYmzpfYmzpZfԘa7-r#׏y(j"O;E !1micF~m2ͅD5C4K/KBkCv 0SM;2<_;??f@$U"%ΟҞAQo{Ӡu)[E-v5MC77mn.~ݢkNqVY:j)ߏ ߠQf-1D3 =̔O1͟8;G{ ];a'^):=jO=Yq8bܴSac1& L)ȏbD5_XRk ]˰,VU-&!d>Sgfwf>~nX]}tߝ(Le0mq6ƕ`["̬S,+Hjf[wAyV \ V{ J*P<WhK(:tF̜, ьgD9$乸/YN9SJ.<`^~e,ju"\R¬ڹ ,I _;o4xx衇Qr+HTGQ|ټyaԴ+Q̙;v45QhEmKl{!0cuYmŒbT;0AÌa3 :f t8&p1aC3&l#}áQ<dvLB0c x0cu '4(WkÌ [!%quz(pxD}zWL/:fMVc FO,qTa tx0cuf35(_3&l#J\tƠ9]:\CbvzP:8̘Aaf5aƄ-tSA "p]GJJ- /fLBG裳.Ӊ050a}Z/fLآ`7m 5aƄ-tz*\؂w}`IC*LۍK90x_LOp OkT.#>t1j&\#OPA50ìRu1uʧPA5L=ImtKU#_#}¥=]^S S&ԅ3r1Kx DKvO?y0 Tf&Q> f%%%j˶mTΝ;UKEEJ%33ԨqO#> Lg_ʧPAafSSSՈ/TmLg*UPfq&h= 4=EoifnȧPAap ݵkJuU/YYY*unZ7Z*wEZ:Tr@?.,mC ace=;0^QQ6$W%UbdCfӷV ޷JWܻwowD7|npHe>t! fN~5MRZCǍ+3I7t ɻc=@Ҟ㵭rHWϽwC\I+7U弔zkQmޒBSyW*'ʊ8qTc럪0i af:MRZJb_]gZQ+7QTTV P[TA&?Z˃rI%<d*[.q8Nyi)@=z"Hп34jБE9EG"]10ja.]Fu~1v5{yKF?<? R͏R.8"xjk?.gpe85C =`&&&Sn#U9T^"!xݬE}7 v\0*k $20TTBNH gS%% V@0Į'C)a:4oo߾jLԃFi=AM`b~~>Κ@FnEq5b{חY?–x?ӈ[b8 Yj\K(]TBD B1C b(Ձ 0"-fAJRe<{;S$*~%$'FhCe9tu,%5{ys͛;gbc>=o옘ٱ'zVttt ƢgώT$bf!'nNl,R(3gnM`}m?ٚ%ƢhHhHhYz~*,> x{ @{HfTݣFXn,Z,-bE"üACc#pA1`kEKa czҢ?9i2XbPY &|8bU?׿:D\[4;_q(p_\(9ke8r䨪}Ygڬ#g;'ķֻ^c݇H.ue 0a*iTUdwXnW[%L,>DŹJ:XW:B?}J2< Nqr9&;yæ7dj=uTf{ôTN"Nf5)Stcq<C{1qqCh@pcff 6ӂbAZ$j'0oC/@f&ek5Ol 9<F=. p! QI!#ML!936oN\ȍԼXL1L4cDѹ͙;m9U%5pTy05HORj~[  B(ed |od*Ip8:jWqF%xX[gfd\,d; Vy_5UO W`wD0++kݸ O*!D+ORQ xttqwKUB:g..cj:Kg5EjDՁl*;jу*((#ى , -'N> -Dh@aa!uhUUUj-Cvqd0WBĎ:ff" нuXS,S1kܠ$--M"*B(hVC|ڬX{ǫpruHߟ_WhU@K? 6dff^ٴETN4͆\;jΖn}|]XC\SAdff΀٣?,^\\LAUhbjH- F~y E;R Y^M6#;W_h(mjyqv)_u2;QxUN926ZBQmG쪘9p,Fb8iWg&ļ'c UpٲŇ#!Ӟ↡sG<HPǀQ[avGc ì?k~5Fy_n8yǶ?(I_66ʙ|Yvvx/7'=6>1l>>xTQ /_9z<ͫ2@ظ̙b|v"uЀ %|Ƥ.Ќr9VV۽WXZ,HO~KԶn,ehZ RӉl=gyvӄeVNդ719?孃v S 11Ξ5Ϟ=]HϞF]wͨj ϾYR *8̺IrrJ1LTPqG^^^AA }vЙ fo#_vM6yyE4ϖ@zNi˅:&QA5ÌniJ@u?Pw;HOnuSDŀ.њ.jU?Fg,5UL(#^a BƩ^}|(³zx/ꨠ⾙Zvv T!ė) ODzXӉ2~2k. !3v`r233$i =4#V  TPw(EPPBx4f1&O;jEyPO"FĜ5YYY޸2*abk֬'u0q.,8JL/*,⩈!OoyJ6hH`T{TjUU(펜,Y?2Ԣ~uMޮ4b`"_9"[<o$0Bס܄Vܹs׮]2} 3mUE=ӿ\:=99ABJhoZ 61e{u<Fi|=8oq ^/SB% uc Hh:rGGb,#֭:ӺqC5AX#˂Kƙ?9+уj*۝bqO~|AӾ>?ꪸn6d`DN" \J,-3Aꯎ"ɦM" $USTP-Ӓqėbpx_B.qAE~C ={!yeẖ֝.Q^j޶0! ~s"4NgPgTP16lEQVVRLBY{DE W^'-j"SwPu1 *Pa6<Yx#FX!cA{rE>_xȩ\cip|!f$^P4(2b.O;?:wt W|X2?8/ _̟lʜwbcR(G"*8n?S~FAkV^_wY^Tf <TP 3^ 8j6i3 :f t8&0mc&p1L0ca0AÌa3 :f t8&p1L0ca0AÌa3 :f tDc&p1L0c쯫vX IY*Ɂ/}c 99ǔ<ErmS|í?-}9RHO;mX1i׌yqu(._|K];66IcGMSf ŒQc&mygߺx#'G:|7y&\]֡ =j}ht!XH =3k{ѣ[#>*<Bq`(E)̂jcoyWo}7;jc{IO>?QsF1޽XMTbe,!|0kc>1 hx*]{=S0Ca񌣲pc4 CaD[ZY-}٨ t|^43_oyC;SGchw~Dڢ1ۦ^">{g ?96[6G#GtO|뇓+œշ2X&x#D 鍛E)N+4yH !}A-Kӆ9"s 4|7M,VHIkOdZcҲ1MeBD}cHʰ,VHXq3S;ך>^ܔr;21gjߝzˬ1 @(Y^$#W͟q;di=X0~_Xe7kn]F3?Ӱ"Ƥ(Ɛx(6$b̔.5ƵaX-׊N>ҴPփ Wi]:b!W}W؈CgNF{. DEXUoWRY5}$\qBb*?e)߿2s dGm{*~aQF~1 m1'cWcVnX2d|I* !c<Q[q0r5G!$CCbsH(|+(Y"_@qFD;Bw  Ra,LmM5`-ZblJk^mdIcDcuYb  &#bL-ҋA6qX1BUO^@TOnV{`o9jg9$SjDQ[n}lYC榦M DIQ&hcڨ%O2B1Œcucsr0xe `B ._+"Z)u/X,VGR1 4c \8&p1Lpc10ca 1 .c \8&p1Lpc“U 9}%^8Ƙ|ߡ VCGRk]74jtn7TgQkc O1D҈411+{/F ^8Ƙw>62f SVYcz^8ƘD}Z/cLx@1&<Q{Ѵf6@Z/cLxB1l8Ƙ Z3ں>I1\CwAPlh}n騅4Wp1D }2)~}CE 1fB1@t!xcP ITkc O(^8ƘDAF)~H36cb? rc [>8Ƙ ŀ s=nIz,1&?={މJLp1`1 \( $d51Ƅ'}Z/cLx c21j p1 @Q 1 (>!Q4=2UV5"V)c*ja^8Ƙ@ϙ04ꞡQN%<[@L۝>JȸrOϹB.mA<&aȾБ14 c@P Ng9FycF- 3xcuITkc O(Mlk8Ƙ5A}0>IiQTk0(?oDŖ1fA1N%̧B{~Bk]lqk$=}P<S\,_>]|n*p1@1@?MdFp#>N@:rb Xi3(-/k&,hMVcLxVc sdе"nj @QceM/Ov)T2 ~JB6<S<*v5*?#ȏ{"䁘9}qS1jBGO?OSc'"B,nIXzzP 1KC!?%[~V|%=L>#1D t_"$TlykIZS&kIMH}nkz H$AϪ(ҋ5m (SFPcc=!~@APLZc[{?gϞjU5Ϡhhv5")))QٶmJ`֭eeejSdLcYYYUUUj@g-RSZZ8ӋP cP#\S.hONN޿gXauӍDq~ɴWhmcV clDO\l66*333//Fe0VF%*ԝwq}*+Řݲ.ZH輛V Lb fR#CWkSSSHP:0;;;''N+GiUC+*@1>bпVĉ_. 6j ^&`t.D]ꨳ;l.^6r8j0c Lr +/̴$qT,STYYŀnB,8VÃS҇M25Fhga٨|?ek2joFblStJ}Ȁ)LR xNK`qrFawKx$#5mPAUU0 c21G á| q@oh9W Y1&pn$*=-#OUd@-qyhT!TUSZa*qB%9UֲnК/U1y A⪶0bS~cs?$)9:1ohyq$!yr':kO~b]ų[G̘x~q+t?"c"1 1cYKeO <+>ucUS^)853N@W,\j~GvWpK!ለv_ oqS#Y3y^uuIoCUd\T!:?^e 5UCV[ueEEfFFee%͂x#sӡ! o-8j)|=6tO'ѣghAPYWlY=H7{6&n6Rdd槧wQ8Pl\Q|ZmV׺u}zWdeښ;~֣Un'bJ+++P)QXA1U!p]M9X;}u T*Dرm?[+,os"<m60t50}EĬV+Nyyy:$gbB+(Zλ.8bi@>˅8/hcB( $P2Qg?9O/52r>{BoB1D jD=䢢fuvÇSRR 279233hijl#yRbǧ=Eg*?WIERZZZUU\~ t4MD2B E h:1# n=X__YYKy rPiG3m! @1n i*4XvNNG\;P*sz$ F%.8cuɽ2DdRQxKopjZt0ՅDyGUŵT{pwH+q;+3 BÌ eJTZ'%mھ3۷+bGnߒe <'$o޴)=} 2l۶UW"j5-XqiCBu7I\:k6\m{nU@Ee嚵&ZmʁE%B]Vc=cf7oMYnúk7m^qmNToc̈ 7T7o߾QC*s1ڮxنDVBBjӚMWqV֙ϩAˢJc _~xQLkjn$/cϛ=(Erϋ=oϙ3̜93fvЬٳgP(z91;3g̈ ";6.EhW\Y1㫖%Fӄ,lmA~>ɲuYjU9O6eZQ\٬t+,5얈ٚ6 %VӢ53{s{4|@M'0DǁѯF  "ڎqZVk':{ c2R1ࠠK@Ud`Ѣccc7}Xt곒#Q?}0f<=)b| o!ςTxw[|ℂGj^q>\eĀ!ӧ4 ]Oe4_ZQTiZkZeHL-mZM,Uե4Týw@tH+`5o}qs3byehV O Qs WUdb .e_9 jVZҥOhzW?7 NG#gC5P'cOAhP7AS:cq-Vj<M1q1Dy bL{-8]Ę.uuFkу K~G2KDث:Z6L{jHGk] 3ueĘJEUd@2ǘIrPGblũcQ?1<1Z]ZGͦ=,/ WκB"f *-/t[ j^FLR{$6V 7nYZ}23+**(`j/(ƚ<M0)zDO ][hjjlj4ƛfxSӥKbzΎQ͉CJ΅Ɗ:oΜyzgظ9m^uл߈86bEGQ4U U##Y|*uWS};MԞ jR6-Ũm~EaWóuR/4oʵl:q;OԻ J5m=Cr%-f\!O .lu:9򻹈1rJǘfEXz͐0Ik.-s!+I莭JL&da5vM<\p[W]sޡczUwzjj8\Es`h}"' SR%Hc+VYsՋFQ{#i`Z8ƺ;UBqXyQ#xxID2НU3D8j:S>I9r$99 l&O8C,NHJ+ebBkvޝ qC4Hii $;1֣g@ɴfEap#Scwl1!4$.VD<Zs*M`%`\i&}cAD6ZVpP"M ZYlqL`OETVT` j}%}^D:r1:ǙDTWlܸZnqj U|SUg;,;HJLLXLѨG | aUU7hWQ1@Z:e:WX)c4j2['uy0!cZ8>,;p٬z \x#UKt߄Yp3Ӂ@ˉV$LžC {jmڴPa~6|] 硒RD^!ETVVKB ȕuVT`jI$!*oq87ՠ;P5s,1{snysCbVAUgS/rSؖc޴J3VK<Ӫh˗/_j-RV.]ψtii9s9g`(w=a\\S+Dzb>5ߢˍ)))NuQ=TE<ꆍ[ԾVϏAc!&bH(ˀ)Kc aU*|a׮]ƐьZ N'b11$c1.qٶnuUg}VmOPhfĬq@$98s &}yr?bs~oG}˗Ŝbc{P)!|c)dz/V^V~54~z"?&&\5j@"&0POڍ'?ʦʿLJp)Jj^: ~@4_\[q=3-!q+-qYəב4/9Dط'rBﹿ(9s^r 9G$UZx_55L&b,ߎEb9o;&gzϜQuI>4=4oχRn-7`e"F%s|TUv w'v76/~턻vHprT-c]kDѥp꣏>Q( 􂈱?yU](xOyz-=+ 14`uJ$f<rucB-8{l$d"R)A1jLQbX:/XO=(Oz1rEHJ1L0"b҈7{j BkaLg'r]˫?1y t 1vłěe[؝g-o݉2(އ'5c#jblo!`]l].`CD 1Qkދ%$*T-!cAe'y ڼɧT9jU5_w((4 C-K$ u =5 ?m>BF/cݢS2fǘ0c'WO1(,,ܵk @~, puMTdeeugv&<_{W]?} Xd/%^SJOo1}Xj+UԴ=2] e8T]ړ0]eRBW<a@jntavO{Nn|U$VxsoF&k&Rc8=k/?$^U-E{l+!4"m1EkӨB˃bTc,lܵ@Ę!Gb@1/Kb̔DpcY;` 5oJvAژXp~2aX 6mӦM8x'E#GҐkmk5ٳ{`0pbLZ]WPl/檪ÇShU^t $"r!J݋] WPC}}=/d:$cL$2D B!c4 * kK"|H ?'^ gh^[~JRjD8ʄ!0P$Q=zʕ+ۧ2DqQYxѓө 1a Q%\֯B26;N!Z1f?`+=`wmr(CCú`ol%F8w68`Gvg$ ӌUJסÇoݚp$,СC2E=)2j+(tJ@%7 2}BXS' !5I-1gݷ\W Ta\E(F3ٟԾ);SvlϢW7"iiiY4 $_'(QDqZx$vJ$@m9f ǚi_ӴZ/=*z'ZdnYI/O_rXx/`ek֬X,WZ6$"kr ~JMbߐhW 1uE6HW& G˕ϐ` Hz(ME0I6t=L1r?Y"<.ro5(;=U?Q P?! k׉= .\~?mG?|ȡQ|Q{u0mb#O8*I Q/.b̸bS9c\_O<}H8K.6ǥ*g@Sc2*!B_B!>| G[CQ&~D1@c"'&SjyL?Wmٝ?y*~'1ĵb…q]b2Jm,OjڬAH[b5/"*S3O*A ѓj!X,zP*R$F._Ř<h!Q46II] NίpӪ׻l.(w7d2xqj:GY[笮:}*#ޟ? n\R")?p]8=Ee\urF mdz1.] )nӋQz7 ?3U29zի>tHfPU݂c1r"AD~҇c2b_] {cv j2ˀL :k9ry \&pu?tu_fZv~{^c'S}ZWwʕ>~2 *c@{h&ڿ/x%7h""R%: aBοcGH\21pu*}br6";'#e",M GDlV򓲗1#MzAfT@LҡHe50%&%.5H>xntzYSC@1aRc29zýOPk`AM8zx<Stw./x˻#UӋp1Lpc10w18&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca1<iQ㦲XcL(_\qw(}aQޚM@Fb8vM6j6G#Qvnr-Ӈ0rܔȱBN&S3uiM7m2!fytVϊ/߿~ !}PՎ#F]m˷r2Նz4|`,i-=o2;2>6ŔiR+& iҖSz3⶟P難zlmkK_~d-?nݱ?M=baL9ѓ7o&׍vݸ~w#cH?zV\qW2QNgF Cc?w<L@/fQ ݊jbtUPSck@z<zc9"*!7Z{\@NIbHcV׉!CJޭe >t[\YKn_47=E57_^o?|RsQwE,4bφѢY, jds[R fun%SI3f ;i+26@Vb+'z!1yQ-*-cM8ٰۦFOK};aOaM72麻}i'#n|47ylpG@D©ac^777}n2?tcً&a),u[M!06nOaa=|ݸ"ljpᑓ>8%OuDd>5qȟ2ơ:=rToCn-SsRX,Tuda?cLSn?mO;u8ܴN1~,rNQXfDqZQA4|t51ƥX,+N& dX:QƨiX,+(N|aqɨ˘ @>3Y,8YuWc􍚩}הcM?̺b))Sh^S&4ͤ̍ ~qY,2Fi̛А iL]7Q7 C`\P^R&T9͵fTtT e).Fyg}^`T$S>LHƍgX,Vi q͔og՞̫˸,  X,NRNUSS=+S,<|;Yu;6=U[wf9vO' S}+olӽ/ס3+3ie\xɼy8T(z¸i=zPz,ldp<:)t\,/޳rcLPUYANE'j綗ZLCX"gE rG ꙝ6Ll޸%tЧ5혹ItN6Ci.~ u2]p28{s5dm WᲿf NV]VWClhԄoE>'[yo!'N濪uIO/ljK1֏Xb\"'٘'io!M3вQ%Fi311SkjXF PgђS"@'MTc)^?Ym/ TbX?'#+(i9UVO>vzPp/|J^|wI Pz,lu'czJs2jdꊝaaBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2aPDm|;1 Ä>Pd 0:{q.Zau#q`-)}*om'0\@t* FMoooXkCov2aPBڽu¥)L{dH` d'Qd 0:0Ʒ;0L(N N0 JS{sDREa uj}`TGd 0:{9S<>SO5ޚ9Tk}1̅'>}tJw&1 ԩ5Q'䈇1$';0hLuLV⟑1'AGL3 AafN(\Jd 0uj}a(>Pd 0:>ru(Ua&PFa&<Qv!ѯ8S\>8c$'^afNLTOÊ >>]'ʧ|$)#f?]LzzD= ;0EڽoUG`BdZ4!aR贽 4p,a{^'3~ SĬvafN;0Ejہa&Pv`'c %ԩ=9pBmR;EaDCv2a:{џ-tO09@H<O?*T.}dh=o-8 dȘ9EJd W.z䜄7b0j0_!a(Ew2zFGGs*adxu_K'_H0D1*AK&Cd~zNuj>y'v2a:w;>Ԉ v2a:>01 Ä>Pd 0:>rd 0:>d 0uj7p*aJ/O|a;0E ߨ[~E<./~EO3Kh4=Tb^XxpT=9UKu"GU5z^_mv2a:wΙ afNCq2 0 uj`Kya'c %ԩ=1u|Je'c 'ԩ=Qi~a'cǚ3ej}^^p<sZa5{#]UYW4NOMF֏aΣN^*`*K!;uK!py Q {`9 rZ&Z>g?B?B?r-E?ׂF!Z*fr2~ND+'xξAۛ<ՋIMf}ͳXk%=U |,N0Aڻiއ '{OS!!ϻB_{0z@ ͋+˜$rW3 '(}[$P?SΫN0ACv2& UB;SCml+pUv& L9&XݔcU;L9hjUkf߿۶m[n˫P:>ru(Ul@QVVKرcAeOeeejj鈝;w_vQ8B999*awlZ,́[ഞRYKLLd:YYYj@뙜YPP0a:{q. M3==y G<yH}ϡx ;Y著Ss~~>[B UUUjKtɌ:jݻ޽ZM`l@Zoc5RXzz7}呠gQX<X/_r!|ަO*q2΋5W/a'7-5mEEEjtt"[n ~ҁ"*?Qˁa-dlHPPl@<.XڴVX݅KAޅ2>gO`+r<a\v爯G_#QXm)--E`ǎ=(..^~=:=:8l߾}ڶπ hvhh'`WsƤqacPD@8}Fav2Sf>ʂuQξCn۴q{bΔ={;e?>ՔC٩E(.IO'KLܵiӎk={ HMMݶm{Ķ(ַ41-gkΔmeNۖ+%5/9%/5 SRwef//9lְ4ds; v23+6̴tM5lڴ [k^_',5=y56SVl^jixK*!qZvMAAAff& `:ggam44q-~IE4j˚&eib^;NLvݘN|wC59NS#֬5zz[~s6m`Zi}JJKM+lmޒRЅm/Y|K\5(tc-v<Ç|{>tGx ;m?{lG&/6{f; u\q$SgE8הy_fq'wRӘm 4}"^LFg/Z1TznКξ;&ʿqf.:Jn-s;ԫOy!/R;Z>X NYHg!ϰDH# B$DxNl 3EWL5,"lL'==߸KlJ9yLl{'HLg!Y".GXjNQꔉ$"}QLA62_o}`> N1^)>y9Oq,l0;ri,ڥ<(+g`amޝ#g{ee01t'r8#m3$ː 踽/\:á/:zK(&.(G--\4ȔOGO%pU9nYFhv)-Oj%d-TTT$%%/2k%mTuuN};aC4˚ PW;<WL͘YmZ/bOx6ʄa`2x /!_<Yr9\´ZNSx]!''^fmҪT1D>IPBe1:F'sL'0-YD9Y=2kduO9 a%ůѝLHɬ61NfS_?i[T(M|[{NnGC|^qj0 [N$5 W]S#Ät. CXpl߾===؁bTĶM#YV]kW5$ F}-]YmeKy g'u`' hho>N!0&r^|X^@Cߣs[L%(rVuuΝ;);v(//ԥ2yie: @`2-:>|xQm$ܜ ݷ.d=Kee%wj$`S#!BdaH 92[MhQ%3)!H, b#݊D>rJ𶌌{W) Z[5dtɂ'ñ㏎` Plr]aRCCr/!\iԀ+M\ff&NgD B@TR_sr8`EC]v_1rf=Z8&0ra\1NzRRRГF 9r'ֳ֓V:#)!;|²j%=dn?% yp|, -[0+;29U`I:TJ.S 6b )۫0MBU8"!g S<'(Nzݺu6mU%nJoSnc}js|Co 6PqsՊo??!Qvk87Jtc!4*zy!d<TJT^n}*ijYbW%-ũ2:0KzɨQ)~TKP#&a 0unڴ lX"a-KBsIp*LӃ ",\bz>T D[_a^Zrָfb5*Ϊ 7LeBr  QYݦGlLG_C5oJa$U[H6]ᤏ/|]} WB83+%a8ꗈm -..޾}{ZZځt^2ER26 ;!chNp2{ӎP{P֪*5ԩ=SҶ=dY۳0iqA=<(IȁD1147z.7z._܈?|$J#e-QqWT aqf=g͚/9sFtYg͞5k v11ѱqOLllLl(iq(i1c␏,bvY918~B&@Ypݹڣe E{RאB9OĠ'#LOC:{M\́AZ݃ڴ9oZ66 .yĥeuT}ߵZ"C!H<&8`Z -^3 $B^zLpctϞ=))) /r8Š熃\3^3$fYEɝ]'Č됏 __qin/@#whN<̄셶'SӚ/7?ϛE x2ao6~ÄI/`N {LFwQVhF|w^p1ua8dupd/7'nv,>01s͋33:zΜsfy".n.4Ec>09F(M›Psbg|y11ѿ|f9ODϞ'll9@Yqs3N%$媭ݛE$h‰@3xJ%yߙ\o4aQ 7{DAΑEө@ 3o8"6(:B,V#LQ Fq@'{m޸yݚ7OIN֞}AFifg~A)_^GB3d3b!~Å"E +33:d`m m;N&MFK_Ycm}:.ݽ5y8hͿPرA+#"FaƯ YT- wß̘;;;7;/5<7zԃQ#G:[-ZfZƜSų><șPr>YG˦O񋋯H`ꢸ/\n}LtjX!NG۾Tֻ\Ǹ?<F2jm,24 z{^8?R>9H|~Rd9rꚓ~ID?l:vsfH;y |ϛE, FQ /ߤgq 3ezN&>ӲˑBNFV8SmXr"DO e%b K;\/1;M@1x'ulJ`W,=-&]9sq8aeut,u!lL~N!GrRPPCm^8MjBK['0*1/KKGɮUXKvW,G߂2(D8qv]p27°g0`Wd%r,\t( 벯c#'ala`(3PuQk㗶Nf9ߖ62TD'~j}S!N檝l1N5MaQw{=. {cސ&'k<#ƪz2Ore'LY㨩s&Hx έ0:Gh#V 1eLhENV_b WHU>P'ًr2`XLuؙ1d"`)ߤum =Vkm+OeGGhim{f=WSxI8g~eytY$]B'zlƦ/=͗'fM6 x<PEe4Ț($2m9:648z뭹s̞'?c!bgΊ5#vsΎ-> C-ngbfŊDGϝ1;nVظ1s0ѳ1qyscf̎*0wL8qϊQ rKWt mHFNI+qm3#Ѥֺ?Vonx۴ʬ\h?=ɓųbjӚ[j38m/)# ,hOj)?щ!{!N跉~";Qt"npҥr{_3kuXڦN]?k+Ǟ'oSU`}% kMe[cTUUѻv?$k#M"@}kEj%=dhVRZ %e d,\. 2eR z'䗋gOSYYyyER2H>TXy* J~YjЭи0v9UUuuⲲr9,;PVzvAEIQqQ~! z(:2%%III)) Fa S&Pu CוX˪+eJ[Rť ,/æ^qQ*ʷ&o1:=+AȥBzUU^e(.AW+-W@Iy ȗ]Uc OB'%%@{ Np 8p +++55lN&.TRg:)GrE/ ˈcLyi HVĚۋko,]"Oa , e@܍kŗY1"bh qAN8Ů]HWUAqHp_8$Q<= ;tjĬ58蕌CfPX8Ԁ0AZb ]h913v b:Df;NV̍+\'@><v慥aOgyQu"Q1KNNw}\#z?tboeP GzzZ*6V<[mQ r2?V#^̤tm*!MyDBt!,EEEg |0O%a-G,k*3T;I!f(9VAA]Sdi8pE x( 1TH@ anG$}dtڠyTPwZ*t%ѐF~Τ44Ny9DN 0/l6$.`_vTE.~4a_aOsd! b#o 9VkZZR8Yqqu EmIݻwcU+**ЩO=^:;wBq|1IH|E~޻woii)v&OM F?ӑؓjqlavQ:vM@[`u󾮮~ㆍk֬?4;:NDm}Q9JBtusv$<Z31rխ]nÆK.o!S=fyl8AbDءCmسgoffVjjb1|zBV."BnLc=dZIL6X7 ňvee+WZۓG  v%ے MLL& DdEF x)_1P6߸a&h˖7o9MjӦ}iaڼ2 =zM:2sشf妵҆jع+o^ 6oIW`BiY!=}[ZZJo- ct[zfzz^ؿRSSSRq^RRa?4]Q^rxun߸aӦ[6n,rCdTPXX=뱒X3SӥZmI-JaAٹkwZz&)5-CT%3`z8qٳq񔟜j:{AIɴtdE^)pR/R/fXA}LlޒV/oex_ꔾT-~Y~#}ANnrrvSrss23; f͚3g.HF9sm8DhތݒRgmݚZ3l(ߢ'ګ455={kKUj?Xw>sF_~P J`'= U;HN}%fϻ`n~Wg"s)uP.jĖ-?&pՋ3LuSOfzG$XOILWcbRcҹWeccʼnH1rr4c윞O9&=';;j*.zo@ + |";$*c Jؿ~|BVa0F.:k=&&6=Ecjq$b0AitBEcbK|@Qıwc<j2w[,{߯ƼUFeƼ JX}(fA[ wŋ-tf,sϝ2/KM'n>cwJڠA6ְWT>>Zp]X.vzr/6edr4z!ȧ zyçOŬqGksE&ͱ&O˦ĸ1 z3R (i͈LԶOkQʬŊ.8U~VxZ 5"2Q2>Iʳ;#&R K['Qu[xk g|P7X ꚓT=Wm^:03,xU9򊳰(I=8%c)Yi1DkbF:Hz{_ZcMD&CO-8[AQ$8>QCћV꾈QjX-N(q֣%]p,+9ᙳv\$d11`jH/#'[V'; 8  PL4悱ds0ljrÁXVO( j[H9VOA M;D9bwR=H@rc(`4.8;W,{' |Wh|ߞ{l=>0 n83QFӐ&_ČD :j*D?*)蚓QNJ_nM8 23{Mirvh?Pȱg3ԃDs\ zu ra˖~f=~?˹F2-dLOI_!hRל邓ud*myTdL邓u rjmbtGv^eͪ)W_]V#6o C7t|6} L>ٻZn߫һZVDGU#vz'jz^ZؾWO?-tȾ_~i^?ߟ_/9;~iH\\χ>ɘ>`׮];vP# 0݃{vޝ 0>a'cOOOW# 0Nw轫μka;]KH)..NNNֿd 0v2THHC>x1<W+ʪV@7gr )dteKjn\}5k0OW{SwsAjWwF 3"Z$ht~1ZS=ʻ<HP=gSg~O%Fڿ]ɾꍢ=Nz\.EۧxliҮ<.ߡu%?Ek:G^K/ZSCS(i7zP?jw-ҚjSoa'N7L'Z:?,&|'C#Daj%<ۧ/,:+FCMbFdH(pr4|o$'&  iɐ5`d `'c\$z['j%r@i>WJ^r )dLdffvK}BEE֭[EE1a> o}}]8&:+, VRRRyyE>12.f! )$5R8#<ŋWi]UUQݽP;_!E%*+>>C!ȧ QmL'* Dևa>,9ZU61y 5O T/ax^:@݄ f'CR]BiT;kjj*:0 ;Y8Pc%ցR8L Á3XVFSRR 鞺rFB2,%t“jV; 9X3 .݆S?9u˥c(**T scBeddڵ+'' RX+ZyY &dCxΨ*`!B޾SDV uir:#I3Q 8qST&;JeJEq1]8o]2cK4 3m{f28N=-= ˅YGUudlWD0LN8ش?qϏ-qo1 F^0z,/`FMݨ;ŠKʅ :0a::jЙ::6n[?/O;P-cpHCX t˭Ғ7l޴iG9NN ?OG?G;B]wM㮻 E提$GTP ݉9o Qnaq2;<bF ܍yׄ; 0ꞻk w^z]$ ꅿx ?wfK?<0a;Y8+YfFLEk,L!F)'ZD[㚽`v1=8tiC4,fGIr)b5mfvZ56.GA faM a,iCPY2#bTJkn]M=mPQyE׭ ,3-]ֆ U- 3a' Vl6#=e]'MAlNN0J3SsA]Nɭ7Q]MX?D,&d/~'m|)5vIMe;dMԞDO+L#~=DDsڌkMƦj'SIr2ˏ~ oqR x6*8Le.|7闢 7Bmb2r0rDyNfy5% %)-jb2&O:OlB̅i떈#!ZYw>br/`' \2b ImpWMVq-DOMw#;Hsgt$E-uk˴:ɽb'c,:Mz Z9îaEF>w}{>}kC<YZQrԺj.0U!!?&O!*NJGn~u=w5ϿVaĈFL\/q v:V9rddaQÆERaC(22rH|Q4e({f~u()*uUGE0vmc#D1PX%UR&ZHޢnoP%%-y|oFtJ_pʍT 3a' {K8fC54&;1Dy6xV9.{M悽8"_~K^c[5V['yFOcx>TcI5Ho`Iy| Dk&"`J0:}UY] =}_ @uH(*mVK<NliV5 g*VZP]--x߿_ivN⴪7nL~2< _Vj ` @I#*Oa'c@`' M[BTr/qV&@HVTT7w v2 vn֚3KHH@;; 6ω^aӦMׯR ô;&TR ô;-|)Daa@?$=wؾf-jm&|a'cETpuvHuVfҧ\_;cv2[lJT[YD\PoJ8"KNEXxDq|cZDdhDy$}I0fDydT4KTR *pX"}X. TR+iX%2P#KG3TL=]uL]hcs}V)"pсPL Nc<|ds/}hG?X^e/_vtHS ݕPrؘg6̏b9IF>rA& ;3`'cEdp 2^ }ޯUnN ɘnʟ@\m_~生 jm&|a'caBv2a&a'caB9_|90 'Mʥs2a1 0 ;0 ڰ1 0 ;0 ڰ1 0r&1 0;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ('v2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caB'cX,+tN&y`/߿~K?6&dj_\q^ثknnvG~e6nJ丩7z 7mXd|ĸi׎r1)rCrbR㑖 M.45J1vmFrim#=g_\Ma/6 445 D4ec&Ɔ{dmo ?äagS"NfԘ)cdQE>l&0nr؇FzNϊ/߿~ Gt&'*7/`oecںÔ6yЋ9vx) S)ǧnӿ5a,:.YW^?'gnp'_;#E"LqOq۔aGny rܤ'=?|eHYq_aS8 Nf0lcq|JcI]x SfgusʔVe66|c&wWTvsw{57bo{dm6瑣'0vꍣG|ؘQ~ݸ;emomƶӳ/߿¦6FC33 5 ?NA~o3i$4Ȩ>&դ-o]a.Qrh8iKMՇaNc-i0 R~ie?gQxnoLO]76?ûYuƵNo^t<-Lw7_=Io0rHYq_à^$&MK1د.%ILE$) r&r)[W3E}e`9duTVFJ4;R]uicQ2p օ!Ik" ȪO=frSc mr1wo<w] /ް8 Ky͟Z\pPo>!]Y[oϱ?1@,ҕzs)%I<QӃ9 lIrl%„|y-NxGb*ocSFrͥpGΝ5;ou'K\pWzwM5n.g]D-;׎zUǾۃW>4/F>P9bzGl?~JUEץNƦ<M̎u 2$fTCI1/h&{c&u5ۦG:{lϣn6'1=qS'VnmSț^~C7/>;\s[n4l#f,bzAl:ImH^N[[c;2߭2<s#o}q\sǔ1uc|o7cΘI#?4|׏y˔S|6KaX,VԁAϜMa"M1~ʍ ^?nxCLz0rp/F 9qBs(J|'Z|L< L7/bXAS6.<eQLۦG¥+9Ta ظi2+qgRؘ3`8赣sb.bM},1^ES㧍@ N6v:lO;^ GM>%zl-`X,VP5{cFDѵB|A["A٘)·s& #99cX,Voh@ۘpsH갌*ZX,+6|aqI*^>b 1d2Ʃ$,  e\bݎᲔ4jT,aw g0F \gY8[4n<bB]-66Sɴ{4Mx1& f2}t QtXu:c.j)"ݰXԀ2&S5< ͸XYnGǿ+v 8 ƳX,+J_}0  lCx%"3G%(ilzydcrTiW QÎǿᲛK>o[eLhY,2zbcT%fe`4Tr;k!$ i8z](@9*olLS) 1 C %Lrb|?A&=uʊLμbXP!ۆ]в=@LJƍgX,VwobX/ecV)bBNlcS {VY,+x_6:tƔkz卍`SKDa X'%<X,Voʧ)9fٚkOArZ躪kѫ-RSlcؓL]%f/Ab_s޼y4`cX,ac8fb8ԕY_l6<aXldPy i^=֭C\޶Of۫(\lc,7rFO펍Q6Ithƚ!=D'oUG $IFS{mI ^bO|<x 1Q4mJu cmb|IK<Γk!h=z2Y$r/w)-|qP,bpo- r0J6#ېm(7U!$٘sSbYHj V p;䴷D^m\"߂ҷbH+qSukX6.$!1sGSSӎe;DehhihX'%t ~0ІaҨ%fhj*Xޔe;n<J+r±DCGEz۲EZI6)NLƪ׿S0 s{G ȇl S[zc=mqT;"[oX L('acUL6ƚF-ke-$^dlLMX43L1[l'*Q^Mbg$mbػ>-Y//kҺae[3`c4ۿxQ͓|uODc3. dc>EaAi1d4oaOZ٘ Z@'œDgc`0 \JtQL?6fX'%t!.lQo G-QDKt3NE6bzSɼ~MɂwW j10O>^lG0I ݁Sz]6bzSluBSfJtMd1tQ; Hy>[X,Vo]c+rzJ!uSlc,76bX1uaaB 1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a`UBv`c pB??`c |60 ma&4hkcK]QFMvH@V{DX#T,uEz簍1 Ä ~lGQ"ja.%> *@6* pcrba˯ Hb)`c :YEQ =3!'0ؙC'3y`c :76f草6?9d:lc 0a)ӻbCES>#U290Llc 0aۘOaB11 Älc>ac 6PTma&L3Ӵf?bc 7|60 ma&4hkcw~÷r|S>W4ש)HmafƢ:wP<s|sG|gJZ2>aTdcKAjH ac)4z"oaJ[IuϹ^^@! h,ByQ>1* "'H1 8bחDЯht}r4l sc^+)!D *lc 01S60 3hat0`cp鍅lc 00E%a„pac |60 dc ƴ1 Älc>ac |60 S K/抖Mamm^lmc~0 tژ[|{W赊K&n]bƼo V]$;S|mK&{Kz= lc 06FuIҦ7όo3!A{cd~##ӻwz=4㰍1 8>rh?b$ s_GP,ZvC2E>l:1agi7ޠ a~l,`cpu(*60 &0L61aЀm'lc 0A8٘c0lc 0aB٘ڪv`c 7|60 ma&4hkc,5ޚ¥TkMjK1 8XGFM9-HQ}a9⭉o~ Suaj'71Rɡ_H/·6F?*A 9ZQ0̀=%]6F1 Ē34g Swad=FP%:lkaۘz=ZH@SaCGmz]3ǐ2㟉^P9*$$r^BD~ >acp._/dQC1a#6FwԁQw`cp`oacpu(*60 &0L61a ltЧ$0Lf61apm'lc 0ۘOaB7W)^S;jԷ5ЂzMK&R0̀go8~7"G{5|Ugacp1ttkANǼ1_qKی70#^ntw-b^b1T+^,Bv/˂60 3kc6dc7֫QL]aXoOa^¥uՊ:S.3QZ|ަ0̀CuO6&/`W\QE yKC~[C&pDyϰ1 0icCggfPacBO @X?maff6֡dm ɵ 0L"l,pj%mⰍ1 Älcma&Talc 0J8٘c0lc 0aB٘1apm ,v{Iii?Z'a `@ٚtU321 yؒ˖o>S#ZGJ'y۪Pzq[˨L/o46tj5HO&֫cz<^Bo;+j~x)zt  z7-^2uFhc-?]>]$^L Dir,,G G̎u@&rL1PRZjg1 y|:Fd$^;Mv|z/M eId6Vt&% Ƽ9aF*FKքfxR`cdIt6F>:U 1It3vc >Ba(^f/ %<C^"RƘdczkMH=b*4Oboҁ<$J>{ҷ=dUfot65ސS6t\z!rk=dcLo}1|\XMGd׮`uɉG&;%<f2tۘM[6t@[ͼWbc"CN{6&k'bc_u {2'}ؘmazƘG<&3PTmlR^^n#Oc󄓍;1Hkى;v(**Q0Lź׬ͅy^D{ۙ3QWxrss333 a|N6fSTml bwܙZ\\e***H;tXIeeezz6X[n۶-??f 3 33߮i-ݻѭ?uYYY`]vjҦ,݋Q5alcm,ؿ?:.8Ɂ娑T^TTFhdtmp*5a16यFS6FVWWާn7gffwR Eژxozɽ݉{_*ʹ**>؇wm,L())7|::m]ľ};vذJϘLJB1sDm,@~tm,)++KOOlj;TFDl^0=K{1z/@Lrͩk¥ax!LWCyV#bc}lc!Feee U˷mۦFAwl(,, ƆkzfOOm3`=ە ]LƼ' a?zI ɮǨ19'C=*)lc!Buu5\xԍ/p^V#fuf8YHtpAF QSjjUkǤT1!N{1 LHĪm?uW)vIp81sdԯ_B} *)>肛m{@' 55*'@IIIj' }Dwl2=XB_Z{MKKWOWKMTRLzo7{;{ lذ"11ǻ8öl٢{ cUVZ>/#V'c' Qdc}B 6vtm?w;ծN4p25Leo}vv} 333ܵkCM5.ewٝuBv2Eꪷ;X 󱍅.afc܇I)--)wܗB r[z~0es&%JKgTRҹOۛVi;rtfgf姧+%'ٲ%g̔zfOEEEi\YVV}c73)mgRZnrڮyivJNKIݝ;5-/=}OZΣG Bp@8>G1,_e enKAi+JO}6mܮY<}-WDG๛Z o*o߁!C6֭<̌uд}7ӣiإM IbEW6+-٪h5Sh6{ca2N)7w}؎;"Lқ Ӳ49uJoW TTT{'`DCնLUK&ҨY.kBe!KePs7v)[d' U'#?'crN)99EK7 &kMW &gT-~y {SppuՂCݻwضmۆN0ސ?aQ6JE| iKؔ]HEkh 3!K8٘c0B_N1٘ܡRf1NƳO/m,ٺu+llÆ 999&3](<ݞjg٘xQ%a>Xgc%\zڤ.Rw/xK^y޸ ?uƎ|v mSW&/m̳Hkz6u\bQs 1٘kG{Mͳǃ!:vHAfZo93]EacdEO\C7`]"N o{YJk/6{}HgmRwl=gNjyN$ƐԾ!JRW\jmLcsVO㙤5h}r_N,M~]=cb҅G. Zzzok<Gy'QX12Bĭ21,9偐6IQ ac`i", 6&sdEؾWvpPYL6VHU_^rAy?Go %LK;I\plG׷#m<qCݱ1H!m1H1aKu =´6F%uuƄ{p/t˾85!my eVjcH$Ð^6~R{i<kM'1H1|K1 17}2CtAZ/q:RNog&PL; r|)ޅ(^(r*aJ(Ww ^ h8pzclct)ƄyЧT-~ƺOO5 xC}&hQ@?HHHoZGyaVf&->)MfYE} >ޚx:)HAZȌZ+O&0:RqX>*Ӟq 00ꊑ3^mh86(q]^{٧wIɦT-~y"ӊUԂÈI6aK1EtlrlYy՝VgYǃj-߱}{fffAA}=5ꬑ GVcz6F"cE 0ژ[ژd 6 &N˂7)Dw wڬ!0qSXܹ+_15FUdO+?aZ _~״jꥪdg-Z*|q%~OͼGci_Z΂t:ctA W;pӐ i! ʧF( 6m,ZK$Mœȧ̻Fl,~=6dȤI z+-6v^|U⳱g }GT<C***/rݳKRM9@a:RSrԞ='#'˴*84!)!a֭MlƍM9$mȰ\̔])9);S3wZ-;5#JȅRJٶ?)#jk~A6RX]]]}}=j*&|̨{6}MZUlhh_ ~זF0@? ߆vi 946n܌QG zOBGf7jjkȽUG K$$\EIHP 4J9LY+QQ^uAtg:L6рݯa *iiipW uVHg%sNWFF&p[Nt0C#“01?ltS۷ohDt cF*FX_ar,:Gb_&ƂDAAA?[棣c520? S2`۶ei(S,iWE >2 -gr),,޾};\tQB3zZtgc?裁2tL88Sk251xxˑ?sEȍ0Dm2J@/泥B8X 7*X_&z4OBg7u c0V!^ҴZY4vQYhH`*z&@[߿^rii)P>Y-!l_&z.u6G{"oEZdGҩEF9H`X]]k.ݻѦ(&ge:1z7&wF)0J\."_ƷT\i\EJ#ES"Ct䊫51N+@SC|g"莋䔅=Fyt+D2j\B%uCO$\g ~SSSj=tX= SZ *`LC@g 4#B7F 6=%>&anw +$L`&f4rA,EZIda` ???^ӱH6$;:EG/pdeeaQ9/y(j[CYQbC!!Jci^4,b@hי*lcgl=:X$,Ll@Z[email protected]^~, 6 kj8XZ=C9Xvjk͛6lP^^5cx* 6_w8"zfHtowq"dj8q%fDlv:Z$uQ!.3$H(@%HP)-' âu {eY^7a=`c'"?`|[0g=lnrޛ\H{/\$B/ $$iڦm @.7ErfV"b1 cky{fvvVJڕsΜ9sfym+5iiKKK1'brDJ5Lh M& R`!H,[ lǎ])̾uv%/NO]z8(ǻ.%5e7Poddd`2_X LA֭[WVa^=u u'<$5c1ݛ;f|/ƿziA<op?dqx4荄["ٞ*fXRp }BxCu`k4F[ká`Eze=a-Zr%1CK]\} <!Wp}nf;N;j]^ z_-B7?>\o/΁F Yŋm7iz^M6L\= c}]`LѸs"CQ}8.\0Dgi fA"z7XCŹZ~ %ZՠB+ ,c0DYʫW3jZjW1Ы0˟2\bظa#Q %%HQ5Rs3֧aFLߠ[߸ itC %("nvvիSRR WXK{V\NU @ _UZfZ l U YaM;z#x ޚW.YjJ˔/ZrޒТ+}sbVEwnsm_] ټy3n+6l,|saVrUHA0k7BZne.d+ǽӝSlEVd9I +ѹ.~s2$h@he&gcCmmG *:ƒZIU@Kj\`v@lCC* %F`.q![V78._o1FNeJX V/)Tx=>]Tu c03uuz"a #om=ڊGZւ%ӊ 8e+ET> ŭUBEl)bSp߬5{VRrRRRԩSCDB|\B<O( dP!>.DJTxފ6@kIC-%&}Q>wpLu !Bzҭ<]B7>^fK 3=\lyL{tqt]k|:f1u+B-|C֦lꈉ4Hnq15%1u_z"5mG(ڸ~c2+*XHr QuЪUtV?6[qcxQ1c To1ҤIɎةGM>?ӶEsd/'a1^6pz"a,==:D?E,D'ĶL: {"W 5pk˷hdK~5~4{ZZZzm!Lx I3mڴ3fSRL+> n*T |ԩqSi8ijĤ8ȩdXAup)t tո\)b刏IVRB -tYʤ?9 \B-Q>:҆䏻fV'g(AA.&z8=2rWo 7 ʕ 3sV\\LIO/ܶmkRS lϛ~^,<qXB,*Oo#f/{wzpL:~$^k:NR^xՂH50j$M칔3eE+P2= WAMINmdeexݲ1utIdࠔ}P6mZDD4*O45)>)UIPC؂!˅qHH8%qz\fLON"FގOJ\bZo[c$qp.U.ջ27fÁwbgl'Kֽ<;,Dy|=:3RCE a$8@<i'㮫BA&vͺ%.^8sKwS5էqN#pT}0x{Nq0eۉ2jw 08|0 c)F(A):ri: +\*s()K /x;[C鏄{s8ս{6d=eޯym>PS-|nNYXbP`Vӹ|‰?Xx;-{6z&fӈ|4{0'.~ME<s=;tlBT !Po8M-M*=NLqSɥF\z#OQ@8i*{-DwgO238'7auR%^Sh#[+ohɛtE{d}3߰.I?bs:s.A!"އ#EXR84b:>cCh 5/3_> ט~cx†>;Qs AbPR<yqnD[:t#ȇ%C#(ծ{>G4}'dׇ8X[v cw߻1Sʭo~cuyXճ0;>Kc/z--(׿N4Gk>@o^BPﷆJ0Da̫Øi1N(KSQH7{bbq_{YcjM^ K4'Uq?Lԑ(؛lڭ1SÙ|*ұX>3>KRь?N)+ c0:%UV b!!.iE!&a8D!!zR I-̿ȍyk1lH-lж{ ˜ #Ӄ01O6|BD#ĭIApVjbζ< *h-%haa q{!D#ɦ܃T5-oW=vc@C wP~Yz}, qa cMɶߍվ/hCƉ`|j`\4f|UrV_'RyK$CΤ3(E1X`[_8QQ1}&Q-_ppA筣@Rcv 09 c)& E0,1D#,;n(DedHڰ{`7FƎ[`Ucǎ !_ crC4 $P>,B. X!CC8<a cW5FE:/[u,0f/ Ve~rcĉØrcʢn &_1s>{1=\:c+SEV͹TOĜg+k*=ʓ ?+ 4f;3cTUo7u3 SUQTa ^Jm -gUa@UK].n,L u vca!\Ƭo-C&5ME=cUXsV w7][]2Rsz%a(raюay mןusԼsn?̼3q;] $uщOQqJqe2D s<곹[s˭7o+,t_i 8aAUĪtb+g9i;ʟBTx3j!U큖Tz䛃-EEeuuFII-ܢ>0@R $L051F- Eq^IqӒQiS⒧zb|B2 ԧ gO0&`O¶ɉI+Vj]r;񎊝8j#/ h>%(kP";c=aTqqH߿u[ 7\}L]D)æ Ũt9n,&n CY5&vQ/{SCO§0F_}P c8VOp&9Ov ;tv#L~Il<*ʛs<^G};Ńrmؐoj" #a *" =i:FA:]oL֖Z64UGKZ FLK/DKN!TRr2bN2Y}'LKN"Iu3%ᴤiӓMCJzCI?``zw5jxxcG}*;'A76b=ܢ랺A7>^^m/!*μk &O dO缲5[Cԟ\7яx뼍ކG%f[c(7 l7"/GEyY7nCs QjWͳCjw4^~~ttwc_Jpr^Nr }mo-,*<Uo<`ƍ[l>t?z&)}ކ1rUoN2l%-+!٠j*h[xsI5+Cq~U HJY Ue.$N Wj.=/G=|n]^VQah{v"er#apt:mR2ݜT\Rb+iW@Ǹjj[ 3Y:7=جP(-(C%eК)xC\NUo஭q9ssrrs.'1A E2ok<ʲJ:]+(/.ؘAgWS'C)@j́ iD,~{zoxXjYL}. tWR͹! Nt=E-t ᱅ &\QkOʨ@V$r(JHЃ-E!3"i裣\rZ36gPu3 x3::Տl@ F0o}]}WKhdPV7ةk5{FtӦ5Hcޢn;QjpBjTgR@\V[·7%46[XPG?GA'RTTe K38@jTNIIAl'^15Ì gt}-Mx큑 yZG5 ?4oSӑ@N'Z?]V65ͥ_꼩(%555w1zq:u֡9Q=]]+* qwÆ D㗆 tF#u|yb>ݺu+2<eM$zG7:VH!baFA5[P-u}u0Tjκ1ieggsRQV***233׬Y .tI_ǻ淮t)N۠CRU >e  R^M,M[XX3]1 a `VҩT4#OqhЫiZjSe0رc^-[+ ˿ UQpA9#QpO T }Ԫ2= u4Tӈ˂͛7WUUYۙ쾼|ӦM֭ӥB{*E jd-Po]==Bb R cWw)"s`R-4SS-̙28bbcOgVY9Ϋ*++q& w9YHIII"?"H` B.HEC] cu{BJH$7FB8` # DLD5^o t>bT#!z!P0m `;|[email protected]rS\\wuPEXd#y -).ƛ?ZYg@1+(]1 a* /U  &\$0c4WSSq/k Q:a}>  s0kvs),'PgB zk֬F}b9ba,ZGxԿ xw-E8"X; k$6otׄ0d+yiBAcKsbiV6 ]TO#РL#*++_ǻ,//Qm|_Xǖ-[oߎ1^Ulܸ7AװN@իWD*V ֭i 9ll /H#Hfvp|&/ xD5 0™póGjj*?L<0և Bًr媥KbY]]D<I,//D/Y7|' *uﱌzLުE-YX~;!_OϮDcӴr5Ͻ 3p'[1Çٮ`C,X07\>K@=ß~=ڑ0WY~/Q>ܥMaBDEWVV566|k^Wj7{P*UˏWS[񌩇 } Wqx32jGgٚK>`Bb4bLm^ aT eզ:^{ i+TCat;Ђ)QBU#Zl92CkѴC;k5kbuY OD¾]!aѪ@r<[͡H=E Yr/_ƸBT|P} @];0Ž̒3́.| $ݱc粥|xTǬߥ9-Q0f}MBDjUʒ%[6441u.㍠! i\!Hs]io H{:cC*PG˦+D`6+">X¼N;gӦM ~(++۸qczzziiu+WvB z֭+VXxiHZ-!-^d2L ˖ĴT,]2tNYo7co4wކ@v^FN.}-DZ4oiś +WNQ?hnּii$Y(_F6@ε.mݺקܹӴbvSRR/[QJcU%x"K PSGtA$7jIIqɆtcRS8iiӶdn8%7eOZ~)]X(..FHCLECLSD!j._6Z˖/hK/c IIIӦAIJӦO6cXVyuܥ).n{T|Az{ Wc橧'zd}wp P mR˖~,Rw}FFF/ච;wq$%Ĥĸ8ɣds@<MB4̝;NrxC :I ,ɺe+7kv*7|IMpҢ~|x@!̤_  c}]t:|I0DDY.)*UHM=@SMޘ<Fn)Dӧc x衇u?:ok.*ú[ `lūшNiDiXhK8ZE JqOv1egg(ԿRؿ'%[Prbix$p$!x񲩩[XhwB^϶p -}t E[dB c؅>AaLݻw[aLPԃ<I^cg@Yp{ Ϝ}H c3Jv=ys֮Kӯ@ al _EX ˢصo*NMNbϗql='to:M. sYVduF7 :]U5ZL:;v}MZZ>F:!a)ԮFأxk~x ׏{8Z%r/Gºsot>0Eªu^|X8@gED[=Tvgjs==/r地;)Yٹ&DQ63ḘF*POD6AvEcr.QPc32Cup?`z'G?+RSOnVrrru:ƚ[A1hޱ2!%4r`}ݒ<X]ر<\Ɗ|DX?a c OOLzWԔwKpQ[BW߶~gBۯ>H`-Sg<k>8(یOk3?wBI4!ѽ[Q_BԾz,N3h\Cs.UsG_hʍvՔni m=csݚ7<?jmiVGa},հw~~d`~'Jټ~SAS `(yv*DtD /U5F }B7<\ytW#P%bZr?E1l6<>vدvrPSڸιꀿ;ihYez8WCKHli~3G2PX^{VhFElJkP,w4GYu?DDl1RwSlaMW"Veo-_\9gE26d/(&ƚ E1cp&HvGs9hbdw0&LzwGz cVݗϻ1l̻8f8Djo܋BD&d)8& ϋM/OCh 5o?eMzWoY!V+{ D51 QAˋ9- al_(A96AKuf{Y};B k#n a A'!  kEw|lưD h Be<T8yMto:D}[GSr9*Bx !!]O,06yS7x9Nvx?/@a"Gg&EuEg( %d cH 1B<0fn Hma c.`j>ꆛV"aBB4B0CUȢYlÁ41lH#?Z&*\YUC\zU;$5qƐh~/ ;U1{X$ ې0ѝ蔎_al2g0*Yx8EH6hQ !b!!yūKxMLD!.E/%*ƌ UWs0 ܿ{1DCPG7a wWDP[߬a A%ǖPa V0gc5p[’h cZ`u ؆sn b-! أOnE>nDMBb^Tc0+k9KC1c7v4!҈^-_쏝<菊Χt7UL50򖏝06ܘ` ch^ [!Ae;r3 ]`؍oZwxdQx9;r&,3Ɣ91DAApxO=/0@RpcXARՐEjii1s"*6P?*|a 3 cz_į;ʈjҐ1$ Aa G^"36.=c6EZZ1tOcƌ@!*#;v?>˹ vcU0vV!wYjQa "Q ݑc\fkv&BX` cn,\t͍u:zokW=cVa4[){nݛN6@Nt-3= c!n,\u|c2w|: 3fн锅rm'\0l[ں~K}y݉N}7p=}d֬;SwS6na %]]2?=lk[Y6r?\cH'***R IIIkBnEt]p[p Qn+fLn-8|X y@8p@aQMlڔ1m4}Hrr򺐟>:tEqqfV ^c~ '|Z  cB05YYYo  cB=1555W]!\HzEwØInnMtFHzErRSSKJJt^HzE/ØI~~~zz7~D0&p1Y8OL HzExØIaa!Z @˜+(mO cBXf͖-]f/)--Ŏn Hzŋ`tٸqc^^Ԃ HzA;X۷oOIIq:ػX4AHzN;.a!aLK]ߊs{JVު{oplTsfG(!r06)=?qcHB|ۆn=a06ԙ7mOC`m9 N70&B/06Ա1ro-:Uc-u`5|ԡ V1Kδ[--.~{=Şgm{~/tAh$ ula"SipGH=:Zp 6D}1|Ec>WT]z>p)}_f Ԓit'5޴_8B١=v϶"!1:>!!=>ZFC 0&N[7  ٺ9~D mbG|e0%V#\32˩uϐe$w0`(U0! A5FxC3m~dUWQuƖ6-HDP7 cuȄn Tk9ݛ5~amnY$}C=c`́0Fk?%v%1*n~KSn,M*'s:ƍp1Ɣ!KEP(D5=n]ču,8fu*VYȊ ǟ 0H\>Y.蔛o6Xy{g 4Ƅ'zчm3u_먣ZhRVVyιoZ(df 0HrmܸQg"\銕+WTWG! `E˜:1TUUv1YD D.; WQQ^SS55xA]__ B:4ɺ֭[αSqfPΘiA c<Ac@%_=Z1A&EQQQFFQЀCM,?Dz͛7s<^" c f$*v90YcFZ%s0{:ߦ 0x/j%uA7],l˖-#B!a, E1zM*0H aFYSw.ΚVaaaVVVii)E b$tx1#UUUfA$E9A9[tJE2fI<AcvH9}Xj?Ak0_ٰ_Hp wp˜mM8mӹP~FXtG!ĜH=Q}`,0# \n7aLx)BUT=?D"Pk @RRRQëLxU-a+VAޖCh#u։9~FXt0 |d9̨B$ Q_MEfVa3F7Wi[mAʇPNT-jbHCB>r,ںu+*#*p .ؐ7ESUkRW+͢ X%L cэ EO( P!,effcݾ};t[í081Jdϣ>WVpkT aYTT]VVFEuuNmp1 fYVKZl5kPvUځtX`p:/B a,dL.f^3%6z <q+W?>["uaq21,!ʚMT!qZKuf-:+)-&X3~aW(r i@ASLpn` -Q5܁*,,LKK !Hn|&மs"VxNԫ*ܾJB)h᪥[6ecVWQ1\V@DNࣿau_EfZڪQ>oߚn͛7[~ . ! YUB5*a\PT]"-_U0ڧDngP=&9Ȑ\ B0xk˷zދ>o33vg!:3g>nig?pyZƩcVÜ>O]vQ宸{;~EƌyXYci9:s3Ϻų.zv6ܲ| x}gIL J3g<.8‹.",.| ߅^!} Pv!_SQ1c󹐄.9ywCۢUj 5TsІfV+n .8KKIۂ]@HCv%<|/sOee7(覴w1qԭ-&)dc4Ygv͎:;Nszzeat r6_}yEE˓T=ʱp6goڒQRNSPVݩkǰaða2@&(b!u ހkbZTLuQCn#Fq0`)1=nQ<Ƣoc} 0qǔx%$咩1:{cg?o}pCj8sz<x4՟<\72bd\㓋Դjjjk8~qG!VKP?Ge}x| [pt+00aTprNCԔɱQב/X1:@o^B0fd[[չj==Զ:t!@s#61, Q7b)6/ z'b9"5aÿs`:XGubrwh/Ço8P#vw}K>oj)Qh b'/haGƪ  ף];G˜  cM}SQlDil%VznSvmC\^hj޲NӿW߶bA:ՆVag;?nΟVݥFgoۿЩG)KV+W_p-tY[!nFZaKKˁO=?N{VϓP~М(Okl%V wvoz@?iiݽ3 _5ϵU܅[X kZ}u8-dQiU-5d֎25Ј:`w`6GuAH'ܲ>N<9&_}d-tY[!(;f=s0ijx?XSoٿOVyjDYXXr[U c " ^+c-G&DIJ?Ci9x%?UB>}q8{el :6vpVmY̐Ua=dޜDUt~Ջ-tY[!X7|qkڿ]O{ᘵiH_4\06kzGE ?a,fDABCܘ$N cX? ]ih!tyƬ:l#RSbGvP9!0*,m*݊ y$E7ޣnUNh3Ri "0vy^hQXxABL [L:0z#a ]VVa#a,q6V_4%Tg|B}4?1ԧeuz/=MQh۱k'8np$)o)vZDGl#f{SmΊ%FO=wC]<쳿[O)W8þp 7*ՍGObXE۩?HZ+c#v~_AuNFF5,uKsnE<ƢZ|{\5f8GF@#=4 G<;˓gtm_ZB<|>lK~ux=<n9aĽ'{CO%9i&_z5NSm߾k=z􈑣GEihGĒ4rHCH#Q45BU5r448)tMUoQI#G>qP4z4 PeD>456+ں5_[Wb!Oꖮyrbq" Ƣj_vz<Foc#eݍ$ u&Rȹ3aMFOz|zP_`訄v !U{5KC]hiE=ǃ:v=O'꽴D mՁUƦ;֯__S]vXPXjZD^L̵hJ`ͶmtJN0)_m1㢟Y!# qRDju^=>ixjQHkcu<.wcG" {Q UZu(bQl?ZZw@HZT[PP[$v˂~y(G: ǶMV0z-^k4BUއH0 d` O&z ]zVaL)fd#Ev GP(ڎ*S 8A,YGQJoZ6C ݐĶ cmCC#lSYYyYY L{ ָ%Tn°"aLBD s*gV!ӹv̮vxa>SdMf@ (!D$ CT\ W t°b:-0333WF$ BHۜ@.1F l׮]wE˜ 1!a+zrrrڇ1!D$ U]]]SScF˜ 1!qaxY&55u:/BHD,IҥUUU4ʁ\yA:F˜`߾};f|8lzuԂ#*..A:F˜ZBg >Q8Ƅ ;c W^y >X;LO۠" cB)..?L2wʕ$AHzȲe>5j>NYp&1H coHz-;X>TgT:6&vs8FٵZGZ:ՆT/8ffN):Ӄ0RՆ%W$&RNΚL]!aL Hz-QL?9G;%cLfE/+F&$ƨ(;Q+#жZ[}B^P GT8p`_p*j ;=e6:^:*L#!rKyX?zk#VKk5kv537I3ʂ>nݎOLl9~'oyȢڎV&%Ʋ$c*_{VH1a( aL!;@1/ىsB f@Mäݘư-1 0kC6QY{f\>Gp!-aO)0n(i~#!?n?mׁ {'aL HzH_CLҩPP1{cdF:k$ C cBYbڇA4$ =ROCzX]NG;нA1礥ϘqۭL"z7B UVK/007o~YY j$ Q1A!0& D1A(F˜ HAnoA!5 ڗ}  c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!06+uNA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ P:' Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B D"H$:0&D"QJ˜H$XDZ#Ͼ2d<duUp:*Dll"\C .[![ByV!e<duUp:*Dll"_Ǟ|iqacs~sUՉc1&5'FzkFZO9Q;Ff #N8~' 1^=rܵ3j5h T$蚑Ff4jhiulkFxYO9;zęW8Nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[E@c~E߂(d9yտ0cgN:qμ~O9zQg^q˜:J8\DK75ahXrkJGrb'iWF1c~u'jWs nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[Eݑl5{'^Zxek!(*kUK1h-ȉ1ʢHEw~u'“.3~qaUs5z0WWx3SN=oo8n#sҙ̫N͈1W闟8]q9[N>Qcq'qZ}hX>n{% ؈Zל4c5\܉tc &ӯίzY>N.'#[ByV!e<duUp:*Dll"\C .[![ByV!e<d_LVʺtbVO4\~ïXW_39:c`6F޴w߻&x~ȱ,|/z,bdWuBGdNtŊ֎Rogג/:>~1q5dv9N9y3 9Ѕ?q_FFN}U2u/?|_~}DxL1k)g&17̫N:μ3=~so8kO>>W?>x∱W8ˉg]ukNwͩc97rl,{bBByV!e<duUp:*Dll"\C .[![ByV!e<duU|/ ]12۪!dfN(.w$ke. E#Ǿ2,=:IDATa+mZMN'`ta7 ?Q&ؗ 5ݑy}2VtOj8ض>e6fV*w X̽3]'6O{_sx1ן|an۷7__g%>E<wf.xጋ&y</w9w\vM?SOdf֑x:λ_{Ÿi'߼fug༿GUyGw$kis=Xl"\C .[![ByV!e<duUp:*Dll"\C .[![B!.V7ꨵvOO0Եn<gއ_1kBzuUboi] f؞vW5uݕi`^XK Ա췓cU&*[f/F5⤱N?Mh呲L8y̕9׾mn'={3>+O=cם0_zq]8/yzW O7wj¹W>z`:{=3g|ziy:RK//μ1W;m<sNU*J?+jCcHel5Y]1o.+ku_&v:yˊir6VUUzGR6 3T%AeF( j|aQΛNUωe׺Y*Ǯ߱FH3ړrC9_믧>|eSŋuMϹq#μvm9G{9:r ]pU7,y+ܫոko<-Ly3.}5ϘvٓN?Gbę7ܫN: r۾}D"H$DC\]l߇ߐu͕}rGzBs`ДؘfUpPD6 D>|üp>]1càruhlhG\hY]V1axȳ9Qg失W2~ c&Ow ;a#Ϲn{OU?>sՈ&fm;cჿ:S~w֯-v5꟏iNċ?z̯Ϻᔛ|hi8;1&<i` 9a~A]xCy1GvFβ[wE"H$DC\.ʀfdu6ud3g]M~xg_F?ixԱ7uʸ^?z'qbiO8gԩȎ<Ϲǝ&;gMy{cI\߿rٗr'r~Gvoߍ<~_'1akO:lI㯸+O8/>?7g'?›Ko8ˎ? ϾӮ;+1c"H$DA1ՕT'N!~ ¡\w4w?Qg_7 '</|oǍ>{Gϑ/9g0juN=n&pU߹9G~׌>ʓ^s9'^yOwco^~ܸ+{3'SιnY׍ȱWs%-M<iܵOu6rhc뿞z֟Ν0c.\$D"H$$ENgElm]qTFyͨ׎>g]s+G~7 Sն^4aX+.fx%$E1]ԕ> BkGv8z\>W{v::tWx'PMޑH$D"H4x$~l$.c`cEOr'}`D\X׌׌ JY5a#¿M1n"TRv_lμjکmTaxM<鬉'u-ވ3qU'Ү5H$D"hHIc&`4I9t\UeFj? $2N^Uc#NF[^ʏY-lưV}NN+GȒ[gYq]" D"H$ *bD鱆bҕZX2ieTSFK2tqվ]mh$dԆj[]SUTD"H$;śA)vl5;m[N'n}H$D"(J$~l|'5u.VmeorGVeH$D"(z$~l|2Mр+Ď٪D"H$DѯXss2>_`[wj)y=\*̸qOVo5^]gNƥL>h]BdQUB|ȗ"H$D"Q?FvwtKMA}Ǵ/RH[BmV*ve|E"H$D"Qc?oϔʽ[I*f*T~vyvEnw{YW{P|;%h70*m GM v*SIm4`Lw.vb^U+-D"H$SOm Y[R}g *4nF)k.3E5q-loU`/ҝYۦPe0z^]ۥVm+=v?2_iH$D"H k׉"y qs k4Q[w=g ʲ#G҂i'&vRNʹJY@vhTo\ٶ(H$D"H$4uqR?<^Ow|8~$ŏD"H$DEWZ$D"H$EďD"H$D"Q+ȏ0?UW$D"H$D}-/c"Q8K#PN+taH$DA=n߻n;n}4]Ռ ut[}Sp((ZxAIU]cZeSAW!a[BG"v D"H$uÏw㖢ԴmN؄B<m6@3κ{[ZC"kvBbK®?pӆuTۮcz! ďďD"H$Z"](3 6nmmyL߆e;Q5;:.cΛĶ!Kv/7> ~ᤤm%Xr˭(autscG l7|{T%c'f /+WgM? E*s܏x>t)Allg]?哓#sBKH$DA1]W7py[oӑӉ%pZ]l=J6`^VWf=tRi{ǬmY] ĬB_<gZSpsynW#(Ѽ'S\̏2Z 2hm͘B^UtIvBc-Dh^KZedYVM7e\tlYm+c"H$:} ތ֢"clB6lSWA-1mj|K7 QڒMKR:t-V%Z󸚥tS|o ۪Pt׆?>Q&Y4T9=^i-\hȮfLaUdXG~ j׌AhY E+&;ڌYB[*=$t]ue)nyJ~̨N5KSAl;IH$DA1w?qkhqֽݑہzpY^PD~nmK}66o膘at:o֎:do뗔Uf:Ť$ȽK{0cEmU'^ 9AՂC{Lg}^?h&l13aBGymn ފ2QQ:D%['!ՏQIY2yi|rV57JH$DAmn^Nĉ㡫]^[%rte5gb1˼KFQ,v+٦i$m3crܷXaF5cd2 ,wG^aeդ!kB`)lUHcݕ-?^D"H4(ճcm2s誗,ȎAm~G==DU>PS #,6[ d>{ezs?9KNB3c?~KH$DA(%P8;FmPĀ.: @XďD"H$?&H0<.[E"H$ďD"H$D"??$   %AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AA!_SahZ=B   cCc  Y:AABA   D]}%O^0լ~aKܸ(in޳2Qfw=v[Ur%]:s.lޓZVF=j?ws_yc+E!V|0AA!Sf,௬tPM.0E%1ls'ƈAAȢ/mrM'tUz0s?'㞛+k1AAA,zչL.[@/7:vOO0Z?&  E~L4AABA   DdžAA!?6t?&  i{an@   D"vSǑK   D"c  0$?AA!A(~l{u. g]n>,zQhYoLwN۟jď  K?36,{V&Qj^37LX%~LAAP5+ys5n^5In57+V+kcT򄹨Tp1ՌB=Zw`D~lWBAAL{eNz0Ț.˚:"bY .4q[؞Ɓn*G`l̊1AAAt5LdgծC6Lo'e3m1"ec_l٥`~ұKzYoTԀa.ď  [L,Eۉ|ď  g~LSď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c)G%~LAAc1AAA@ď  K?aKxfsJ>g %ByKg\I󞔩F+AAaHХ#3 ]:ۼF=Y<yyœԗ.urVHq .Yv{a`m:vQcc@5^զ?A   c&)2]۞0UF Xbfjɬ`x9=luMXZ&iצ?\9*?&  C.Uhd3F&G^|f^թ n*ZשFdTH/k5@   B?fż[BX?&  C1e~P ď  gDŽ>E   ďE z/ݜ1AAA,ď ď  Bd!~l ~LAA" cc=n@   D"vSAA! ?AA!D   cJ<al@zCtsNU:yOTޅ3l쫹y'w6L?&  Cc:#`.q<· \`37:c  0$zu(~Ye7hk6ԨxhQ5u3Jۍ)vw)kǰ-ZnU칹[0mB;L􇁦Gʹ6%!"~LAAc~p1=afcQ1Avd^hOJ"X#1VsE.Q5k-T5>؎3@f>mނO]AA!AH~2TtoJ.{P"=r50xZVwՌ:v?40<S̸|T2njoFY@F{5$AA#c9?3Æ2Q &"ݏ?AADď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c^ ~LAAc1AAA@ď   D?w=ҙhnWMtG47Y|17tˋ\ͼKz^n좏?&  C1..EN u.Ԅ2 $-XSff f Ǟx`ʦڭLVPmwh7{bcYǂv7+k_ YWuYgAA!A\f!]1j6Ɖ}m[ئ}2֏mnS6gl~>T!~LAAcM=ca_؋ <;0H;c{W͚? ԹkY ҏۦ̸m^e14y?c   tE~П4Q'^3?&6ZÁnKÀ1rV3~!}R3z?&6@% & c9x7   tT拏3k_67uߞ:AAA:@~$~LAAcCc  Y@l;tsAA!?rc  @ď  @X"~LQYYhqK/guwwnYSse% N~y_ɓ;,W47Y ?,z3יC i|>ItHj6Ў:@VEp!cې/O^ď /}puaZ_x1t& HH~)3n!)wҟMZ_w,6Lٳuɍ\̀edq\&Zo?&~L\6!jWFVO  #18a_w=1eWo+ɡ[L.*U4w5u?~;'  nM )賉PP<N.ښ:.;4! rf<DJ 0PǴ oc9Xu:Tܬfw0yusz[#/~ѲyNal~̸?fMw1A@g~,ƿlk?PoO'Z%v(Eh}_, ,7R~5^ď E~{R +Ə)륾DžrInywC?FL;5<ڱ1VZl=a+hsi?\e@rNpx_[ v*~LA~ ?Vύl(U-]x H&u[[7^ R ?pI;TӆتcSuhGjj[lnud̸:ɿؤ&~LA(c y'et~H"~L0Х{B"Dz NRj }5 ;KA~K>,ˆ:3=~]̛iܸ_՚>.W$~LA("͏ @ a ?B\Hly4MYqm^oXwǨWTrȿUTcM<c B$#~,a7{ ď Bď 1AZx<ȰQ8.3sKYYҧOAcCc0p=KfpĆo:ֲJ}pe۷o߲eKZZի׬YiӦ]OAz1Ax<XuZ;-!Y :M`2334>v؊Bۍ7*WUUYYA:BXbX3?&۷_e˖-al z,Gzz:ڬ czǬU^fdd8N]˃뒒 m6^n[A*"vStGa0K|'|\ه[OhCqq. c&4p;W.((EQEmm-N8N ^̴4x6XMq\0rMa#~,?&]B+==WpbzuME}CjWTTA^ <n`sssaqສ m@ď %%%[l6 n%>8ק~ \ eZ$cIUcé[m F~y_ɓ'u577+~Qfcn&w<׼ҙ[&/F]uO({ 0BknO>n#4+~L۷!tB /٨`ͫ~c&. $55T mpBp* iii(A=+ 'es%]l+(UrYv>,zOFKy7.BTG.vO^v}j+6 Pzuv!~ >FKOO~k/sq+7ߏYy+Op֏Gfdd`TLa K~ i @{W2Yw`}6f ;xG6ȏ{'Tux.ԻtHda>?ŧ~٧͟} ?&a fퟯxu2Gyy.֏ǫ.BF{QQHPͬ):ܱ鬺 7z-I#A1}[J3 6qF +x2[`eU?vL߬T@MjZy#OSc[nwqq+^09|ohJ@ouQdfff¸br8i^p=_O\+Wt==Puی֏yL?zWI~K?{ma0?c&tfP~?1A X,-W"ײ+V*шW%/LϥK.6(,,+"Rp -[,ryJ0].G ӎxR坬hTBXkǨdʛ3%B~,\ ]'_4ܧrLRQQ_JIIxIdS]] 'Ɩ&55N ײz]ăkn9 .T `Ƹiii?618xE-**˜7?w.?̃ezjndA>W-\ %[(76oa[YY5ڛ1Aȏ >O?yPpYիWWpUWG֭c{`WG8 T0l0`)?9=?wqbYj}zw]Kתk}nwtעk*+kjk;w6x몼}Z~k??>䓏_͟QZZ6قiO聋/}aGzꍧ׬Ymҙ`+^)))Vt\Gs/9uޅ潹Dp\׮G;Tw3^}eza"'hk[&Mv{[C/]60?f-X?j>y}Zs\{mՄ.: {>};ߟ/.>}磂ҹ&U>_J>8o{~ |qKla 3^MH~E cfcBYzɱӏϚr}秪 L|. QW 05짟/[Y^S\\Bc5⮑֮Н5g|{|` ".?񿰰NO/--'kQϿc{w8ZԲ*\\ b-éڑ篼^[p]^zJ #147+67DŽ˅g?gsJwqFa&*ҝ>o.᏾y!{&׬:f16?lD(߾[<Js`'}!\TUUoݺ 0eeggu%Ŷm0}-[ Nե{[.H1G1Qxr ;vd#1(9#1!xb[bb$ G ?Cu>Ta.Q}X п@l;>}g~N?&ct? jjjJKKu'w|\.f 6_L7 :c>,V"8#d8Zeqeaj99 B#dwm嫭Êm>YA">?Ͼfŏ =s?fVE~³'j=mJo.uyi[m{o_۾[|r6N}b=aZ>_G^??6oZު<ɚm=> T A?@#V2v=֗cEqqesrr.vqƤJ;hSӪ??2ZeZ2lXX;ce55ʏѓ<X&#U"B?lUvtʟ4_?&.؈,-mo0~򥛛) >i|w?򖯚ۼi_ܬc;ˢe~Cc _"m[,* `Ÿw[:N QvM?rel_K Ul 5\e]ׯ~,bL}qY;+gUi6f' w4K3=UfQ?zm~`]}fuzٞpo=T/oV/A?5ʹ /66at Y,}*~/ˏjӬ~L*iFj c4~ֿW *;; ?@~,&X,؃NgӏU㲫- cSYnSN-|০;x-ώoQ&͟~)YB؋a.vUkrY(y=ZxLϕ-?fz$mYb`x`u؀}2z{*m13Ktr?thm~z)ٷS³c12+\V)^w fUm Y}D1ub&Z|Y'?(,m& ^W~9+ ?f3}9+cQA~~?f?t bi 1͚+?6JbcZ ?Ì sŠZv͘RO&ݢK?ּ肞SfnF.;QZ߸L-47Y|q۟xS!?!mT`vx3 Ī'557ia ?<C119_Xo}K{ͱ)qiiܦb_vlcf% 1ldU~w~csv_1uNobS1w%t}9Q>ز?u@SYla[1Κpڭ~,plF1UISz c\Y|'hW\XT+ǐ3-5mǚZ84<eX,5 ?6q7f<5:q\7BOH¬Q ;aGJ`:A7rS?۰dffSMM O؊̗lj𔣚uC1cBOo>g&X)f1ZcP~^$QǢxCv3Zw|ql =Sqwa1>`èu0F٬' * ˪J+k*ʶfggA ''#n,M? pK9A,.1:f}ccâ.dMLZ;Anm{*5 i[7n{Rx ǘ~,xAw"ijY=US}a⍫L3f}^(>5xcB/A$.,,|c$vYB\ii7xy2t| }zͶ¢kz~~/.՝5qQ?)'HTW<VkCX6]t[1d9bհluh{β1,x9a}Zuy0OC<Ǎƒ•¡)F(VZYYc Xejkȱ)VƊ@p1E |{010Wftljӈ ?FI,.P/pc-`${ }(m1kM?z;vIU/K+6uyEc?&t B# غuqsY[s?/'sʨ{FΜ5&V/  eN<=F8uxYs232|iNqՒ)ǝ> +v\Us[ᦰ>g;l-zQ=ikA?~%D,u-Ͻofe{5t/ONSY'qɟ:/,:)'4}f{{v4ռUO㯐_!=C{-޺\.d;f0fׯ_|yJJ bǶmPF ##Yyj.AD-;?5˸٥2ifa3X`Kge'X2Ԅ_Џ4hgK!UgFl~*Ǽe۽!f'ڏ ґ 6mљ!γ襪 `FFGuQw_RRf͚|j]>u o]ې!<>7YTB nO]_n4Vzk\;vԹ;6l7x})pBJKԮbC ،1YYY6lذu۷N'ZFi%\^!QH~, d= lUS[5`kM4맟Ŀ>5`6ďY?RPP`|wlm  zSSx+]0'>QzkYP.JP]qֺ<XWO C[[Xk04>d1Ϧ4H(V Ӫ:1e˖ eD%sE ֎뛘mҎ8a+t&5[~&*Pfzf>3?6AOfCc5YYYk֬-E*b`'D(ʃF0;Z>x 6\ZǬU oF~JhKZ"%JU oQJc 3v:%%% /QHὠi0-^Ĭ̘upVcVXc͟ K&~lH(5̆1+" xqX\\Lp l`E<p:OO'ԓPtUr2SJ^JH*kKChSez*΢ 5}ZZZ GqF"Qެ3̅XZ(Ag}٧cr, %HD!~̊4}WUUatݺH<uRDZa kHc 3=Gp>e t dQz7 iFXbEjj*N$Nqe_uC}ee|bsnj?;21}A""ր?fEX배"sCpavHpNuAoQ]"t>v#fiUZaXKiK.ۺukyy9V>6{Kդ޵ 70cǢXF!~̊[xaX*McHj 6]ib=@2 mO 1DR77ӍNf͚͛7íVݣp0?6ig+#="zN,RP<,2AWk"$ -Znm7p7lܸ TUU1zp;ՙ>;X]. ܮKYYYٗA_ ϗuu|Xг7H]ó@,L/9%YE_/A3fkh7,/8H#QPPrJ8a8R8Xkmչ4^#P(t foN~X 3]vt.z:C+k&7s,RXXaÆl$pd~#kM mp6Ph-mmu a*j*`wjQQŋ'-[۶f}AnUN݇W :;j!]>@ D榤^|媕[/󎄰WLx*//Ex/GOvXt)L^7`"ڲe ::%]ԔBp%\g m۶Z /yxŔ[]]s53'RmyodF=sV*NpDFyee4H~H^^?_.m QbWE i0``⤁#*@aG oc׺Z7?6t?S@. R{C d1r!fqܛ6mM=?!?ȎuNF- 5BF׳@!44Qջ`tB7a#*qP[fLzEw[+]TФ\ 5S-,D!$Wi)VpoO.˨΁ g8UD 9^;{+՘ +yRRR=t z^YAM k:x}Wxl 5>hѢ%K,[ qQ</&'u1*TTΏ!K41]~6LA60K%Z WVVV Wqq19 644 j\yC $8*1!YDXUCG&@t*VO6T 5]g Cwcх~,!~L74CW`mѭ oG.K332Vez%%%^_0U566"`c'NJ^:ܾ9SG/C-!X- P9]0i{ m^mK=Pز x ;a^KaMky:su!LA8)E..)F9~FaKཀ-]#[ 8 !\TBӁg 9kj}d0 @D`U>"^)-[ M-b@ރ^„CW4?sڿ9p8k^\Sŀxg%F\,_n-??!T꼅{B#:i%<$}skVb4 0u0I5Oy/rǧZV.oY""׏]M ڡ[@h Or(zPazث_>jd2&說*ӱ`BBԫ 8и;p; ȾYf,ྰE?z iTK+{ sN q"Xsz\ ۋqJqUUJ$]5:oÎթӊJKvxU6^└m#/^lP7n܈K^wfGp9H]RG\!R{\;]. @ݞ:TT`2jNW[ K+*Qªr:Tr54j+=M LeznQD ꕖT (Q,afDDB9H?b \NExCACVoK/ؿюU}:`%91Z>SX]]qa061cV]:[EfaJp!ɬVT1")syKSJ9?]%VL^01 Wt޿o?7С|{|"M~{kX|:(B1":ZAh5m7oZۙP}:T+>~{C_aWTC%Fj޽.q5'!0w*4I|WclфIO?=k;w߽BݣEkfbIo=3gђ(3gB6PSB{Il0s֬\ +yWEKNμY @uʀVsU ;>}w}_0?7/M s<^PWޮ;jkoI{tsϾ_i;?]1Hɝ?TK]?=?9c`{~[3Nt'\E!NE07?:g?Hwg&#s<c91n]$OfenxbgqwwWrqee;Z=nxW]e˯yn/9fU81DSd~{~{1Gm??M/c~r69w~w}l/~۞_;뼮:>UB7kA*%:wY ._á7ׯ__#D>*< ZV>PuB.宁7ĊzoF-ϫjO_߳;~ EWHKU?GJ_jI⑌H~y19߿w 3~yL;}CѺJwEc>tU (s68^!z\?VYYw^ّ#-֖hA[[[(?omEi*J*U MKkkK zGVf#6 Kq60bęӳ.v*TleKĤ3%%'%$'%$ģ0!1$&&&%'c5T< %$OOLmh $aK1ZEۉq ]Mf29>$, TPaZ7-Jj JKA&I^>O]HP2Su{=Z]zu'>q0ǤXT(13r8t,Ee3D *e\.|Gۺ Y0V8E9 w}fK$%wQɏqYE齯tp\p$$dBSDS&0rdG MAjm\@̊w8b7|]UWΥa-.oשl6ap:UUUl6ꢢk!`ƊV^xť%Ӟ?[j8@W$Iة1S1nɑ*]d6w8s |SP뫅% 88Z7RŏE8x T֛Gu> Ë9t .:HSE07䀈aB)B$o}PFo1:c( F;:|TB=7Pvؑ3w \1jnb--+}@H$vvtz%O<ddP4}dxرIq:QkpJJIq $re d5R{ӕQ.(!.))aZ2 wozXs&'?5)ajR"M1kD 6DnQY>e-_\<'V;_ .O9*v0](WB:t$!6>m:ר{FenН<o>{f^z9v"_V^^>ށ7^uw~[_qtܤ̕4ԕM\_a3YaP\ .+D0Fן)VWct/^Dp 6`ҸK ,';'---5%u \kZ*+gKqi1u)ç|7fB 9xb8M6<4PcIʦ8^zeOSuM_5ďE8uBYЛG5k'9_}?푯ߑͭG_~CvЁo:@Zh呏t @#呕C &-Pu y-K+}klD7P~ß}`7G>;DLA[}SgQOUo>#e![hT>#s7l'dee' /Ubοn4yrRr2Yq S&N[oMI.iw:%i n6{=0)9뮞LNm7zԄS>yZr\|RBrۦޕtf$N:=iSfLK>#a ࣦ݊OM4 /!qZ|iIw$'NJmjRoIN@mq>eRҭS<:ۦO8-qj3_t9n,)nzҔnN쏉HH4=!I{e p._O]дo**}U. 3. \QM…cdpI)$_sKGlWbDG̤PHďE\ u{ݦu={LJ<nNr59qKX\"n5gUշmoQqPYSNzEW` ÄC_L+sUw5e˖}c%֦۰qÖ̒r(9LCRQ ~Fш8MG è3Gu׬O%${y&8ӹvOЏ &ďExɴS W@)عŕ rտ{%c_9 OGzv/AniZ -+>YZٽa***~衇.V+w JKZkWͻrzg?ˬ'tUi/}Sϼ6fi'{s3cŊu VCѠʱl﮿{0 coۛu%nlHUy~7~n)r؉5% CciQ|&sk?;}/UjUؔXDQ*I;5ZJūr\r#HeecJ,9xٲWP\1fKtL wv97#= :sWFfMP7Wyԩf [nSO55?ۇ5A Džan&\YC|v5r۩m?FiŨ6x c^2m!~lUJJ#p@oͻ$qre6J4-S ۡޥ󼗲[Iv"զ.+\NۨYXKYo le3^¤}T;ßս:{>7Mضa[ _}YT{9ߌ60iq'{ ֿ_rr ~lK~M=Q͢f}cf5g?vY;oW6f=_|^,Żէ[צ=3w`c0cP1$>1d}_?&Os [_JޡzCU ~,`VUomcmܽo9=z)Jle?36ɸ`H1Q8l5'_w#j-{0$lǏ/ݎFs<3۪Uu<ά 2ToJc;zkӦy& uHjU9O*Bj.oq9)qg K6u8yㅪ2|GvgcJo)]:DT 3d3{ƍ>h[A>iӷAwִRI=~׾rJNl]~cʽ߿C~O?j#-Ok׏YjXwhq=vg3>6gҼ4kK{~ջ{v2t$Pwɞ}\Н>zcov`#H`àp]i/ YlYmϴj u>˴a䲼mcJ V\wvk3l=k6?.ɃMSȭcNkةڏ=1XeMe-݄bN6>H [չ6nXȏNLɼ5 Cc,bG%_ Ҵ}3;SϽRuM_'#3?N~LQň:DKM]dZe钾 `"~c}i"[_p5ٮ͏E"ďƌA܏)E#]`zZ6mKf_B2o2vb&8&:s0N }q敮юu[L2惈|ٲ5:U7؏׼ꪗ/)1:JO_?cC ӁOuLE?xٜ6a@3E~1НRRgn\RZZY]wu>VNZhUpCR#~l~,==p jQW(4?8{+J {**"ߏ=C>{f^~%v"_cϼ 3C'\cz啕6nCQ1PDUNJpz>5AGƌ Q ϾbUu]StN] SOXZBԣ^fܵngYJH?SiP)Kd:+!a's;f؏F.hB^ca }鮡_Cj+*p1~}ذ!=77nvm566Х1(tN ~l~o%TRO!T?(!OJ/|=4-exK DkkKkC~akl*IJ-8]ڝIe\Zܢ*[Q-}]yW\\V_ E7g cϙ>mڴĄxуy U^COWOa,ȒU$oL$K>-aFRz$=HNC(4Ӱ={JNH^'&HLNާ_F qjvt(9@MQE*KHj>jMm-A{=>o}}KS:<<ԞrZ@j4%v.6[<? E?n{f?Խ6ႇkY~'Nr?osۯE4d F_uUZrwFG>!AS0Vfn9b}0= 12.V87;boB oϯzKT~1~4%JbY+:%D5+w~]Ɲߣg$5eÆoÉi@Ꮙ]5Pgcwc ssBeT~wں.g "OOu[>8 n,'''==}ʕk֬Aْ*Xl`:4@F2lސď "׏QT\\ZV" M PY [*h9ZC/xbWmDqj>Xxw֍S /nt}%nkJJ22lnڱs]55NL4jnÁݱcً/3g3g- ӎai\~VI3ƿ&UzNI3Ocst;1S5WzRT%QFM@Ug{_3g ׭_tt} ކzO}.`>8s&͙j)Ι|SL|kqW>qX[1i򫓧Ι2Em{s:ҹ27D6^r#|{ݙ[8' Lqr]|K`u]ߘ9#H;|TVV-XOu[m%i+dtpaK5,M}|}ڿINVDO2HsCM S^25OBL2< Ug汫ng{zs[swhlUWVmڲnݺ|$u!L 31!やTkhB6=uŅ|N럹o@:U Ec44eN\IX{+\ ^haG q :y>q͌|^ZIU;UU*..˜ܺ5t]4$a5 #A}z>kHcí/_|Æ [nݾ};g,A  .=\&i_.f5kj\մ4Ɏ~Wm>>`}Js5܈~t" =| 0٥$`sS퀦jtd\nt,놬ZVt*lS]VԺ=8 zhfZtG BpPـ uiXTUWWT9k0Yz_BSVVx`gӦM8]:#𕯇 BnzpA}SmC& ,tr䂜NL#C*}} ו QME ZgYxSlNvKr O[SZVZUUi36% P0rNBQKQDTW_8=7nWWfNFgFۃUU28aLtQD^Cx=A}S)((.)),q (tbX˜?-W+gd{kW6oe @1E.`Y1 SЖ/((zv6ZdH]tJl>j(TaOEF!N)tWV3cp@mU`1 QR3QC'?EBB;ק1zk. 6ioʪk ȨN!T|OR~ Gf"Xjvz25YBrd1`B1|/'\#_!5ݣ.t:O==ռWKuЦnXmOk(br۶mŝ4$X]be̽ 8.7B@Wx(`41rTchDTCǍÃixM7AC.;Lإv׈F+i@ tÆ k֬ǀ4"aubu MVTTe 4NMMŻ Qr[A 0bFŵLmVfoU0YBsPe<*FO1v fG}Ӡ2PoCq mR@Iگ"9n444lݺp:@"\qfdd_^p0[dvxR"?A4@|/SuesR__%6\'j˜5xS@ K${s~R'5_aII?k0zqab g;vE3^=۠ tpG?J=ԐF<1H8.8%c fu4 ƴ[GKOۍh4Y Rnna;wzo mBD!艮$=ev OkC糽v g q]( É)"USW?7mJj{Z_B[1 ?^[d@ *ғ'Wq}I4 X )xkjG TTkV\⢶V Tpii).7oތW|L]vʨm! @P9=x+ِ!Cӹ~L#(lW=IcTDsNII $)++j< MP;۸qcJJNg% J؏ a{ХB. Bzە~2T|d@SXXzj\P|0[d!I#لeu ݣsk3t.t8|R`n \v܉,>,Y%(;؊f`=n"_0K2fLdiDzNg 9Xzm;aK.ci(ڲeŋD lᐥ- 7QO[KOOs ٟ"c 5_itwA$ }U@"UVT Lyfa avvvjjjyy.c[d!cL:11%x6c c4}5,zqɋ.d}mݺu͚56lpIIy VH2ՠsnW62MX$+^< I"3mTCax08R $Q~~>͛sssj`AO fAfddxDN?F`C޽ Nvq<@d@*((΢pl эBrZZƍOCЏE}#%o#ko=HЍZW`fcpz۶m=~HS}nѫHc:;xHKB{Ӧt^&0eܼAhVcv,A9&0&a~081~Y1=t"az!bFcVIq׮]|͑]TTiT@$PL?JJJRRRrrr0M?fEW<$"pΝ 6== .myb5,SS?컐4QQPP܈'7͑`x[.rNp050_ N/W~xű ڢB HE(1u E~((ā o+oB?&Ⴇ}/իW\r˖-[jUn.=3B:TUU"///Aaa K.]x˗,Y^7پ}&Ś5k0qz B]:F,T^\~m+؆ W)HbccTO&=A\*JKK11j 8F!AtƵ~?_kK_]D:OoӦx`û/V5w뼵 Z@mۆظq#^ц﫯\o.&dĬ6 9G󚾐z윥K.YdѢYYƟ+z Bqa2IOOץCӹb }áqf*({$\ c|vkk6oXM-8yy[U5wBI;Sr%i= ,FpܹV1UWWÃUlXf-Y8;vNE t'\Bg>LJvઝ-g[+RMS CZff&E-[:[6} B9abiy`A,(( j?&D%*T嘈)7!ruNG 'hGWjꚥKeg \qӥf26zܗ_xʕ+"< :?@DZ/]Tz72.q5Shf0ŭ%cu\MoiZZ%K7m\SlG hH38 fҏZVP:%e[p))o1D]3*gT=3O,Km!SS9%b+|:/A bgz-MQnMO5Dq,k׮[@]japT7H_?4}W'%&TMt䤤Clܸ1\G8\jC 8B5DlS'&}&VN׀Xuǎ]\dTrw[|[ ^:==IkD 7ocǙ6oF=@dWN#}"++t:3JlS<X\aH766 NS\-XYN Whtnڹ{ݕ9ٹ+V_dҥ^ܚtaPg]cwא1!NnMT1'sGӎF>—>C^/@x𢘃A$J<H\ʳsk|׳dF,ǎGlv|vNAA+ϕ R5k`WݨrJLPc AY07m۶-\GMLL#ªx`QaB<%'"BK#$tk䄋ッ?8BV+KSVLx%|16u؈FۊԵ=Œ3X$%%͚5{eammۊo{tzݻ7???++ _ ͟=~nj*ةJH Ĕ)qS iV3mVZWB}|7nܤ>{ٓVy2x[R j>gWq|Z08cJrr67w3裏d唔3x U6f.Zry˰_yuP ~Ln8ϟ0@RRr*Q'%'+%M X;0g,Z_|fs>,,S'&wl*~k 5^x|pϞFkMZ--\ o߾K ә%KIJL4JD̙Iw\H(ߝlνFF\:^qΚ9+5uMyyyBY 4* FwLr<x_WdcxYN8"uPtHƑVUU)x;i[a8rV\5~|^G}g!.VgSď ^<<]}"`OR HTtXͮ~`U ^϶{;px9Ѩ{Fen87.#cCgfø{OFfuCݻwgggiիW'Ӎ#L_xFE23(&p*=!&Q!L9e(SRRps9$a1dB^ґeўeG X>!=csƖpC}~KX.;#0cBb",9tcc#&?PSq/Վ68]/?{;ďE;z ]  \4 O|9+Xӣ1yͮ\ cEi{ҪV?f%Z`[999]^ 2xُ$a4 ‚1aRTTk/>=Yp2B>"Nڷ౅X?5EW5HH~f:w,ߗ΄+Vk:cG7_h ]?\߻o+ďY܏󩮯g^ڿ5w6ϢMT1".^-fl ܢC~Õt%Zeo|fלΧ氪i坴nZobn}Vom+WN/UVx{xT}H@l'q쵝n46n}M>>my6q}_c 㤵_i':N67#W$>3IȀ`L93 0+_F |>9hV?{HVJwweeJUzNJ'fQqI f?7S'ev̱ο+yZ]t j* l='jܿf$,})644N&'7|Z9nz,#64w_>?y敵,ím,ylOcoLؕYc+&J?.c'\i/;[OcGaha1,417\c^%KW _n'f[Ap *ҫ&oێ=n4M+7$D19bkȲdfQ[6䓁3NDUxvjQNFLm' Guϴ<fݻ& _H|%U!0yěGƖjautN >c;CջL<ƒ8}TĪ_鴥b4yKo q b1Uënj<:OS$a66hhS" IŐ^֤Oos<fb6N?:Tyˇ?]*~2+527e!-TW:CfXY;~c$VPiK.ipޢĦcF}5jP%8׹yN=nr4HĪ鴥b4yKo q b1Uënj<:OS$a66hhS ):\8sPOǡt:OS>w<c͕}N,t$o}7ުVnVQ3 򺯸FcZ;wS3aLOjw-c+gy ~\ҖĪ_c4yKo iq b1g>^5LRu7<gp w]OG"5K^9`VKۑcst\'Ti&7 ܠVGϔRy}"g7[_xwqwc&M<d'lRz\%<K+7L |L.;˔<6k45VֶRKZ~޹\Swn0]|LFdc:[cN2KSTFӋfX4DG=L1^Z dP7p%D-oNTyu7cL2_>mse1DcfSRqvz^YzL8/ܨcO K*yÒ+3<1'kTdV5ljGuffg&Sd,c:[cN2KSTFӋ<f~\Mmtgn&SN/7y2N?_VKĭ6%ɛ1Ik&hgc<f1߯KksOTKS|̍:6J$eI1|̮|̓ǜeKP>NewX4vLՎ\HL"a=] npy o3b*T;[߱O^XV,]Np/7ylaYtM[Uy Mww~C`ۼ%kylڦssg\rSOg+E"+cfkj9ujρ-FDzu\V^y}"SR<hС7(}=;&)5Km|~/2s #a*.)_OO~o;E=3x.ۿw[yM!#,]ʿ;MG"vV[[X4Fhs|rͫs"&t{M}8媮]g?{z9Yt5:6n?Cӧzf+ tX0o(<ēs|H488XQYysɦ͋ l).Ӏ ֮kz-[֒2z֕d$ٲgiVY_q=#ERٖҌ/YJ*z{gOwwO}C6-ojhlU,.)+,*<.s3mi7y_ںFe|^]/Ş݋N-۞=kg׮]%/[J6<gUUUv)vU]]]YY!)se>A 2l߾BY4!YȈijZgܑ̗<AYooo]]]YYY[[[~`v1>T}}} Z[[l+@Vc˛eٶy .<appP3 i3pc|K臇[ZZ./ y ?6[0IFY[[ij^: fΝ6ma[H$^YYY[[w^UXc(aL^B'+J0ATTUUXc ee\sg{ G"V}CCaQQFޝsa 0(EM'xs{yX,f/A6˖8Ʊ[y @|SaUW"z1eHf¼u/go[mzs-͋Um퟼pf{y eyE y lylSgd!bp|һiZ69vha (9|^PcM7YS教c]vd^5/?)W8n/dO!8QW_}( y ,4lrdWB]'R+:erx)O8ylrE)od̓sr^2`fs&;poMfg:̐^r&L*JIX:[ӓ5EO JV=>lFnf<M:) .G?=yR69H(}RɮML=RLR^y !S>J-i<fܼ{򘮳1:Tu$ج<lcO՜HcLdG|-BvlGfrǞհ̡H*J1SһUgCpX*Mɇs\=;r9+lV8 M/kF3ƧuumyB]΋񟺻{zUX,~C|?()O?808h pI*+-P<Z5u[vo<"Hն Z3x֒7fϧXIffm,dl:[u< ;[^^i1X,UUUU[[{!JJJR544gmxxضsD0/CCCv3MpX<`N$?Hd2) vԴs'9{ =IEJ@ww$՚IbH$eI$gyeigsssOOYvXc"  ý3ve]uAnii$/7gbbe[m(g=qi*dA`0888::*;Jw G253 3\9ؘz%ʗMQQʲLlbbB.Xv{,7W[UfF *}U$IlxxJ6Z}7ijeF s6\aͲeY޽n۶m4$ʵa.fL`3±r̰rF!dr5 $W|-u/nE<mTIsJ– cBY▼ʪ:n[JH3}f6;zkV ɟeN<!DupsiOOgAɂ_c[邑CL$9;6yȔ F ry``\*?{Xlckk*ؒFYʓd0Y*wƒ:${DigfW>Y*̹{Kg6ʬ ,54LWw0>3Tr,ܞp9'5e̳XVͲxbrDݰ۴UxXTcb1&;jUrO=*&IniLiP)nRFvҢPݹsg}}8p@";xu?PsHhI?HԢڢ;)\zƶdF"tQF}pFZ.*s4}Z[[Qڄcnq[\1gP sHg9ICCC^p M_cvb y Ylļ !rQ*'KXa1˫,tKH]vͮߕޔ,;m$SM-Mt;-uM/%'iݬLL^r(Jjfs@#ǐe-rޟ3tPl̲jC{YOc"Uy5oذaݺuɜ9!@<,01g*/V fNhl,≑[?*}2{ɂP!Fr1cǶmUre˖[Jܵ˂7& =#j~f5駷32ۑҍNݒ4eWԣF %MJP1$wIr#~~ *en1 S3]qVEF{Y+s.<n#={JKK7n޼}.s`f>;un>m7g&ǀ\ZcϒH276&͒:~H$U U#2[ᨳza]5qo(2;Ըy-ŕk[f͚&I&rKofFrnT2Uf9EEtUʨH$S?%dP}PۻY}䪨$l3@^*,̼?:=Gڊ "&*2:<t42[IbT\GGGaQ|rMP[;Ȃ08e9.Au/Id֮p1!>KFG}P$wO_WGwGsw[ݮm ]mm m;ڛv7WYnloƆֆ憶FݭqG,4JշJiټaƊ[6E41_RdSOē Uevyli'# 㣒Hrbb|xdu{WuEC}up:T5e*g&Vj)}wIuu5h9kp`h|l_2ݽdg6H6{1d1n\ooowwwMMMyyEʊʭBWTy.KS=Y)+/.UqұLvUTa#zm*J 6%ܪf_=RMDJi(DuuTȦ5TssK__ʍgś*Iv?޾N~{H<cckC~ pg pW^T,rp*YW*ɭU% LYki`U򗬼{ oJ?GI3 b 5OFQ.9"alt_R%nO<˾]/X3%eιM|UiyEo[~;:jJʊ7mX_^[⒒=i_c~z$=ǯ⊀ )/ٍTiWtɺU͆:\8 9m1";Zl'Z6a 5,OPRQJw'4W]uO?s?0688yf\%o]կF-t V𝁐`kyf@p-Yv0Bw_ ^ҊH<WOI$;[715^Wew sѩ,kRӓw2MvgJBK̗T%PPe8l867Y[K{:zyZ̷I0z% S$C=rZFޱ+5Ť2:Z68C8cϳsr=sw.Ɇ 6o+\꺌l<.1>̺Cw=*WC+B*{|-;yLrGH_K6 ޓw #K$\kJ:{K((+GcilLQ?#K]'Gb>jd9p@"Ӗʹ UMet6e&/H:8|K,P(Q\D2P*$1%Xl|||ƍ_B'K*ErP0\ tȇt\@^~@dP@ͰF($?^&{Tg7,Rj|PNRJԫCpn_9XXM;$3LuқsPLv`0Ofe6 p^85[i / /P8,ȓ m޶l)HJ9"; cF\$A4$wɫy tkCYnp+KsSk7gɆM 4o%_EQAkEx%%=]9yp~X~շŪ>X,~՚ϭ R2=yX#~У+B?[.g|d{"/ƾ*y5gQ:hW.>Y|>6<}<ľIS̕fE7}o╡/[#eG(=);pjZr?>f)uoxf+y,HOZAӟ/K*e=y+j `< f&cﻯU|FISQ=|U0Ѵ( hN5''9j<W)ofNߨtÝ:uZ3~tP?9}j/T=tjujsCR*cre/VP'ފ#X;ؙYk.Ex%ş/|^:7|r*{g3Ihnlr/~_^'L3CM"-}#pLʏcN(rH*2<fd\8E fn.NtE_1eFpZj$2 Q*\ y<K}("c_4X1y x|5wm U]yUiS{q,SE]8sh<k(] R.fMJqQ=8~rZs,<l ڻa?0f_1\^w)\Ἧ,yMr(#lkH?x7B+/ K5;=p=)ߺ52'}fg63鑌F##cبoɻCRe09)3=~~pO^w}^&r=LT{T |-bҕ)M#X4GbIaNV_F֮]{׆60N( ~A]P3}p~^=E0/ f|dn ~CI5ʚ #yy]ˡ^Wqj%"2T>j:yE! ]C^!u~GйXsa}ւwqqɕ~$#). Y; @|6t8[ }-``m%÷Ic xzzYPnn o 6%Vmy[7n oܱ4|{xm% 6ǞDX<%wwWqF'ɱK_xxC^%w.Z~yr\ԩu ʉHo /yiޭCyrBaNSޙ@_=;wGbDlDzgL$s{zzJT KvW̼㼔,H Kkl_"]۽6U ' $ՅJ,&/ɗ*1IHPRٔӲ $_,]Y4?򥁥A~8_jjG&ӑ,V^$/5KJ{HVwE W, ,.CK+< X* lաɫk/% <搯:f:Ղflٲ󙚿H$~ˆ|=C+?ls[ y Yr$>7_bپ:Z뚚kjZZ[ۤNVdAZvW#=KmSKMSv]P"%:Zw3$abed{l$UGL21Lcc}Muumu- jkMԪFUMu͵RҭAtyRWCIM3Hݶ]uc}0i~c~:.n*blhhؾ}۶V-u9)Mmj[U%SmQSuTVTTlwӣT#!͂JW63oQn۶JFeKjOM1Y689.Zv5<1O{ϩ*+VTTf4{ј=03 hl(Ehb"OFbG"%.r`褖e4ϷԲ4d2:*5*K_jS<&;9D6H8'ۤWt$E<d\桾w񘌚2GJLUv%c#17g-#8#ѸDp,վ#J&q')5܋ }\Y h}K>nJ:~K؞{zaޮ.m; nYm體6ZQA<%3vpKҥ<My(H␈B\rN䝘eZe#InC+'bⒶd<nT7UE&&LtTL1՝ G>[Q̝nfqHtUVoiN1h(r[zaZjgJ`Ӕ3M3ԜK.| 2,?Ǫ'TO,툆^-kʴ/E 6AMMuI#<ޛ\[Vzbnݞқ<*QVD <S9{fZTMft L쾗 g}O_ؘ_,IdՅFdy ;iRԊm75eV*K''ʍRs8եO2- ]H$رaϞ=c:y>|9 c@N%̚!62%J0)8u#YڼX~V,Vċ/811Q[[k.Մ19Fdy ȉ t O=L 3y̴G_XwwwMMMkklZ}  [email protected]$1Y%ݫB  c@.$a$IFv񁁁uɫ,9{3"9_ 'Onv_򋋋+**zzz|wy\w*cGss"$eEѡ!IbF+((v`4440V]]m[/HH}aE1dJv!Č-%7d\%Vʧ~<UZZ&јSop#ܦo,tu `Ak$e1uu|gV-zO>{Q2Tm=;O}5k'~~$nd[~ y 6oO^ooر'z۶ď6,zk׮#@+_;aaz{q:W˿d(;/o?z1xc{ޙ(g|yx_~6f<3ra<σvP-Gy7}+dohZZ_8z;Vy[qª<p){} Kt9Ӂ՚cgE<GQ>^+cc/JL+jLLW˿eZd *U~oѐJ۩w'^x ;R!ʉW&^8:u[1vMOĥƹсC}%ϼdFuN::d>'чNYf{;}-ԝ up苧Nx3IRWe>d<fQC!Js;+<mPtyssZcCCOܻj}vO `+<ěw_EщH{T=a’Ĥ㿒ɟ␓ X:y'MOIPr엲t^jz:L>oV|Л'N79T6ܺCO KSN 2y GSroVu2Q]RI_}OF I5H^8Xy 9 W .=<.Đ!-i'Z }[y]2jXA+m(QRݼ֧_O5tV咭%J9z>f.ILRM1=%YI뀥IzD3̰Al5%s0QMx&󘙒;H7ԙ< y f~E?Ǎ Bz32StA>qV;g\_)˓܇BG1C}NM}& {eL hb]_jV~G=qjQm<nw?g|; oNSywyA{R=UU' ~Ly'1ϻ;\v3wƹcӳ]rXO(y 6\C,ߞ7_02]np , 1>hjl?_ g?GMM?o[68mTx~6 cQVV/dٱ@}K7'~ʳaxxp<`Cɢo~`coo(Ky bX__޽+^Ч72Hjpp^@1y A$Ktsy ;s)< ?c< ?c< ?cTWR1 < ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?Ry| @n1y A1y A1y A1Gf(((r\1(((<FQEQEQG-ve/m[IENDB`
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/EditorFeatures/Test/Structure/BlockStructureServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { [UseExportProvider] public class BlockStructureServiceTests { [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSimpleLambda() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where(x => { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, lambda) Assert.Equal(4, spans.Length); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestParenthesizedLambda() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where((x) => { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, lambda) Assert.Equal(4, spans.Length); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestAnonymousDelegate() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where(delegate (int x) { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, anonymous delegate) Assert.Equal(4, spans.Length); } private static async Task<ImmutableArray<BlockSpan>> GetSpansFromWorkspaceAsync( TestWorkspace workspace) { var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var outliningService = document.GetLanguageService<BlockStructureService>(); var structure = await outliningService.GetBlockStructureAsync(document, CancellationToken.None); return structure.Spans; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { [UseExportProvider] public class BlockStructureServiceTests { [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSimpleLambda() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where(x => { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, lambda) Assert.Equal(4, spans.Length); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestParenthesizedLambda() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where((x) => { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, lambda) Assert.Equal(4, spans.Length); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestAnonymousDelegate() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where(delegate (int x) { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, anonymous delegate) Assert.Equal(4, spans.Length); } private static async Task<ImmutableArray<BlockSpan>> GetSpansFromWorkspaceAsync( TestWorkspace workspace) { var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var outliningService = document.GetLanguageService<BlockStructureService>(); var structure = await outliningService.GetBlockStructureAsync(document, CancellationToken.None); return structure.Spans; } } }
-1
dotnet/roslyn
55,484
Remove obsolete UnitTesting and Razor External Access APIs
tmat
2021-08-06T23:36:46Z
2021-08-10T20:32:36Z
909e6dc8eda8ee5898b4e1339c512c44970bcff6
3d0d94801b78fd6d22afb36d26c834f5056e7e62
Remove obsolete UnitTesting and Razor External Access APIs.
./src/Compilers/Core/Portable/Symbols/TypedConstantKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the kind of a TypedConstant. /// </summary> public enum TypedConstantKind { Error = 0, // error should be the default so that default(TypedConstant) is internally consistent Primitive = 1, Enum = 2, Type = 3, Array = 4 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the kind of a TypedConstant. /// </summary> public enum TypedConstantKind { Error = 0, // error should be the default so that default(TypedConstant) is internally consistent Primitive = 1, Enum = 2, Type = 3, Array = 4 } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task RunMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; await StartDebuggingSessionAsync(service, solution); // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task RunMode_ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Fact] public async Task BreakMode_DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task BreakMode_ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Fact] public async Task BreakMode_ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task BreakMode_Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Fact] public async Task BreakMode_SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task BreakMode_FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task BreakMode_ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 2 : 1)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.False(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_CaseSensitive() { var capabilities = ImmutableArray.Create("BaseLine"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_IgnoreInvalidNumeric() { var capabilities = ImmutableArray.Create("Baseline", "90", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_AllCapabilitiesParsed() { foreach (var name in Enum.GetNames(typeof(EditAndContinueCapabilities))) { var capabilities = ImmutableArray.Create(name); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); var flag = (EditAndContinueCapabilities)Enum.Parse(typeof(EditAndContinueCapabilities), name); Assert.True(service.HasFlag(flag), $"Capability '{name}' was not parsed correctly, so it's impossible for a runtime to enable it!"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task RunMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; await StartDebuggingSessionAsync(service, solution); // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task RunMode_ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Fact] public async Task BreakMode_DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task BreakMode_ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Fact] public async Task BreakMode_ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task BreakMode_Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Fact] public async Task BreakMode_SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task BreakMode_FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task BreakMode_ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 2 : 1)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateEntered(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.False(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_CaseSensitive() { var capabilities = ImmutableArray.Create("BaseLine"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_IgnoreInvalidNumeric() { var capabilities = ImmutableArray.Create("Baseline", "90", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_AllCapabilitiesParsed() { foreach (var name in Enum.GetNames(typeof(EditAndContinueCapabilities))) { var capabilities = ImmutableArray.Create(name); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); var flag = (EditAndContinueCapabilities)Enum.Parse(typeof(EditAndContinueCapabilities), name); Assert.True(service.HasFlag(flag), $"Capability '{name}' was not parsed correctly, so it's impossible for a runtime to enable it!"); } } } }
1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even whne it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions { get; private set; } internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// </summary> internal readonly EditAndContinueCapabilities Capabilities; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry; private readonly EditSessionTelemetry _editSessionTelemetry; private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, EditAndContinueCapabilities capabilities, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _telemetry = new DebuggingSessionTelemetry(); _editSessionTelemetry = new EditSessionTelemetry(); _reportTelemetry = ReportTelemetry; Id = id; Capabilities = capabilities; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); NonRemappableRegions = ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty; EditSession = new EditSession(this, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { _cancellationSource.Cancel(); // Consider: Some APIs on DebuggingSession (GetDocumentDiagnostics, OnSourceFileUpdated, GetXxxSpansAsync) can be called at any point in time. // These APIs should not be using the readers being disposed here, but there is no guarantee. Consider refactoring that would guarantee correctness. foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _cancellationSource.Dispose(); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); internal void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } internal PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateEntered(out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(inBreakState: true, out documentsToReanalyze); internal void RestartEditSession(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); internal bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } public void CommitSolutionUpdate(PendingSolutionUpdate update) { // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var nonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in update.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (nonRemappableRegions.Count > 0) { NonRemappableRegions = nonRemappableRegions; } // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in update.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(update.Solution); } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> public async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } public bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> public bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline) { lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { var pendingUpdate = RetrievePendingUpdate(); CommitSolutionUpdate(pendingUpdate); // restart edit session with no active statements (switching to run mode): RestartEditSession(inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() => _ = RetrievePendingUpdate(); public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { if (!EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), baseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { if (!EditSession.InBreakState) { return ImmutableArray<ActiveStatementSpan>.Empty; } if (!mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public void SetNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions) => _instance.NonRemappableRegions = nonRemappableRegions; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions { get; private set; } internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// </summary> internal readonly EditAndContinueCapabilities Capabilities; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, EditAndContinueCapabilities capabilities, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; Capabilities = capabilities; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); NonRemappableRegions = ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty; EditSession = new EditSession(this, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateEntered(out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(inBreakState: true, out documentsToReanalyze); internal void RestartEditSession(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } private void CommitSolutionUpdate(PendingSolutionUpdate update) { // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var nonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in update.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (nonRemappableRegions.Count > 0) { NonRemappableRegions = nonRemappableRegions; } // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in update.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(update.Solution); } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); CommitSolutionUpdate(pendingUpdate); // restart edit session with no active statements (switching to run mode): RestartEditSession(inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), baseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public void SetNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions) => _instance.NonRemappableRegions = nonRemappableRegions; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Features/Core/Portable/EditAndContinue/EditSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; private readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions; /// <summary> /// Lazily calculated map of base active statements. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; Telemetry = telemetry; _nonRemappableRegions = debuggingSession.NonRemappableRegions; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(cancellationToken => GetBaseActiveStatementsAsync(cancellationToken), cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements); } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, _nonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, DebuggingSession.Capabilities, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); var emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, _nonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); if (newActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { if (methodInstance.Module != moduleId) { continue; } // Skip non-remappable regions that belong to method instances that are from a different module // or no longer active (all active statements in these method instances have been remapped to newer versions). if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; private readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions; /// <summary> /// Lazily calculated map of base active statements. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; Telemetry = telemetry; _nonRemappableRegions = debuggingSession.NonRemappableRegions; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(cancellationToken => GetBaseActiveStatementsAsync(cancellationToken), cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements); } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, _nonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, DebuggingSession.Capabilities, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, _nonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); if (newActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { if (methodInstance.Module != moduleId) { continue; } // Skip non-remappable regions that belong to method instances that are from a different module // or no longer active (all active statements in these method instances have been remapped to newer versions). if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationFieldInfo { private static readonly ConditionalWeakTable<IFieldSymbol, CodeGenerationFieldInfo> s_fieldToInfoMap = new(); private readonly bool _isUnsafe; private readonly bool _isWithEvents; private readonly SyntaxNode _initializer; private CodeGenerationFieldInfo( bool isUnsafe, bool isWithEvents, SyntaxNode initializer) { _isUnsafe = isUnsafe; _isWithEvents = isWithEvents; _initializer = initializer; } public static void Attach( IFieldSymbol field, bool isUnsafe, bool isWithEvents, SyntaxNode initializer) { var info = new CodeGenerationFieldInfo(isUnsafe, isWithEvents, initializer); s_fieldToInfoMap.Add(field, info); } private static CodeGenerationFieldInfo GetInfo(IFieldSymbol field) { s_fieldToInfoMap.TryGetValue(field, out var info); return info; } private static bool GetIsUnsafe(CodeGenerationFieldInfo info) => info != null && info._isUnsafe; public static bool GetIsUnsafe(IFieldSymbol field) => GetIsUnsafe(GetInfo(field)); private static bool GetIsWithEvents(CodeGenerationFieldInfo info) => info != null && info._isWithEvents; public static bool GetIsWithEvents(IFieldSymbol field) => GetIsWithEvents(GetInfo(field)); private static SyntaxNode GetInitializer(CodeGenerationFieldInfo info) => info?._initializer; public static SyntaxNode GetInitializer(IFieldSymbol field) => GetInitializer(GetInfo(field)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationFieldInfo { private static readonly ConditionalWeakTable<IFieldSymbol, CodeGenerationFieldInfo> s_fieldToInfoMap = new(); private readonly bool _isUnsafe; private readonly bool _isWithEvents; private readonly SyntaxNode _initializer; private CodeGenerationFieldInfo( bool isUnsafe, bool isWithEvents, SyntaxNode initializer) { _isUnsafe = isUnsafe; _isWithEvents = isWithEvents; _initializer = initializer; } public static void Attach( IFieldSymbol field, bool isUnsafe, bool isWithEvents, SyntaxNode initializer) { var info = new CodeGenerationFieldInfo(isUnsafe, isWithEvents, initializer); s_fieldToInfoMap.Add(field, info); } private static CodeGenerationFieldInfo GetInfo(IFieldSymbol field) { s_fieldToInfoMap.TryGetValue(field, out var info); return info; } private static bool GetIsUnsafe(CodeGenerationFieldInfo info) => info != null && info._isUnsafe; public static bool GetIsUnsafe(IFieldSymbol field) => GetIsUnsafe(GetInfo(field)); private static bool GetIsWithEvents(CodeGenerationFieldInfo info) => info != null && info._isWithEvents; public static bool GetIsWithEvents(IFieldSymbol field) => GetIsWithEvents(GetInfo(field)); private static SyntaxNode GetInitializer(CodeGenerationFieldInfo info) => info?._initializer; public static SyntaxNode GetInitializer(IFieldSymbol field) => GetInitializer(GetInfo(field)); } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A base method symbol used as a base class for lambda method symbol and base method wrapper symbol. /// </summary> internal abstract class SynthesizedMethodBaseSymbol : SourceMemberMethodSymbol { protected readonly MethodSymbol BaseMethod; internal TypeMap TypeMap { get; private set; } private readonly string _name; private ImmutableArray<TypeParameterSymbol> _typeParameters; private ImmutableArray<ParameterSymbol> _parameters; private TypeWithAnnotations.Boxed _iteratorElementType; protected SynthesizedMethodBaseSymbol(NamedTypeSymbol containingType, MethodSymbol baseMethod, SyntaxReference syntaxReference, Location location, string name, DeclarationModifiers declarationModifiers) : base(containingType, syntaxReference, location, isIterator: false) { Debug.Assert((object)containingType != null); Debug.Assert((object)baseMethod != null); this.BaseMethod = baseMethod; _name = name; this.MakeFlags( methodKind: MethodKind.Ordinary, declarationModifiers: declarationModifiers, returnsVoid: baseMethod.ReturnsVoid, isExtensionMethod: false, isNullableAnalysisEnabled: false, isMetadataVirtualIgnoringModifiers: false); } protected void AssignTypeMapAndTypeParameters(TypeMap typeMap, ImmutableArray<TypeParameterSymbol> typeParameters) { Debug.Assert(typeMap != null); Debug.Assert(this.TypeMap == null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(_typeParameters.IsDefault); this.TypeMap = typeMap; _typeParameters = typeParameters; } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { // TODO: move more functionality into here, making these symbols more lazy } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); // do not generate attributes for members of compiler-generated types: if (ContainingType.IsImplicitlyDeclared) { return; } var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; internal override int ParameterCount { get { return this.Parameters.Length; } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { if (_parameters.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _parameters, MakeParameters()); } return _parameters; } } protected virtual ImmutableArray<TypeSymbol> ExtraSynthesizedRefParameters { get { return default(ImmutableArray<TypeSymbol>); } } protected virtual ImmutableArray<ParameterSymbol> BaseMethodParameters { get { return this.BaseMethod.Parameters; } } private ImmutableArray<ParameterSymbol> MakeParameters() { int ordinal = 0; var builder = ArrayBuilder<ParameterSymbol>.GetInstance(); var parameters = this.BaseMethodParameters; var inheritAttributes = InheritsBaseMethodAttributes; foreach (var p in parameters) { builder.Add(SynthesizedParameterSymbol.Create( this, this.TypeMap.SubstituteType(p.OriginalDefinition.TypeWithAnnotations), ordinal++, p.RefKind, p.Name, // the synthesized parameter doesn't need to have the same ref custom modifiers as the base refCustomModifiers: default, inheritAttributes ? p as SourceComplexParameterSymbol : null)); } var extraSynthed = ExtraSynthesizedRefParameters; if (!extraSynthed.IsDefaultOrEmpty) { foreach (var extra in extraSynthed) { builder.Add(SynthesizedParameterSymbol.Create(this, this.TypeMap.SubstituteType(extra), ordinal++, RefKind.Ref)); } } return builder.ToImmutableAndFree(); } /// <summary> /// Indicates that this method inherits attributes from the base method, its parameters, return type, and type parameters. /// </summary> internal virtual bool InheritsBaseMethodAttributes => false; public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { Debug.Assert(base.GetAttributes().IsEmpty); return InheritsBaseMethodAttributes ? BaseMethod.GetAttributes() : ImmutableArray<CSharpAttributeData>.Empty; } public sealed override ImmutableArray<CSharpAttributeData> GetReturnTypeAttributes() { Debug.Assert(base.GetReturnTypeAttributes().IsEmpty); return InheritsBaseMethodAttributes ? BaseMethod.GetReturnTypeAttributes() : ImmutableArray<CSharpAttributeData>.Empty; } #nullable enable public sealed override DllImportData? GetDllImportData() => InheritsBaseMethodAttributes ? BaseMethod.GetDllImportData() : null; internal sealed override MethodImplAttributes ImplementationAttributes => InheritsBaseMethodAttributes ? BaseMethod.ImplementationAttributes : default; internal sealed override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => InheritsBaseMethodAttributes ? BaseMethod.ReturnValueMarshallingInformation : null; internal sealed override bool HasSpecialName => InheritsBaseMethodAttributes && BaseMethod.HasSpecialName; // Synthesized methods created from a base method with [SkipLocalsInitAttribute] will also // skip locals init where applicable, even if the synthesized method does not inherit attributes. // Note that this doesn't affect BaseMethodWrapperSymbol for example because the implementation has no locals. public sealed override bool AreLocalsZeroed => !(BaseMethod is SourceMethodSymbol sourceMethod) || sourceMethod.AreLocalsZeroed; internal sealed override bool RequiresSecurityObject => InheritsBaseMethodAttributes && BaseMethod.RequiresSecurityObject; internal sealed override bool HasDeclarativeSecurity => InheritsBaseMethodAttributes && BaseMethod.HasDeclarativeSecurity; internal sealed override IEnumerable<SecurityAttribute> GetSecurityInformation() => InheritsBaseMethodAttributes ? BaseMethod.GetSecurityInformation() : SpecializedCollections.EmptyEnumerable<SecurityAttribute>(); #nullable disable public sealed override RefKind RefKind { get { return this.BaseMethod.RefKind; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { return this.TypeMap.SubstituteType(this.BaseMethod.OriginalDefinition.ReturnTypeWithAnnotations); } } public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => BaseMethod.ReturnTypeFlowAnalysisAnnotations; public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => BaseMethod.ReturnNotNullIfParameterNotNull; public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public sealed override bool IsVararg { get { return this.BaseMethod.IsVararg; } } public sealed override string Name { get { return _name; } } public sealed override bool IsImplicitlyDeclared { get { return true; } } internal override bool IsExpressionBodied { get { return false; } } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { if (_iteratorElementType is null) { Interlocked.CompareExchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(TypeMap.SubstituteType(BaseMethod.IteratorElementTypeWithAnnotations.Type)), null); } return _iteratorElementType.Value; } set { Debug.Assert(!value.IsDefault); Interlocked.Exchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(value)); } } internal override bool IsIterator => BaseMethod.IsIterator; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A base method symbol used as a base class for lambda method symbol and base method wrapper symbol. /// </summary> internal abstract class SynthesizedMethodBaseSymbol : SourceMemberMethodSymbol { protected readonly MethodSymbol BaseMethod; internal TypeMap TypeMap { get; private set; } private readonly string _name; private ImmutableArray<TypeParameterSymbol> _typeParameters; private ImmutableArray<ParameterSymbol> _parameters; private TypeWithAnnotations.Boxed _iteratorElementType; protected SynthesizedMethodBaseSymbol(NamedTypeSymbol containingType, MethodSymbol baseMethod, SyntaxReference syntaxReference, Location location, string name, DeclarationModifiers declarationModifiers) : base(containingType, syntaxReference, location, isIterator: false) { Debug.Assert((object)containingType != null); Debug.Assert((object)baseMethod != null); this.BaseMethod = baseMethod; _name = name; this.MakeFlags( methodKind: MethodKind.Ordinary, declarationModifiers: declarationModifiers, returnsVoid: baseMethod.ReturnsVoid, isExtensionMethod: false, isNullableAnalysisEnabled: false, isMetadataVirtualIgnoringModifiers: false); } protected void AssignTypeMapAndTypeParameters(TypeMap typeMap, ImmutableArray<TypeParameterSymbol> typeParameters) { Debug.Assert(typeMap != null); Debug.Assert(this.TypeMap == null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(_typeParameters.IsDefault); this.TypeMap = typeMap; _typeParameters = typeParameters; } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { // TODO: move more functionality into here, making these symbols more lazy } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); // do not generate attributes for members of compiler-generated types: if (ContainingType.IsImplicitlyDeclared) { return; } var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; internal override int ParameterCount { get { return this.Parameters.Length; } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { if (_parameters.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _parameters, MakeParameters()); } return _parameters; } } protected virtual ImmutableArray<TypeSymbol> ExtraSynthesizedRefParameters { get { return default(ImmutableArray<TypeSymbol>); } } protected virtual ImmutableArray<ParameterSymbol> BaseMethodParameters { get { return this.BaseMethod.Parameters; } } private ImmutableArray<ParameterSymbol> MakeParameters() { int ordinal = 0; var builder = ArrayBuilder<ParameterSymbol>.GetInstance(); var parameters = this.BaseMethodParameters; var inheritAttributes = InheritsBaseMethodAttributes; foreach (var p in parameters) { builder.Add(SynthesizedParameterSymbol.Create( this, this.TypeMap.SubstituteType(p.OriginalDefinition.TypeWithAnnotations), ordinal++, p.RefKind, p.Name, // the synthesized parameter doesn't need to have the same ref custom modifiers as the base refCustomModifiers: default, inheritAttributes ? p as SourceComplexParameterSymbol : null)); } var extraSynthed = ExtraSynthesizedRefParameters; if (!extraSynthed.IsDefaultOrEmpty) { foreach (var extra in extraSynthed) { builder.Add(SynthesizedParameterSymbol.Create(this, this.TypeMap.SubstituteType(extra), ordinal++, RefKind.Ref)); } } return builder.ToImmutableAndFree(); } /// <summary> /// Indicates that this method inherits attributes from the base method, its parameters, return type, and type parameters. /// </summary> internal virtual bool InheritsBaseMethodAttributes => false; public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { Debug.Assert(base.GetAttributes().IsEmpty); return InheritsBaseMethodAttributes ? BaseMethod.GetAttributes() : ImmutableArray<CSharpAttributeData>.Empty; } public sealed override ImmutableArray<CSharpAttributeData> GetReturnTypeAttributes() { Debug.Assert(base.GetReturnTypeAttributes().IsEmpty); return InheritsBaseMethodAttributes ? BaseMethod.GetReturnTypeAttributes() : ImmutableArray<CSharpAttributeData>.Empty; } #nullable enable public sealed override DllImportData? GetDllImportData() => InheritsBaseMethodAttributes ? BaseMethod.GetDllImportData() : null; internal sealed override MethodImplAttributes ImplementationAttributes => InheritsBaseMethodAttributes ? BaseMethod.ImplementationAttributes : default; internal sealed override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => InheritsBaseMethodAttributes ? BaseMethod.ReturnValueMarshallingInformation : null; internal sealed override bool HasSpecialName => InheritsBaseMethodAttributes && BaseMethod.HasSpecialName; // Synthesized methods created from a base method with [SkipLocalsInitAttribute] will also // skip locals init where applicable, even if the synthesized method does not inherit attributes. // Note that this doesn't affect BaseMethodWrapperSymbol for example because the implementation has no locals. public sealed override bool AreLocalsZeroed => !(BaseMethod is SourceMethodSymbol sourceMethod) || sourceMethod.AreLocalsZeroed; internal sealed override bool RequiresSecurityObject => InheritsBaseMethodAttributes && BaseMethod.RequiresSecurityObject; internal sealed override bool HasDeclarativeSecurity => InheritsBaseMethodAttributes && BaseMethod.HasDeclarativeSecurity; internal sealed override IEnumerable<SecurityAttribute> GetSecurityInformation() => InheritsBaseMethodAttributes ? BaseMethod.GetSecurityInformation() : SpecializedCollections.EmptyEnumerable<SecurityAttribute>(); #nullable disable public sealed override RefKind RefKind { get { return this.BaseMethod.RefKind; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { return this.TypeMap.SubstituteType(this.BaseMethod.OriginalDefinition.ReturnTypeWithAnnotations); } } public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => BaseMethod.ReturnTypeFlowAnalysisAnnotations; public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => BaseMethod.ReturnNotNullIfParameterNotNull; public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public sealed override bool IsVararg { get { return this.BaseMethod.IsVararg; } } public sealed override string Name { get { return _name; } } public sealed override bool IsImplicitlyDeclared { get { return true; } } internal override bool IsExpressionBodied { get { return false; } } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { if (_iteratorElementType is null) { Interlocked.CompareExchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(TypeMap.SubstituteType(BaseMethod.IteratorElementTypeWithAnnotations.Type)), null); } return _iteratorElementType.Value; } set { Debug.Assert(!value.IsDefault); Interlocked.Exchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(value)); } } internal override bool IsIterator => BaseMethod.IsIterator; } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Helper class to allow one to do simple regular expressions over a sequence of objects (as /// opposed to a sequence of characters). /// </summary> internal abstract partial class Matcher<T> { // Tries to match this matcher against the provided sequence at the given index. If the // match succeeds, 'true' is returned, and 'index' points to the location after the match // ends. If the match fails, then false it returned and index remains the same. Note: the // matcher does not need to consume to the end of the sequence to succeed. public abstract bool TryMatch(IList<T> sequence, ref int index); internal static Matcher<T> Repeat(Matcher<T> matcher) => new RepeatMatcher(matcher); internal static Matcher<T> OneOrMore(Matcher<T> matcher) { // m+ is the same as (m m*) return Sequence(matcher, Repeat(matcher)); } internal static Matcher<T> Choice(params Matcher<T>[] matchers) => new ChoiceMatcher(matchers); internal static Matcher<T> Sequence(params Matcher<T>[] matchers) => new SequenceMatcher(matchers); internal static Matcher<T> Single(Func<T, bool> predicate, string description) => new SingleMatcher(predicate, description); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Helper class to allow one to do simple regular expressions over a sequence of objects (as /// opposed to a sequence of characters). /// </summary> internal abstract partial class Matcher<T> { // Tries to match this matcher against the provided sequence at the given index. If the // match succeeds, 'true' is returned, and 'index' points to the location after the match // ends. If the match fails, then false it returned and index remains the same. Note: the // matcher does not need to consume to the end of the sequence to succeed. public abstract bool TryMatch(IList<T> sequence, ref int index); internal static Matcher<T> Repeat(Matcher<T> matcher) => new RepeatMatcher(matcher); internal static Matcher<T> OneOrMore(Matcher<T> matcher) { // m+ is the same as (m m*) return Sequence(matcher, Repeat(matcher)); } internal static Matcher<T> Choice(params Matcher<T>[] matchers) => new ChoiceMatcher(matchers); internal static Matcher<T> Sequence(params Matcher<T>[] matchers) => new SequenceMatcher(matchers); internal static Matcher<T> Single(Func<T, bool> predicate, string description) => new SingleMatcher(predicate, description); } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Compilers/CSharp/Portable/Emitter/Model/NamespaceSymbolAdapter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class #if DEBUG NamespaceSymbolAdapter : SymbolAdapter, #else NamespaceSymbol : #endif Cci.INamespace { Cci.INamespace Cci.INamespace.ContainingNamespace => AdaptedNamespaceSymbol.ContainingNamespace?.GetCciAdapter(); string Cci.INamedEntity.Name => AdaptedNamespaceSymbol.MetadataName; CodeAnalysis.Symbols.INamespaceSymbolInternal Cci.INamespace.GetInternalSymbol() => AdaptedNamespaceSymbol; } internal partial class NamespaceSymbol { #if DEBUG private NamespaceSymbolAdapter _lazyAdapter; protected sealed override SymbolAdapter GetCciAdapterImpl() => GetCciAdapter(); internal new NamespaceSymbolAdapter GetCciAdapter() { if (_lazyAdapter is null) { return InterlockedOperations.Initialize(ref _lazyAdapter, new NamespaceSymbolAdapter(this)); } return _lazyAdapter; } #else internal NamespaceSymbol AdaptedNamespaceSymbol => this; internal new NamespaceSymbol GetCciAdapter() { return this; } #endif } #if DEBUG internal partial class NamespaceSymbolAdapter { internal NamespaceSymbolAdapter(NamespaceSymbol underlyingNamespaceSymbol) { AdaptedNamespaceSymbol = underlyingNamespaceSymbol; } internal sealed override Symbol AdaptedSymbol => AdaptedNamespaceSymbol; internal NamespaceSymbol AdaptedNamespaceSymbol { get; } } #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class #if DEBUG NamespaceSymbolAdapter : SymbolAdapter, #else NamespaceSymbol : #endif Cci.INamespace { Cci.INamespace Cci.INamespace.ContainingNamespace => AdaptedNamespaceSymbol.ContainingNamespace?.GetCciAdapter(); string Cci.INamedEntity.Name => AdaptedNamespaceSymbol.MetadataName; CodeAnalysis.Symbols.INamespaceSymbolInternal Cci.INamespace.GetInternalSymbol() => AdaptedNamespaceSymbol; } internal partial class NamespaceSymbol { #if DEBUG private NamespaceSymbolAdapter _lazyAdapter; protected sealed override SymbolAdapter GetCciAdapterImpl() => GetCciAdapter(); internal new NamespaceSymbolAdapter GetCciAdapter() { if (_lazyAdapter is null) { return InterlockedOperations.Initialize(ref _lazyAdapter, new NamespaceSymbolAdapter(this)); } return _lazyAdapter; } #else internal NamespaceSymbol AdaptedNamespaceSymbol => this; internal new NamespaceSymbol GetCciAdapter() { return this; } #endif } #if DEBUG internal partial class NamespaceSymbolAdapter { internal NamespaceSymbolAdapter(NamespaceSymbol underlyingNamespaceSymbol) { AdaptedNamespaceSymbol = underlyingNamespaceSymbol; } internal sealed override Symbol AdaptedSymbol => AdaptedNamespaceSymbol; internal NamespaceSymbol AdaptedNamespaceSymbol { get; } } #endif }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IAddressOfOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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_IAddressOfOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void AddressOfFlow_01() { string source = @" class C { unsafe void M(int i) /*<bind>*/{ int* p = &i; }/*</bind>*/ }"; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32* p] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32*, IsImplicit) (Syntax: 'p = &i') Left: ILocalReferenceOperation: p (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32*, IsImplicit) (Syntax: 'p = &i') Right: IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&i') Reference: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void AddressOfFlow_02() { string source = @" struct S2 { unsafe void M(bool x, S2* p1, S2* p2, int* p3) /*<bind>*/ { p3 = &(x ? p1 : p2)->i; }/*</bind>*/ public int i; }"; var expectedDiagnostics = DiagnosticDescription.None; 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: 'p3') Value: IParameterReferenceOperation: p3 (OperationKind.ParameterReference, Type: System.Int32*) (Syntax: 'p3') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p1') Value: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: S2*) (Syntax: 'p1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p2') Value: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: S2*) (Syntax: 'p2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p3 = &(x ? p1 : p2)->i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32*) (Syntax: 'p3 = &(x ? p1 : p2)->i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32*, IsImplicit) (Syntax: 'p3') Right: IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&(x ? p1 : p2)->i') Reference: IFieldReferenceOperation: System.Int32 S2.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(x ? p1 : p2)->i') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(x ? p1 : p2)') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: S2*, IsImplicit) (Syntax: 'x ? p1 : p2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, TestOptions.UnsafeDebugDll); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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_IAddressOfOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void AddressOfFlow_01() { string source = @" class C { unsafe void M(int i) /*<bind>*/{ int* p = &i; }/*</bind>*/ }"; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32* p] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32*, IsImplicit) (Syntax: 'p = &i') Left: ILocalReferenceOperation: p (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32*, IsImplicit) (Syntax: 'p = &i') Right: IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&i') Reference: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void AddressOfFlow_02() { string source = @" struct S2 { unsafe void M(bool x, S2* p1, S2* p2, int* p3) /*<bind>*/ { p3 = &(x ? p1 : p2)->i; }/*</bind>*/ public int i; }"; var expectedDiagnostics = DiagnosticDescription.None; 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: 'p3') Value: IParameterReferenceOperation: p3 (OperationKind.ParameterReference, Type: System.Int32*) (Syntax: 'p3') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p1') Value: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: S2*) (Syntax: 'p1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p2') Value: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: S2*) (Syntax: 'p2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p3 = &(x ? p1 : p2)->i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32*) (Syntax: 'p3 = &(x ? p1 : p2)->i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32*, IsImplicit) (Syntax: 'p3') Right: IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&(x ? p1 : p2)->i') Reference: IFieldReferenceOperation: System.Int32 S2.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(x ? p1 : p2)->i') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(x ? p1 : p2)') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: S2*, IsImplicit) (Syntax: 'x ? p1 : p2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, TestOptions.UnsafeDebugDll); } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/EditorFeatures/Core/InheritanceMargin/InheritanceTargetItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.FindUsages; namespace Microsoft.CodeAnalysis.InheritanceMargin { /// <summary> /// Information used to decided the margin image and responsible for performing navigations /// </summary> internal readonly struct InheritanceTargetItem { /// <summary> /// Indicate the inheritance relationship between the target and member. /// </summary> public readonly InheritanceRelationship RelationToMember; /// <summary> /// DefinitionItem used to display the additional information and performs navigation. /// </summary> public readonly DefinitionItem DefinitionItem; /// <summary> /// The glyph for this target. /// </summary> public readonly Glyph Glyph; /// <summary> /// The display name used in margin. /// </summary> public readonly string DisplayName; public InheritanceTargetItem( InheritanceRelationship relationToMember, DefinitionItem definitionItem, Glyph glyph, string displayName) { RelationToMember = relationToMember; DefinitionItem = definitionItem; Glyph = glyph; DisplayName = displayName; } public static async ValueTask<InheritanceTargetItem> ConvertAsync( Solution solution, SerializableInheritanceTargetItem serializableItem, CancellationToken cancellationToken) { var definitionItem = await serializableItem.DefinitionItem.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false); return new InheritanceTargetItem( serializableItem.RelationToMember, definitionItem, serializableItem.Glyph, serializableItem.DisplayName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.FindUsages; namespace Microsoft.CodeAnalysis.InheritanceMargin { /// <summary> /// Information used to decided the margin image and responsible for performing navigations /// </summary> internal readonly struct InheritanceTargetItem { /// <summary> /// Indicate the inheritance relationship between the target and member. /// </summary> public readonly InheritanceRelationship RelationToMember; /// <summary> /// DefinitionItem used to display the additional information and performs navigation. /// </summary> public readonly DefinitionItem DefinitionItem; /// <summary> /// The glyph for this target. /// </summary> public readonly Glyph Glyph; /// <summary> /// The display name used in margin. /// </summary> public readonly string DisplayName; public InheritanceTargetItem( InheritanceRelationship relationToMember, DefinitionItem definitionItem, Glyph glyph, string displayName) { RelationToMember = relationToMember; DefinitionItem = definitionItem; Glyph = glyph; DisplayName = displayName; } public static async ValueTask<InheritanceTargetItem> ConvertAsync( Solution solution, SerializableInheritanceTargetItem serializableItem, CancellationToken cancellationToken) { var definitionItem = await serializableItem.DefinitionItem.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false); return new InheritanceTargetItem( serializableItem.RelationToMember, definitionItem, serializableItem.Glyph, serializableItem.DisplayName); } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/SymbolSpecification/SymbolSpecificationViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal class SymbolSpecificationViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel { public Guid ID { get; set; } public List<SymbolKindViewModel> SymbolKindList { get; set; } public List<AccessibilityViewModel> AccessibilityList { get; set; } public List<ModifierViewModel> ModifierList { get; set; } private string _symbolSpecName; public bool CanBeDeleted { get; set; } private readonly INotificationService _notificationService; public SymbolSpecificationViewModel( string languageName, bool canBeDeleted, INotificationService notificationService) : this(languageName, CreateDefaultSymbolSpecification(), canBeDeleted, notificationService) { } public SymbolSpecificationViewModel(string languageName, SymbolSpecification specification, bool canBeDeleted, INotificationService notificationService) { CanBeDeleted = canBeDeleted; _notificationService = notificationService; ItemName = specification.Name; ID = specification.ID; // The list of supported SymbolKinds is limited due to https://github.com/dotnet/roslyn/issues/8753. if (languageName == LanguageNames.CSharp) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_CSharp_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_CSharp_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_CSharp_Struct, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_CSharp_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_CSharp_Enum, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_CSharp_Property, specification), new SymbolKindViewModel(MethodKind.Ordinary, ServicesVSResources.NamingSpecification_CSharp_Method, specification), new SymbolKindViewModel(MethodKind.LocalFunction, ServicesVSResources.NamingSpecification_CSharp_LocalFunction, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_CSharp_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_CSharp_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_CSharp_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_CSharp_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_CSharp_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_CSharp_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "public", specification), new AccessibilityViewModel(Accessibility.Internal, "internal", specification), new AccessibilityViewModel(Accessibility.Private, "private", specification), new AccessibilityViewModel(Accessibility.Protected, "protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "protected internal", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "private protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "abstract", specification), new ModifierViewModel(DeclarationModifiers.Async, "async", specification), new ModifierViewModel(DeclarationModifiers.Const, "const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "readonly", specification), new ModifierViewModel(DeclarationModifiers.Static, "static", specification) }; } else if (languageName == LanguageNames.VisualBasic) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_VisualBasic_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_VisualBasic_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_VisualBasic_Structure, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_VisualBasic_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_VisualBasic_Enum, specification), new SymbolKindViewModel(TypeKind.Module, ServicesVSResources.NamingSpecification_VisualBasic_Module, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_VisualBasic_Property, specification), new SymbolKindViewModel(SymbolKind.Method, ServicesVSResources.NamingSpecification_VisualBasic_Method, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_VisualBasic_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_VisualBasic_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_VisualBasic_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_VisualBasic_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_VisualBasic_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_VisualBasic_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "Public", specification), new AccessibilityViewModel(Accessibility.Friend, "Friend", specification), new AccessibilityViewModel(Accessibility.Private, "Private", specification), new AccessibilityViewModel(Accessibility.Protected , "Protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "Protected Friend", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "Private Protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "Local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "MustInherit", specification), new ModifierViewModel(DeclarationModifiers.Async, "Async", specification), new ModifierViewModel(DeclarationModifiers.Const, "Const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "ReadOnly", specification), new ModifierViewModel(DeclarationModifiers.Static, "Shared", specification) }; } else { throw new ArgumentException(string.Format("Unexpected language name: {0}", languageName), nameof(languageName)); } } public string ItemName { get { return _symbolSpecName; } set { SetProperty(ref _symbolSpecName, value); } } internal SymbolSpecification GetSymbolSpecification() { return new SymbolSpecification( ID, ItemName, SymbolKindList.Where(s => s.IsChecked).Select(s => s.CreateSymbolOrTypeOrMethodKind()).ToImmutableArray(), AccessibilityList.Where(a => a.IsChecked).Select(a => a._accessibility).ToImmutableArray(), ModifierList.Where(m => m.IsChecked).Select(m => new ModifierKind(m._modifier)).ToImmutableArray()); } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(ItemName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style); return false; } return true; } // For screen readers public override string ToString() => _symbolSpecName; internal interface ISymbolSpecificationViewModelPart { bool IsChecked { get; set; } } public class SymbolKindViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } private readonly SymbolKind? _symbolKind; private readonly TypeKind? _typeKind; private readonly MethodKind? _methodKind; private bool _isChecked; public SymbolKindViewModel(SymbolKind symbolKind, string name, SymbolSpecification specification) { _symbolKind = symbolKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.SymbolKind == symbolKind); } public SymbolKindViewModel(TypeKind typeKind, string name, SymbolSpecification specification) { _typeKind = typeKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.TypeKind == typeKind); } public SymbolKindViewModel(MethodKind methodKind, string name, SymbolSpecification specification) { _methodKind = methodKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.MethodKind == methodKind); } internal SymbolKindOrTypeKind CreateSymbolOrTypeOrMethodKind() { return _symbolKind.HasValue ? new SymbolKindOrTypeKind(_symbolKind.Value) : _typeKind.HasValue ? new SymbolKindOrTypeKind(_typeKind.Value) : _methodKind.HasValue ? new SymbolKindOrTypeKind(_methodKind.Value) : throw ExceptionUtilities.Unreachable; } } public class AccessibilityViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { internal readonly Accessibility _accessibility; public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } public AccessibilityViewModel(Accessibility accessibility, string name, SymbolSpecification specification) { _accessibility = accessibility; Name = name; IsChecked = specification.ApplicableAccessibilityList.Any(a => a == accessibility); } } public class ModifierViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } internal readonly DeclarationModifiers _modifier; public ModifierViewModel(DeclarationModifiers modifier, string name, SymbolSpecification specification) { _modifier = modifier; Name = name; IsChecked = specification.RequiredModifierList.Any(m => m.Modifier == modifier); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal class SymbolSpecificationViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel { public Guid ID { get; set; } public List<SymbolKindViewModel> SymbolKindList { get; set; } public List<AccessibilityViewModel> AccessibilityList { get; set; } public List<ModifierViewModel> ModifierList { get; set; } private string _symbolSpecName; public bool CanBeDeleted { get; set; } private readonly INotificationService _notificationService; public SymbolSpecificationViewModel( string languageName, bool canBeDeleted, INotificationService notificationService) : this(languageName, CreateDefaultSymbolSpecification(), canBeDeleted, notificationService) { } public SymbolSpecificationViewModel(string languageName, SymbolSpecification specification, bool canBeDeleted, INotificationService notificationService) { CanBeDeleted = canBeDeleted; _notificationService = notificationService; ItemName = specification.Name; ID = specification.ID; // The list of supported SymbolKinds is limited due to https://github.com/dotnet/roslyn/issues/8753. if (languageName == LanguageNames.CSharp) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_CSharp_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_CSharp_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_CSharp_Struct, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_CSharp_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_CSharp_Enum, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_CSharp_Property, specification), new SymbolKindViewModel(MethodKind.Ordinary, ServicesVSResources.NamingSpecification_CSharp_Method, specification), new SymbolKindViewModel(MethodKind.LocalFunction, ServicesVSResources.NamingSpecification_CSharp_LocalFunction, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_CSharp_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_CSharp_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_CSharp_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_CSharp_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_CSharp_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_CSharp_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "public", specification), new AccessibilityViewModel(Accessibility.Internal, "internal", specification), new AccessibilityViewModel(Accessibility.Private, "private", specification), new AccessibilityViewModel(Accessibility.Protected, "protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "protected internal", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "private protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "abstract", specification), new ModifierViewModel(DeclarationModifiers.Async, "async", specification), new ModifierViewModel(DeclarationModifiers.Const, "const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "readonly", specification), new ModifierViewModel(DeclarationModifiers.Static, "static", specification) }; } else if (languageName == LanguageNames.VisualBasic) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_VisualBasic_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_VisualBasic_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_VisualBasic_Structure, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_VisualBasic_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_VisualBasic_Enum, specification), new SymbolKindViewModel(TypeKind.Module, ServicesVSResources.NamingSpecification_VisualBasic_Module, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_VisualBasic_Property, specification), new SymbolKindViewModel(SymbolKind.Method, ServicesVSResources.NamingSpecification_VisualBasic_Method, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_VisualBasic_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_VisualBasic_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_VisualBasic_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_VisualBasic_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_VisualBasic_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_VisualBasic_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "Public", specification), new AccessibilityViewModel(Accessibility.Friend, "Friend", specification), new AccessibilityViewModel(Accessibility.Private, "Private", specification), new AccessibilityViewModel(Accessibility.Protected , "Protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "Protected Friend", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "Private Protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "Local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "MustInherit", specification), new ModifierViewModel(DeclarationModifiers.Async, "Async", specification), new ModifierViewModel(DeclarationModifiers.Const, "Const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "ReadOnly", specification), new ModifierViewModel(DeclarationModifiers.Static, "Shared", specification) }; } else { throw new ArgumentException(string.Format("Unexpected language name: {0}", languageName), nameof(languageName)); } } public string ItemName { get { return _symbolSpecName; } set { SetProperty(ref _symbolSpecName, value); } } internal SymbolSpecification GetSymbolSpecification() { return new SymbolSpecification( ID, ItemName, SymbolKindList.Where(s => s.IsChecked).Select(s => s.CreateSymbolOrTypeOrMethodKind()).ToImmutableArray(), AccessibilityList.Where(a => a.IsChecked).Select(a => a._accessibility).ToImmutableArray(), ModifierList.Where(m => m.IsChecked).Select(m => new ModifierKind(m._modifier)).ToImmutableArray()); } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(ItemName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style); return false; } return true; } // For screen readers public override string ToString() => _symbolSpecName; internal interface ISymbolSpecificationViewModelPart { bool IsChecked { get; set; } } public class SymbolKindViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } private readonly SymbolKind? _symbolKind; private readonly TypeKind? _typeKind; private readonly MethodKind? _methodKind; private bool _isChecked; public SymbolKindViewModel(SymbolKind symbolKind, string name, SymbolSpecification specification) { _symbolKind = symbolKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.SymbolKind == symbolKind); } public SymbolKindViewModel(TypeKind typeKind, string name, SymbolSpecification specification) { _typeKind = typeKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.TypeKind == typeKind); } public SymbolKindViewModel(MethodKind methodKind, string name, SymbolSpecification specification) { _methodKind = methodKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.MethodKind == methodKind); } internal SymbolKindOrTypeKind CreateSymbolOrTypeOrMethodKind() { return _symbolKind.HasValue ? new SymbolKindOrTypeKind(_symbolKind.Value) : _typeKind.HasValue ? new SymbolKindOrTypeKind(_typeKind.Value) : _methodKind.HasValue ? new SymbolKindOrTypeKind(_methodKind.Value) : throw ExceptionUtilities.Unreachable; } } public class AccessibilityViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { internal readonly Accessibility _accessibility; public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } public AccessibilityViewModel(Accessibility accessibility, string name, SymbolSpecification specification) { _accessibility = accessibility; Name = name; IsChecked = specification.ApplicableAccessibilityList.Any(a => a == accessibility); } } public class ModifierViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } internal readonly DeclarationModifiers _modifier; public ModifierViewModel(DeclarationModifiers modifier, string name, SymbolSpecification specification) { _modifier = modifier; Name = name; IsChecked = specification.RequiredModifierList.Any(m => m.Modifier == modifier); } } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Features/CSharp/Portable/Structure/Providers/AnonymousMethodExpressionStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class AnonymousMethodExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<AnonymousMethodExpressionSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, AnonymousMethodExpressionSyntax anonymousMethod, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance if (anonymousMethod.Block.IsMissing || anonymousMethod.Block.OpenBraceToken.IsMissing || anonymousMethod.Block.CloseBraceToken.IsMissing) { return; } var lastToken = CSharpStructureHelpers.GetLastInlineMethodBlockToken(anonymousMethod); if (lastToken.Kind() == SyntaxKind.None) { return; } var startToken = anonymousMethod.ParameterList != null ? anonymousMethod.ParameterList.GetLastToken(includeZeroWidth: true) : anonymousMethod.DelegateKeyword; spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( anonymousMethod, startToken, lastToken, compressEmptyLines: false, autoCollapse: false, type: BlockTypes.Expression, isCollapsible: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class AnonymousMethodExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<AnonymousMethodExpressionSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, AnonymousMethodExpressionSyntax anonymousMethod, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance if (anonymousMethod.Block.IsMissing || anonymousMethod.Block.OpenBraceToken.IsMissing || anonymousMethod.Block.CloseBraceToken.IsMissing) { return; } var lastToken = CSharpStructureHelpers.GetLastInlineMethodBlockToken(anonymousMethod); if (lastToken.Kind() == SyntaxKind.None) { return; } var startToken = anonymousMethod.ParameterList != null ? anonymousMethod.ParameterList.GetLastToken(includeZeroWidth: true) : anonymousMethod.DelegateKeyword; spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( anonymousMethod, startToken, lastToken, compressEmptyLines: false, autoCollapse: false, type: BlockTypes.Expression, isCollapsible: true)); } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Compilers/Core/Portable/Syntax/GreenNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract class GreenNode : IObjectWritable { private string GetDebuggerDisplay() { return this.GetType().Name + " " + this.KindText + " " + this.ToString(); } internal const int ListKind = 1; private readonly ushort _kind; protected NodeFlags flags; private byte _slotCount; private int _fullWidth; private static readonly ConditionalWeakTable<GreenNode, DiagnosticInfo[]> s_diagnosticsTable = new ConditionalWeakTable<GreenNode, DiagnosticInfo[]>(); private static readonly ConditionalWeakTable<GreenNode, SyntaxAnnotation[]> s_annotationsTable = new ConditionalWeakTable<GreenNode, SyntaxAnnotation[]>(); private static readonly DiagnosticInfo[] s_noDiagnostics = Array.Empty<DiagnosticInfo>(); private static readonly SyntaxAnnotation[] s_noAnnotations = Array.Empty<SyntaxAnnotation>(); private static readonly IEnumerable<SyntaxAnnotation> s_noAnnotationsEnumerable = SpecializedCollections.EmptyEnumerable<SyntaxAnnotation>(); protected GreenNode(ushort kind) { _kind = kind; } protected GreenNode(ushort kind, int fullWidth) { _kind = kind; _fullWidth = fullWidth; } protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, int fullWidth) { _kind = kind; _fullWidth = fullWidth; if (diagnostics?.Length > 0) { this.flags |= NodeFlags.ContainsDiagnostics; s_diagnosticsTable.Add(this, diagnostics); } } protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics) { _kind = kind; if (diagnostics?.Length > 0) { this.flags |= NodeFlags.ContainsDiagnostics; s_diagnosticsTable.Add(this, diagnostics); } } protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) : this(kind, diagnostics) { if (annotations?.Length > 0) { foreach (var annotation in annotations) { if (annotation == null) throw new ArgumentException(paramName: nameof(annotations), message: "" /*CSharpResources.ElementsCannotBeNull*/); } this.flags |= NodeFlags.ContainsAnnotations; s_annotationsTable.Add(this, annotations); } } protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, int fullWidth) : this(kind, diagnostics, fullWidth) { if (annotations?.Length > 0) { foreach (var annotation in annotations) { if (annotation == null) throw new ArgumentException(paramName: nameof(annotations), message: "" /*CSharpResources.ElementsCannotBeNull*/); } this.flags |= NodeFlags.ContainsAnnotations; s_annotationsTable.Add(this, annotations); } } protected void AdjustFlagsAndWidth(GreenNode node) { RoslynDebug.Assert(node != null, "PERF: caller must ensure that node!=null, we do not want to re-check that here."); this.flags |= (node.flags & NodeFlags.InheritMask); _fullWidth += node._fullWidth; } public abstract string Language { get; } #region Kind public int RawKind { get { return _kind; } } public bool IsList { get { return RawKind == ListKind; } } public abstract string KindText { get; } public virtual bool IsStructuredTrivia => false; public virtual bool IsDirective => false; public virtual bool IsToken => false; public virtual bool IsTrivia => false; public virtual bool IsSkippedTokensTrivia => false; public virtual bool IsDocumentationCommentTrivia => false; #endregion #region Slots public int SlotCount { get { int count = _slotCount; if (count == byte.MaxValue) { count = GetSlotCount(); } return count; } protected set { _slotCount = (byte)value; } } internal abstract GreenNode? GetSlot(int index); internal GreenNode GetRequiredSlot(int index) { var node = GetSlot(index); RoslynDebug.Assert(node is object); return node; } // for slot counts >= byte.MaxValue protected virtual int GetSlotCount() { return _slotCount; } public virtual int GetSlotOffset(int index) { int offset = 0; for (int i = 0; i < index; i++) { var child = this.GetSlot(i); if (child != null) { offset += child.FullWidth; } } return offset; } internal Syntax.InternalSyntax.ChildSyntaxList ChildNodesAndTokens() { return new Syntax.InternalSyntax.ChildSyntaxList(this); } /// <summary> /// Enumerates all nodes of the tree rooted by this node (including this node). /// </summary> internal IEnumerable<GreenNode> EnumerateNodes() { yield return this; var stack = new Stack<Syntax.InternalSyntax.ChildSyntaxList.Enumerator>(24); stack.Push(this.ChildNodesAndTokens().GetEnumerator()); while (stack.Count > 0) { var en = stack.Pop(); if (!en.MoveNext()) { // no more down this branch continue; } var current = en.Current; stack.Push(en); // put it back on stack (struct enumerator) yield return current; if (!current.IsToken) { // not token, so consider children stack.Push(current.ChildNodesAndTokens().GetEnumerator()); continue; } } } /// <summary> /// Find the slot that contains the given offset. /// </summary> /// <param name="offset">The target offset. Must be between 0 and <see cref="FullWidth"/>.</param> /// <returns>The slot index of the slot containing the given offset.</returns> /// <remarks> /// The base implementation is a linear search. This should be overridden /// if a derived class can implement it more efficiently. /// </remarks> public virtual int FindSlotIndexContainingOffset(int offset) { Debug.Assert(0 <= offset && offset < FullWidth); int i; int accumulatedWidth = 0; for (i = 0; ; i++) { Debug.Assert(i < SlotCount); var child = GetSlot(i); if (child != null) { accumulatedWidth += child.FullWidth; if (offset < accumulatedWidth) { break; } } } return i; } #endregion #region Flags [Flags] internal enum NodeFlags : byte { None = 0, ContainsDiagnostics = 1 << 0, ContainsStructuredTrivia = 1 << 1, ContainsDirectives = 1 << 2, ContainsSkippedText = 1 << 3, ContainsAnnotations = 1 << 4, IsNotMissing = 1 << 5, FactoryContextIsInAsync = 1 << 6, FactoryContextIsInQuery = 1 << 7, FactoryContextIsInIterator = FactoryContextIsInQuery, // VB does not use "InQuery", but uses "InIterator" instead InheritMask = ContainsDiagnostics | ContainsStructuredTrivia | ContainsDirectives | ContainsSkippedText | ContainsAnnotations | IsNotMissing, } internal NodeFlags Flags { get { return this.flags; } } internal void SetFlags(NodeFlags flags) { this.flags |= flags; } internal void ClearFlags(NodeFlags flags) { this.flags &= ~flags; } internal bool IsMissing { get { // flag has reversed meaning hence "==" return (this.flags & NodeFlags.IsNotMissing) == 0; } } internal bool ParsedInAsync { get { return (this.flags & NodeFlags.FactoryContextIsInAsync) != 0; } } internal bool ParsedInQuery { get { return (this.flags & NodeFlags.FactoryContextIsInQuery) != 0; } } internal bool ParsedInIterator { get { return (this.flags & NodeFlags.FactoryContextIsInIterator) != 0; } } public bool ContainsSkippedText { get { return (this.flags & NodeFlags.ContainsSkippedText) != 0; } } public bool ContainsStructuredTrivia { get { return (this.flags & NodeFlags.ContainsStructuredTrivia) != 0; } } public bool ContainsDirectives { get { return (this.flags & NodeFlags.ContainsDirectives) != 0; } } public bool ContainsDiagnostics { get { return (this.flags & NodeFlags.ContainsDiagnostics) != 0; } } public bool ContainsAnnotations { get { return (this.flags & NodeFlags.ContainsAnnotations) != 0; } } #endregion #region Spans public int FullWidth { get { return _fullWidth; } protected set { _fullWidth = value; } } public virtual int Width { get { return _fullWidth - this.GetLeadingTriviaWidth() - this.GetTrailingTriviaWidth(); } } public virtual int GetLeadingTriviaWidth() { return this.FullWidth != 0 ? this.GetFirstTerminal()!.GetLeadingTriviaWidth() : 0; } public virtual int GetTrailingTriviaWidth() { return this.FullWidth != 0 ? this.GetLastTerminal()!.GetTrailingTriviaWidth() : 0; } public bool HasLeadingTrivia { get { return this.GetLeadingTriviaWidth() != 0; } } public bool HasTrailingTrivia { get { return this.GetTrailingTriviaWidth() != 0; } } #endregion #region Serialization // use high-bit on Kind to identify serialization of extra info private const UInt16 ExtendedSerializationInfoMask = unchecked((UInt16)(1u << 15)); internal GreenNode(ObjectReader reader) { var kindBits = reader.ReadUInt16(); _kind = (ushort)(kindBits & ~ExtendedSerializationInfoMask); if ((kindBits & ExtendedSerializationInfoMask) != 0) { var diagnostics = (DiagnosticInfo[])reader.ReadValue(); if (diagnostics != null && diagnostics.Length > 0) { this.flags |= NodeFlags.ContainsDiagnostics; s_diagnosticsTable.Add(this, diagnostics); } var annotations = (SyntaxAnnotation[])reader.ReadValue(); if (annotations != null && annotations.Length > 0) { this.flags |= NodeFlags.ContainsAnnotations; s_annotationsTable.Add(this, annotations); } } } bool IObjectWritable.ShouldReuseInSerialization => ShouldReuseInSerialization; internal virtual bool ShouldReuseInSerialization => this.IsCacheable; void IObjectWritable.WriteTo(ObjectWriter writer) { this.WriteTo(writer); } internal virtual void WriteTo(ObjectWriter writer) { var kindBits = (UInt16)_kind; var hasDiagnostics = this.GetDiagnostics().Length > 0; var hasAnnotations = this.GetAnnotations().Length > 0; if (hasDiagnostics || hasAnnotations) { kindBits |= ExtendedSerializationInfoMask; writer.WriteUInt16(kindBits); writer.WriteValue(hasDiagnostics ? this.GetDiagnostics() : null); writer.WriteValue(hasAnnotations ? this.GetAnnotations() : null); } else { writer.WriteUInt16(kindBits); } } #endregion #region Annotations public bool HasAnnotations(string annotationKind) { var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return false; } foreach (var a in annotations) { if (a.Kind == annotationKind) { return true; } } return false; } public bool HasAnnotations(IEnumerable<string> annotationKinds) { var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return false; } foreach (var a in annotations) { if (annotationKinds.Contains(a.Kind)) { return true; } } return false; } public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) { var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return false; } foreach (var a in annotations) { if (a == annotation) { return true; } } return false; } public IEnumerable<SyntaxAnnotation> GetAnnotations(string annotationKind) { if (string.IsNullOrWhiteSpace(annotationKind)) { throw new ArgumentNullException(nameof(annotationKind)); } var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return s_noAnnotationsEnumerable; } return GetAnnotationsSlow(annotations, annotationKind); } private static IEnumerable<SyntaxAnnotation> GetAnnotationsSlow(SyntaxAnnotation[] annotations, string annotationKind) { foreach (var annotation in annotations) { if (annotation.Kind == annotationKind) { yield return annotation; } } } public IEnumerable<SyntaxAnnotation> GetAnnotations(IEnumerable<string> annotationKinds) { if (annotationKinds == null) { throw new ArgumentNullException(nameof(annotationKinds)); } var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return s_noAnnotationsEnumerable; } return GetAnnotationsSlow(annotations, annotationKinds); } private static IEnumerable<SyntaxAnnotation> GetAnnotationsSlow(SyntaxAnnotation[] annotations, IEnumerable<string> annotationKinds) { foreach (var annotation in annotations) { if (annotationKinds.Contains(annotation.Kind)) { yield return annotation; } } } public SyntaxAnnotation[] GetAnnotations() { if (this.ContainsAnnotations) { SyntaxAnnotation[]? annotations; if (s_annotationsTable.TryGetValue(this, out annotations)) { System.Diagnostics.Debug.Assert(annotations.Length != 0, "we should return nonempty annotations or NoAnnotations"); return annotations; } } return s_noAnnotations; } internal abstract GreenNode SetAnnotations(SyntaxAnnotation[]? annotations); #endregion #region Diagnostics internal DiagnosticInfo[] GetDiagnostics() { if (this.ContainsDiagnostics) { DiagnosticInfo[]? diags; if (s_diagnosticsTable.TryGetValue(this, out diags)) { return diags; } } return s_noDiagnostics; } internal abstract GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics); #endregion #region Text public virtual string ToFullString() { var sb = PooledStringBuilder.GetInstance(); var writer = new System.IO.StringWriter(sb.Builder, System.Globalization.CultureInfo.InvariantCulture); this.WriteTo(writer, leading: true, trailing: true); return sb.ToStringAndFree(); } public override string ToString() { var sb = PooledStringBuilder.GetInstance(); var writer = new System.IO.StringWriter(sb.Builder, System.Globalization.CultureInfo.InvariantCulture); this.WriteTo(writer, leading: false, trailing: false); return sb.ToStringAndFree(); } public void WriteTo(System.IO.TextWriter writer) { this.WriteTo(writer, leading: true, trailing: true); } protected internal void WriteTo(TextWriter writer, bool leading, bool trailing) { // Use an actual stack so we can write out deeply recursive structures without overflowing. var stack = ArrayBuilder<(GreenNode node, bool leading, bool trailing)>.GetInstance(); stack.Push((this, leading, trailing)); // Separated out stack processing logic so that it does not unintentionally refer to // "this", "leading" or "trailing". processStack(writer, stack); stack.Free(); return; static void processStack( TextWriter writer, ArrayBuilder<(GreenNode node, bool leading, bool trailing)> stack) { while (stack.Count > 0) { var current = stack.Pop(); var currentNode = current.node; var currentLeading = current.leading; var currentTrailing = current.trailing; if (currentNode.IsToken) { currentNode.WriteTokenTo(writer, currentLeading, currentTrailing); continue; } if (currentNode.IsTrivia) { currentNode.WriteTriviaTo(writer); continue; } var firstIndex = GetFirstNonNullChildIndex(currentNode); var lastIndex = GetLastNonNullChildIndex(currentNode); for (var i = lastIndex; i >= firstIndex; i--) { var child = currentNode.GetSlot(i); if (child != null) { var first = i == firstIndex; var last = i == lastIndex; stack.Push((child, currentLeading | !first, currentTrailing | !last)); } } } } } private static int GetFirstNonNullChildIndex(GreenNode node) { int n = node.SlotCount; int firstIndex = 0; for (; firstIndex < n; firstIndex++) { var child = node.GetSlot(firstIndex); if (child != null) { break; } } return firstIndex; } private static int GetLastNonNullChildIndex(GreenNode node) { int n = node.SlotCount; int lastIndex = n - 1; for (; lastIndex >= 0; lastIndex--) { var child = node.GetSlot(lastIndex); if (child != null) { break; } } return lastIndex; } protected virtual void WriteTriviaTo(TextWriter writer) { throw new NotImplementedException(); } protected virtual void WriteTokenTo(TextWriter writer, bool leading, bool trailing) { throw new NotImplementedException(); } #endregion #region Tokens public virtual int RawContextualKind { get { return this.RawKind; } } public virtual object? GetValue() { return null; } public virtual string GetValueText() { return string.Empty; } public virtual GreenNode? GetLeadingTriviaCore() { return null; } public virtual GreenNode? GetTrailingTriviaCore() { return null; } public virtual GreenNode WithLeadingTrivia(GreenNode? trivia) { return this; } public virtual GreenNode WithTrailingTrivia(GreenNode? trivia) { return this; } internal GreenNode? GetFirstTerminal() { GreenNode? node = this; do { GreenNode? firstChild = null; for (int i = 0, n = node.SlotCount; i < n; i++) { var child = node.GetSlot(i); if (child != null) { firstChild = child; break; } } node = firstChild; } while (node?._slotCount > 0); return node; } internal GreenNode? GetLastTerminal() { GreenNode? node = this; do { GreenNode? lastChild = null; for (int i = node.SlotCount - 1; i >= 0; i--) { var child = node.GetSlot(i); if (child != null) { lastChild = child; break; } } node = lastChild; } while (node?._slotCount > 0); return node; } internal GreenNode? GetLastNonmissingTerminal() { GreenNode? node = this; do { GreenNode? nonmissingChild = null; for (int i = node.SlotCount - 1; i >= 0; i--) { var child = node.GetSlot(i); if (child != null && !child.IsMissing) { nonmissingChild = child; break; } } node = nonmissingChild; } while (node?._slotCount > 0); return node; } #endregion #region Equivalence public virtual bool IsEquivalentTo([NotNullWhen(true)] GreenNode? other) { if (this == other) { return true; } if (other == null) { return false; } return EquivalentToInternal(this, other); } private static bool EquivalentToInternal(GreenNode node1, GreenNode node2) { if (node1.RawKind != node2.RawKind) { // A single-element list is usually represented as just a single node, // but can be represented as a List node with one child. Move to that // child if necessary. if (node1.IsList && node1.SlotCount == 1) { node1 = node1.GetRequiredSlot(0); } if (node2.IsList && node2.SlotCount == 1) { node2 = node2.GetRequiredSlot(0); } if (node1.RawKind != node2.RawKind) { return false; } } if (node1._fullWidth != node2._fullWidth) { return false; } var n = node1.SlotCount; if (n != node2.SlotCount) { return false; } for (int i = 0; i < n; i++) { var node1Child = node1.GetSlot(i); var node2Child = node2.GetSlot(i); if (node1Child != null && node2Child != null && !node1Child.IsEquivalentTo(node2Child)) { return false; } } return true; } #endregion public abstract SyntaxNode GetStructure(SyntaxTrivia parentTrivia); #region Factories public abstract SyntaxToken CreateSeparator<TNode>(SyntaxNode element) where TNode : SyntaxNode; public abstract bool IsTriviaWithEndOfLine(); // trivia node has end of line /* * There are 3 overloads of this, because most callers already know what they have is a List<T> and only transform it. * In those cases List<TFrom> performs much better. * In other cases, the type is unknown / is IEnumerable<T>, where we try to find the best match. * There is another overload for IReadOnlyList, since most collections already implement this, so checking for it will * perform better then copying to a List<T>, though not as good as List<T> directly. */ public static GreenNode? CreateList<TFrom>(IEnumerable<TFrom>? enumerable, Func<TFrom, GreenNode> select) => enumerable switch { null => null, List<TFrom> l => CreateList(l, select), IReadOnlyList<TFrom> l => CreateList(l, select), _ => CreateList(enumerable.ToList(), select) }; public static GreenNode? CreateList<TFrom>(List<TFrom> list, Func<TFrom, GreenNode> select) { switch (list.Count) { case 0: return null; case 1: return select(list[0]); case 2: return SyntaxList.List(select(list[0]), select(list[1])); case 3: return SyntaxList.List(select(list[0]), select(list[1]), select(list[2])); default: { var array = new ArrayElement<GreenNode>[list.Count]; for (int i = 0; i < array.Length; i++) array[i].Value = select(list[i]); return SyntaxList.List(array); } } } public static GreenNode? CreateList<TFrom>(IReadOnlyList<TFrom> list, Func<TFrom, GreenNode> select) { switch (list.Count) { case 0: return null; case 1: return select(list[0]); case 2: return SyntaxList.List(select(list[0]), select(list[1])); case 3: return SyntaxList.List(select(list[0]), select(list[1]), select(list[2])); default: { var array = new ArrayElement<GreenNode>[list.Count]; for (int i = 0; i < array.Length; i++) array[i].Value = select(list[i]); return SyntaxList.List(array); } } } public SyntaxNode CreateRed() { return CreateRed(null, 0); } internal abstract SyntaxNode CreateRed(SyntaxNode? parent, int position); #endregion #region Caching internal const int MaxCachedChildNum = 3; internal bool IsCacheable { get { return ((this.flags & NodeFlags.InheritMask) == NodeFlags.IsNotMissing) && this.SlotCount <= GreenNode.MaxCachedChildNum; } } internal int GetCacheHash() { Debug.Assert(this.IsCacheable); int code = (int)(this.flags) ^ this.RawKind; int cnt = this.SlotCount; for (int i = 0; i < cnt; i++) { var child = GetSlot(i); if (child != null) { code = Hash.Combine(RuntimeHelpers.GetHashCode(child), code); } } return code & Int32.MaxValue; } internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1) { Debug.Assert(this.IsCacheable); return this.RawKind == kind && this.flags == flags && this.GetSlot(0) == child1; } internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1, GreenNode? child2) { Debug.Assert(this.IsCacheable); return this.RawKind == kind && this.flags == flags && this.GetSlot(0) == child1 && this.GetSlot(1) == child2; } internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1, GreenNode? child2, GreenNode? child3) { Debug.Assert(this.IsCacheable); return this.RawKind == kind && this.flags == flags && this.GetSlot(0) == child1 && this.GetSlot(1) == child2 && this.GetSlot(2) == child3; } #endregion //Caching /// <summary> /// Add an error to the given node, creating a new node that is the same except it has no parent, /// and has the given error attached to it. The error span is the entire span of this node. /// </summary> /// <param name="err">The error to attach to this node</param> /// <returns>A new node, with no parent, that has this error added to it.</returns> /// <remarks>Since nodes are immutable, the only way to create nodes with errors attached is to create a node without an error, /// then add an error with this method to create another node.</remarks> internal GreenNode AddError(DiagnosticInfo err) { DiagnosticInfo[] errorInfos; // If the green node already has errors, add those on. if (GetDiagnostics() == null) { errorInfos = new[] { err }; } else { // Add the error to the error list. errorInfos = GetDiagnostics(); var length = errorInfos.Length; Array.Resize(ref errorInfos, length + 1); errorInfos[length] = err; } // Get a new green node with the errors added on. return SetDiagnostics(errorInfos); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract class GreenNode : IObjectWritable { private string GetDebuggerDisplay() { return this.GetType().Name + " " + this.KindText + " " + this.ToString(); } internal const int ListKind = 1; private readonly ushort _kind; protected NodeFlags flags; private byte _slotCount; private int _fullWidth; private static readonly ConditionalWeakTable<GreenNode, DiagnosticInfo[]> s_diagnosticsTable = new ConditionalWeakTable<GreenNode, DiagnosticInfo[]>(); private static readonly ConditionalWeakTable<GreenNode, SyntaxAnnotation[]> s_annotationsTable = new ConditionalWeakTable<GreenNode, SyntaxAnnotation[]>(); private static readonly DiagnosticInfo[] s_noDiagnostics = Array.Empty<DiagnosticInfo>(); private static readonly SyntaxAnnotation[] s_noAnnotations = Array.Empty<SyntaxAnnotation>(); private static readonly IEnumerable<SyntaxAnnotation> s_noAnnotationsEnumerable = SpecializedCollections.EmptyEnumerable<SyntaxAnnotation>(); protected GreenNode(ushort kind) { _kind = kind; } protected GreenNode(ushort kind, int fullWidth) { _kind = kind; _fullWidth = fullWidth; } protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, int fullWidth) { _kind = kind; _fullWidth = fullWidth; if (diagnostics?.Length > 0) { this.flags |= NodeFlags.ContainsDiagnostics; s_diagnosticsTable.Add(this, diagnostics); } } protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics) { _kind = kind; if (diagnostics?.Length > 0) { this.flags |= NodeFlags.ContainsDiagnostics; s_diagnosticsTable.Add(this, diagnostics); } } protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) : this(kind, diagnostics) { if (annotations?.Length > 0) { foreach (var annotation in annotations) { if (annotation == null) throw new ArgumentException(paramName: nameof(annotations), message: "" /*CSharpResources.ElementsCannotBeNull*/); } this.flags |= NodeFlags.ContainsAnnotations; s_annotationsTable.Add(this, annotations); } } protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, int fullWidth) : this(kind, diagnostics, fullWidth) { if (annotations?.Length > 0) { foreach (var annotation in annotations) { if (annotation == null) throw new ArgumentException(paramName: nameof(annotations), message: "" /*CSharpResources.ElementsCannotBeNull*/); } this.flags |= NodeFlags.ContainsAnnotations; s_annotationsTable.Add(this, annotations); } } protected void AdjustFlagsAndWidth(GreenNode node) { RoslynDebug.Assert(node != null, "PERF: caller must ensure that node!=null, we do not want to re-check that here."); this.flags |= (node.flags & NodeFlags.InheritMask); _fullWidth += node._fullWidth; } public abstract string Language { get; } #region Kind public int RawKind { get { return _kind; } } public bool IsList { get { return RawKind == ListKind; } } public abstract string KindText { get; } public virtual bool IsStructuredTrivia => false; public virtual bool IsDirective => false; public virtual bool IsToken => false; public virtual bool IsTrivia => false; public virtual bool IsSkippedTokensTrivia => false; public virtual bool IsDocumentationCommentTrivia => false; #endregion #region Slots public int SlotCount { get { int count = _slotCount; if (count == byte.MaxValue) { count = GetSlotCount(); } return count; } protected set { _slotCount = (byte)value; } } internal abstract GreenNode? GetSlot(int index); internal GreenNode GetRequiredSlot(int index) { var node = GetSlot(index); RoslynDebug.Assert(node is object); return node; } // for slot counts >= byte.MaxValue protected virtual int GetSlotCount() { return _slotCount; } public virtual int GetSlotOffset(int index) { int offset = 0; for (int i = 0; i < index; i++) { var child = this.GetSlot(i); if (child != null) { offset += child.FullWidth; } } return offset; } internal Syntax.InternalSyntax.ChildSyntaxList ChildNodesAndTokens() { return new Syntax.InternalSyntax.ChildSyntaxList(this); } /// <summary> /// Enumerates all nodes of the tree rooted by this node (including this node). /// </summary> internal IEnumerable<GreenNode> EnumerateNodes() { yield return this; var stack = new Stack<Syntax.InternalSyntax.ChildSyntaxList.Enumerator>(24); stack.Push(this.ChildNodesAndTokens().GetEnumerator()); while (stack.Count > 0) { var en = stack.Pop(); if (!en.MoveNext()) { // no more down this branch continue; } var current = en.Current; stack.Push(en); // put it back on stack (struct enumerator) yield return current; if (!current.IsToken) { // not token, so consider children stack.Push(current.ChildNodesAndTokens().GetEnumerator()); continue; } } } /// <summary> /// Find the slot that contains the given offset. /// </summary> /// <param name="offset">The target offset. Must be between 0 and <see cref="FullWidth"/>.</param> /// <returns>The slot index of the slot containing the given offset.</returns> /// <remarks> /// The base implementation is a linear search. This should be overridden /// if a derived class can implement it more efficiently. /// </remarks> public virtual int FindSlotIndexContainingOffset(int offset) { Debug.Assert(0 <= offset && offset < FullWidth); int i; int accumulatedWidth = 0; for (i = 0; ; i++) { Debug.Assert(i < SlotCount); var child = GetSlot(i); if (child != null) { accumulatedWidth += child.FullWidth; if (offset < accumulatedWidth) { break; } } } return i; } #endregion #region Flags [Flags] internal enum NodeFlags : byte { None = 0, ContainsDiagnostics = 1 << 0, ContainsStructuredTrivia = 1 << 1, ContainsDirectives = 1 << 2, ContainsSkippedText = 1 << 3, ContainsAnnotations = 1 << 4, IsNotMissing = 1 << 5, FactoryContextIsInAsync = 1 << 6, FactoryContextIsInQuery = 1 << 7, FactoryContextIsInIterator = FactoryContextIsInQuery, // VB does not use "InQuery", but uses "InIterator" instead InheritMask = ContainsDiagnostics | ContainsStructuredTrivia | ContainsDirectives | ContainsSkippedText | ContainsAnnotations | IsNotMissing, } internal NodeFlags Flags { get { return this.flags; } } internal void SetFlags(NodeFlags flags) { this.flags |= flags; } internal void ClearFlags(NodeFlags flags) { this.flags &= ~flags; } internal bool IsMissing { get { // flag has reversed meaning hence "==" return (this.flags & NodeFlags.IsNotMissing) == 0; } } internal bool ParsedInAsync { get { return (this.flags & NodeFlags.FactoryContextIsInAsync) != 0; } } internal bool ParsedInQuery { get { return (this.flags & NodeFlags.FactoryContextIsInQuery) != 0; } } internal bool ParsedInIterator { get { return (this.flags & NodeFlags.FactoryContextIsInIterator) != 0; } } public bool ContainsSkippedText { get { return (this.flags & NodeFlags.ContainsSkippedText) != 0; } } public bool ContainsStructuredTrivia { get { return (this.flags & NodeFlags.ContainsStructuredTrivia) != 0; } } public bool ContainsDirectives { get { return (this.flags & NodeFlags.ContainsDirectives) != 0; } } public bool ContainsDiagnostics { get { return (this.flags & NodeFlags.ContainsDiagnostics) != 0; } } public bool ContainsAnnotations { get { return (this.flags & NodeFlags.ContainsAnnotations) != 0; } } #endregion #region Spans public int FullWidth { get { return _fullWidth; } protected set { _fullWidth = value; } } public virtual int Width { get { return _fullWidth - this.GetLeadingTriviaWidth() - this.GetTrailingTriviaWidth(); } } public virtual int GetLeadingTriviaWidth() { return this.FullWidth != 0 ? this.GetFirstTerminal()!.GetLeadingTriviaWidth() : 0; } public virtual int GetTrailingTriviaWidth() { return this.FullWidth != 0 ? this.GetLastTerminal()!.GetTrailingTriviaWidth() : 0; } public bool HasLeadingTrivia { get { return this.GetLeadingTriviaWidth() != 0; } } public bool HasTrailingTrivia { get { return this.GetTrailingTriviaWidth() != 0; } } #endregion #region Serialization // use high-bit on Kind to identify serialization of extra info private const UInt16 ExtendedSerializationInfoMask = unchecked((UInt16)(1u << 15)); internal GreenNode(ObjectReader reader) { var kindBits = reader.ReadUInt16(); _kind = (ushort)(kindBits & ~ExtendedSerializationInfoMask); if ((kindBits & ExtendedSerializationInfoMask) != 0) { var diagnostics = (DiagnosticInfo[])reader.ReadValue(); if (diagnostics != null && diagnostics.Length > 0) { this.flags |= NodeFlags.ContainsDiagnostics; s_diagnosticsTable.Add(this, diagnostics); } var annotations = (SyntaxAnnotation[])reader.ReadValue(); if (annotations != null && annotations.Length > 0) { this.flags |= NodeFlags.ContainsAnnotations; s_annotationsTable.Add(this, annotations); } } } bool IObjectWritable.ShouldReuseInSerialization => ShouldReuseInSerialization; internal virtual bool ShouldReuseInSerialization => this.IsCacheable; void IObjectWritable.WriteTo(ObjectWriter writer) { this.WriteTo(writer); } internal virtual void WriteTo(ObjectWriter writer) { var kindBits = (UInt16)_kind; var hasDiagnostics = this.GetDiagnostics().Length > 0; var hasAnnotations = this.GetAnnotations().Length > 0; if (hasDiagnostics || hasAnnotations) { kindBits |= ExtendedSerializationInfoMask; writer.WriteUInt16(kindBits); writer.WriteValue(hasDiagnostics ? this.GetDiagnostics() : null); writer.WriteValue(hasAnnotations ? this.GetAnnotations() : null); } else { writer.WriteUInt16(kindBits); } } #endregion #region Annotations public bool HasAnnotations(string annotationKind) { var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return false; } foreach (var a in annotations) { if (a.Kind == annotationKind) { return true; } } return false; } public bool HasAnnotations(IEnumerable<string> annotationKinds) { var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return false; } foreach (var a in annotations) { if (annotationKinds.Contains(a.Kind)) { return true; } } return false; } public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) { var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return false; } foreach (var a in annotations) { if (a == annotation) { return true; } } return false; } public IEnumerable<SyntaxAnnotation> GetAnnotations(string annotationKind) { if (string.IsNullOrWhiteSpace(annotationKind)) { throw new ArgumentNullException(nameof(annotationKind)); } var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return s_noAnnotationsEnumerable; } return GetAnnotationsSlow(annotations, annotationKind); } private static IEnumerable<SyntaxAnnotation> GetAnnotationsSlow(SyntaxAnnotation[] annotations, string annotationKind) { foreach (var annotation in annotations) { if (annotation.Kind == annotationKind) { yield return annotation; } } } public IEnumerable<SyntaxAnnotation> GetAnnotations(IEnumerable<string> annotationKinds) { if (annotationKinds == null) { throw new ArgumentNullException(nameof(annotationKinds)); } var annotations = this.GetAnnotations(); if (annotations == s_noAnnotations) { return s_noAnnotationsEnumerable; } return GetAnnotationsSlow(annotations, annotationKinds); } private static IEnumerable<SyntaxAnnotation> GetAnnotationsSlow(SyntaxAnnotation[] annotations, IEnumerable<string> annotationKinds) { foreach (var annotation in annotations) { if (annotationKinds.Contains(annotation.Kind)) { yield return annotation; } } } public SyntaxAnnotation[] GetAnnotations() { if (this.ContainsAnnotations) { SyntaxAnnotation[]? annotations; if (s_annotationsTable.TryGetValue(this, out annotations)) { System.Diagnostics.Debug.Assert(annotations.Length != 0, "we should return nonempty annotations or NoAnnotations"); return annotations; } } return s_noAnnotations; } internal abstract GreenNode SetAnnotations(SyntaxAnnotation[]? annotations); #endregion #region Diagnostics internal DiagnosticInfo[] GetDiagnostics() { if (this.ContainsDiagnostics) { DiagnosticInfo[]? diags; if (s_diagnosticsTable.TryGetValue(this, out diags)) { return diags; } } return s_noDiagnostics; } internal abstract GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics); #endregion #region Text public virtual string ToFullString() { var sb = PooledStringBuilder.GetInstance(); var writer = new System.IO.StringWriter(sb.Builder, System.Globalization.CultureInfo.InvariantCulture); this.WriteTo(writer, leading: true, trailing: true); return sb.ToStringAndFree(); } public override string ToString() { var sb = PooledStringBuilder.GetInstance(); var writer = new System.IO.StringWriter(sb.Builder, System.Globalization.CultureInfo.InvariantCulture); this.WriteTo(writer, leading: false, trailing: false); return sb.ToStringAndFree(); } public void WriteTo(System.IO.TextWriter writer) { this.WriteTo(writer, leading: true, trailing: true); } protected internal void WriteTo(TextWriter writer, bool leading, bool trailing) { // Use an actual stack so we can write out deeply recursive structures without overflowing. var stack = ArrayBuilder<(GreenNode node, bool leading, bool trailing)>.GetInstance(); stack.Push((this, leading, trailing)); // Separated out stack processing logic so that it does not unintentionally refer to // "this", "leading" or "trailing". processStack(writer, stack); stack.Free(); return; static void processStack( TextWriter writer, ArrayBuilder<(GreenNode node, bool leading, bool trailing)> stack) { while (stack.Count > 0) { var current = stack.Pop(); var currentNode = current.node; var currentLeading = current.leading; var currentTrailing = current.trailing; if (currentNode.IsToken) { currentNode.WriteTokenTo(writer, currentLeading, currentTrailing); continue; } if (currentNode.IsTrivia) { currentNode.WriteTriviaTo(writer); continue; } var firstIndex = GetFirstNonNullChildIndex(currentNode); var lastIndex = GetLastNonNullChildIndex(currentNode); for (var i = lastIndex; i >= firstIndex; i--) { var child = currentNode.GetSlot(i); if (child != null) { var first = i == firstIndex; var last = i == lastIndex; stack.Push((child, currentLeading | !first, currentTrailing | !last)); } } } } } private static int GetFirstNonNullChildIndex(GreenNode node) { int n = node.SlotCount; int firstIndex = 0; for (; firstIndex < n; firstIndex++) { var child = node.GetSlot(firstIndex); if (child != null) { break; } } return firstIndex; } private static int GetLastNonNullChildIndex(GreenNode node) { int n = node.SlotCount; int lastIndex = n - 1; for (; lastIndex >= 0; lastIndex--) { var child = node.GetSlot(lastIndex); if (child != null) { break; } } return lastIndex; } protected virtual void WriteTriviaTo(TextWriter writer) { throw new NotImplementedException(); } protected virtual void WriteTokenTo(TextWriter writer, bool leading, bool trailing) { throw new NotImplementedException(); } #endregion #region Tokens public virtual int RawContextualKind { get { return this.RawKind; } } public virtual object? GetValue() { return null; } public virtual string GetValueText() { return string.Empty; } public virtual GreenNode? GetLeadingTriviaCore() { return null; } public virtual GreenNode? GetTrailingTriviaCore() { return null; } public virtual GreenNode WithLeadingTrivia(GreenNode? trivia) { return this; } public virtual GreenNode WithTrailingTrivia(GreenNode? trivia) { return this; } internal GreenNode? GetFirstTerminal() { GreenNode? node = this; do { GreenNode? firstChild = null; for (int i = 0, n = node.SlotCount; i < n; i++) { var child = node.GetSlot(i); if (child != null) { firstChild = child; break; } } node = firstChild; } while (node?._slotCount > 0); return node; } internal GreenNode? GetLastTerminal() { GreenNode? node = this; do { GreenNode? lastChild = null; for (int i = node.SlotCount - 1; i >= 0; i--) { var child = node.GetSlot(i); if (child != null) { lastChild = child; break; } } node = lastChild; } while (node?._slotCount > 0); return node; } internal GreenNode? GetLastNonmissingTerminal() { GreenNode? node = this; do { GreenNode? nonmissingChild = null; for (int i = node.SlotCount - 1; i >= 0; i--) { var child = node.GetSlot(i); if (child != null && !child.IsMissing) { nonmissingChild = child; break; } } node = nonmissingChild; } while (node?._slotCount > 0); return node; } #endregion #region Equivalence public virtual bool IsEquivalentTo([NotNullWhen(true)] GreenNode? other) { if (this == other) { return true; } if (other == null) { return false; } return EquivalentToInternal(this, other); } private static bool EquivalentToInternal(GreenNode node1, GreenNode node2) { if (node1.RawKind != node2.RawKind) { // A single-element list is usually represented as just a single node, // but can be represented as a List node with one child. Move to that // child if necessary. if (node1.IsList && node1.SlotCount == 1) { node1 = node1.GetRequiredSlot(0); } if (node2.IsList && node2.SlotCount == 1) { node2 = node2.GetRequiredSlot(0); } if (node1.RawKind != node2.RawKind) { return false; } } if (node1._fullWidth != node2._fullWidth) { return false; } var n = node1.SlotCount; if (n != node2.SlotCount) { return false; } for (int i = 0; i < n; i++) { var node1Child = node1.GetSlot(i); var node2Child = node2.GetSlot(i); if (node1Child != null && node2Child != null && !node1Child.IsEquivalentTo(node2Child)) { return false; } } return true; } #endregion public abstract SyntaxNode GetStructure(SyntaxTrivia parentTrivia); #region Factories public abstract SyntaxToken CreateSeparator<TNode>(SyntaxNode element) where TNode : SyntaxNode; public abstract bool IsTriviaWithEndOfLine(); // trivia node has end of line /* * There are 3 overloads of this, because most callers already know what they have is a List<T> and only transform it. * In those cases List<TFrom> performs much better. * In other cases, the type is unknown / is IEnumerable<T>, where we try to find the best match. * There is another overload for IReadOnlyList, since most collections already implement this, so checking for it will * perform better then copying to a List<T>, though not as good as List<T> directly. */ public static GreenNode? CreateList<TFrom>(IEnumerable<TFrom>? enumerable, Func<TFrom, GreenNode> select) => enumerable switch { null => null, List<TFrom> l => CreateList(l, select), IReadOnlyList<TFrom> l => CreateList(l, select), _ => CreateList(enumerable.ToList(), select) }; public static GreenNode? CreateList<TFrom>(List<TFrom> list, Func<TFrom, GreenNode> select) { switch (list.Count) { case 0: return null; case 1: return select(list[0]); case 2: return SyntaxList.List(select(list[0]), select(list[1])); case 3: return SyntaxList.List(select(list[0]), select(list[1]), select(list[2])); default: { var array = new ArrayElement<GreenNode>[list.Count]; for (int i = 0; i < array.Length; i++) array[i].Value = select(list[i]); return SyntaxList.List(array); } } } public static GreenNode? CreateList<TFrom>(IReadOnlyList<TFrom> list, Func<TFrom, GreenNode> select) { switch (list.Count) { case 0: return null; case 1: return select(list[0]); case 2: return SyntaxList.List(select(list[0]), select(list[1])); case 3: return SyntaxList.List(select(list[0]), select(list[1]), select(list[2])); default: { var array = new ArrayElement<GreenNode>[list.Count]; for (int i = 0; i < array.Length; i++) array[i].Value = select(list[i]); return SyntaxList.List(array); } } } public SyntaxNode CreateRed() { return CreateRed(null, 0); } internal abstract SyntaxNode CreateRed(SyntaxNode? parent, int position); #endregion #region Caching internal const int MaxCachedChildNum = 3; internal bool IsCacheable { get { return ((this.flags & NodeFlags.InheritMask) == NodeFlags.IsNotMissing) && this.SlotCount <= GreenNode.MaxCachedChildNum; } } internal int GetCacheHash() { Debug.Assert(this.IsCacheable); int code = (int)(this.flags) ^ this.RawKind; int cnt = this.SlotCount; for (int i = 0; i < cnt; i++) { var child = GetSlot(i); if (child != null) { code = Hash.Combine(RuntimeHelpers.GetHashCode(child), code); } } return code & Int32.MaxValue; } internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1) { Debug.Assert(this.IsCacheable); return this.RawKind == kind && this.flags == flags && this.GetSlot(0) == child1; } internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1, GreenNode? child2) { Debug.Assert(this.IsCacheable); return this.RawKind == kind && this.flags == flags && this.GetSlot(0) == child1 && this.GetSlot(1) == child2; } internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1, GreenNode? child2, GreenNode? child3) { Debug.Assert(this.IsCacheable); return this.RawKind == kind && this.flags == flags && this.GetSlot(0) == child1 && this.GetSlot(1) == child2 && this.GetSlot(2) == child3; } #endregion //Caching /// <summary> /// Add an error to the given node, creating a new node that is the same except it has no parent, /// and has the given error attached to it. The error span is the entire span of this node. /// </summary> /// <param name="err">The error to attach to this node</param> /// <returns>A new node, with no parent, that has this error added to it.</returns> /// <remarks>Since nodes are immutable, the only way to create nodes with errors attached is to create a node without an error, /// then add an error with this method to create another node.</remarks> internal GreenNode AddError(DiagnosticInfo err) { DiagnosticInfo[] errorInfos; // If the green node already has errors, add those on. if (GetDiagnostics() == null) { errorInfos = new[] { err }; } else { // Add the error to the error list. errorInfos = GetDiagnostics(); var length = errorInfos.Length; Array.Resize(ref errorInfos, length + 1); errorInfos[length] = err; } // Get a new green node with the errors added on. return SetDiagnostics(errorInfos); } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Features/Core/Portable/Completion/ArgumentContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Provides context information for argument completion. /// </summary> internal sealed class ArgumentContext { public ArgumentContext( ArgumentProvider provider, SemanticModel semanticModel, int position, IParameterSymbol parameter, string? previousValue, CancellationToken cancellationToken) { Provider = provider ?? throw new ArgumentNullException(nameof(provider)); SemanticModel = semanticModel ?? throw new ArgumentNullException(nameof(semanticModel)); Position = position; Parameter = parameter ?? throw new ArgumentNullException(nameof(parameter)); PreviousValue = previousValue; CancellationToken = cancellationToken; } internal ArgumentProvider Provider { get; } /// <summary> /// Gets the semantic model where argument completion is requested. /// </summary> public SemanticModel SemanticModel { get; } /// <summary> /// Gets the position within <see cref="SemanticModel"/> where argument completion is requested. /// </summary> public int Position { get; } /// <summary> /// Gets the symbol for the parameter for which an argument value is requested. /// </summary> public IParameterSymbol Parameter { get; } /// <summary> /// Gets the previously-provided argument value for this parameter. /// </summary> /// <value> /// The existing text of the argument value, if the argument is already in code; otherwise, /// <see langword="null"/> when requesting a new argument value. /// </value> public string? PreviousValue { get; } /// <summary> /// Gets a cancellation token that argument providers may observe. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Gets or sets the default argument value. /// </summary> /// <remarks> /// If this value is not set, the argument completion session will insert a language-specific default value for /// the argument. /// </remarks> public string? DefaultValue { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Provides context information for argument completion. /// </summary> internal sealed class ArgumentContext { public ArgumentContext( ArgumentProvider provider, SemanticModel semanticModel, int position, IParameterSymbol parameter, string? previousValue, CancellationToken cancellationToken) { Provider = provider ?? throw new ArgumentNullException(nameof(provider)); SemanticModel = semanticModel ?? throw new ArgumentNullException(nameof(semanticModel)); Position = position; Parameter = parameter ?? throw new ArgumentNullException(nameof(parameter)); PreviousValue = previousValue; CancellationToken = cancellationToken; } internal ArgumentProvider Provider { get; } /// <summary> /// Gets the semantic model where argument completion is requested. /// </summary> public SemanticModel SemanticModel { get; } /// <summary> /// Gets the position within <see cref="SemanticModel"/> where argument completion is requested. /// </summary> public int Position { get; } /// <summary> /// Gets the symbol for the parameter for which an argument value is requested. /// </summary> public IParameterSymbol Parameter { get; } /// <summary> /// Gets the previously-provided argument value for this parameter. /// </summary> /// <value> /// The existing text of the argument value, if the argument is already in code; otherwise, /// <see langword="null"/> when requesting a new argument value. /// </value> public string? PreviousValue { get; } /// <summary> /// Gets a cancellation token that argument providers may observe. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Gets or sets the default argument value. /// </summary> /// <remarks> /// If this value is not set, the argument completion session will insert a language-specific default value for /// the argument. /// </remarks> public string? DefaultValue { get; set; } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Features/Core/Portable/RQName/Nodes/RQTypeVariableType.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 RQTypeVariableType : RQType { public readonly string Name; public RQTypeVariableType(string name) => Name = name; public override SimpleTreeNode ToSimpleTree() => new SimpleGroupNode(RQNameStrings.TyVar, 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 Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQTypeVariableType : RQType { public readonly string Name; public RQTypeVariableType(string name) => Name = name; public override SimpleTreeNode ToSimpleTree() => new SimpleGroupNode(RQNameStrings.TyVar, Name); } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/EditorFeatures/Core/Tagging/TaggerDelay.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.Tagging { /// <summary> /// How quickly the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> should update tags after /// receiving an <see cref="ITaggerEventSource.Changed"/> notification. /// </summary> internal enum TaggerDelay { /// <summary> /// Indicates that the tagger should retag after a short, but imperceptible delay. This is /// for features that want to appear instantaneous to the user, but which can wait a short /// while until a batch of changes has occurred before processing. Specifically, if a user /// expects the tag immediately after typing a character or moving the caret, then this /// delay should be used. /// </summary> NearImmediate, /// <summary> /// Not as fast as NearImmediate. A user typing quickly or navigating quickly should not /// trigger this. However, any sort of pause will cause it to trigger /// </summary> Short, /// <summary> /// Not as fast as 'Short'. The user's pause should be more significant until the tag /// appears. /// </summary> Medium, /// <summary> /// Indicates that the tagger should run when the user appears to be /// idle. /// </summary> OnIdle } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.Tagging { /// <summary> /// How quickly the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> should update tags after /// receiving an <see cref="ITaggerEventSource.Changed"/> notification. /// </summary> internal enum TaggerDelay { /// <summary> /// Indicates that the tagger should retag after a short, but imperceptible delay. This is /// for features that want to appear instantaneous to the user, but which can wait a short /// while until a batch of changes has occurred before processing. Specifically, if a user /// expects the tag immediately after typing a character or moving the caret, then this /// delay should be used. /// </summary> NearImmediate, /// <summary> /// Not as fast as NearImmediate. A user typing quickly or navigating quickly should not /// trigger this. However, any sort of pause will cause it to trigger /// </summary> Short, /// <summary> /// Not as fast as 'Short'. The user's pause should be more significant until the tag /// appears. /// </summary> Medium, /// <summary> /// Indicates that the tagger should run when the user appears to be /// idle. /// </summary> OnIdle } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Tools/ExternalAccess/Apex/IApexAsynchronousOperationListenerProviderAccessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.ExternalAccess.Apex { internal interface IApexAsynchronousOperationListenerProviderAccessor { Task WaitAllAsync(string[] featureNames = null, Action eventProcessingAction = null, TimeSpan? timeout = 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.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.Apex { internal interface IApexAsynchronousOperationListenerProviderAccessor { Task WaitAllAsync(string[] featureNames = null, Action eventProcessingAction = null, TimeSpan? timeout = null); } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Workspaces/CoreTest/Differencing/MatchTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Differencing.UnitTests { public class MatchTests { [Fact] public void KnownMatches() { TestNode x1, x2; var oldRoot = new TestNode(0, 1, x1 = new TestNode(1, 1)); var newRoot = new TestNode(0, 1, x2 = new TestNode(1, 2)); var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(x1, x2) }); Assert.True(m.TryGetNewNode(x1, out var n)); Assert.Equal(n, x2); Assert.Throws<ArgumentException>(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x1) })); Assert.Throws<ArgumentException>(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(x1, new TestNode(0, 0)) })); } [Fact] public void KnownMatchesDups() { TestNode x1, x2, y1, y2; var oldRoot = new TestNode(0, 1, x1 = new TestNode(1, 1), y1 = new TestNode(1, 4)); var newRoot = new TestNode(0, 1, x2 = new TestNode(1, 2), y2 = new TestNode(1, 3)); var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(y1, x2), }); // the first one wins: Assert.True(m.TryGetNewNode(x1, out var n)); Assert.Equal(x2, n); Assert.True(m.TryGetOldNode(x2, out n)); Assert.Equal(x1, n); Assert.True(m.TryGetNewNode(y1, out n)); // matched Assert.Equal(y2, n); } [Fact] public void KnownMatchesRootMatch() { TestNode x1, x2; var oldRoot = new TestNode(0, 1, x1 = new TestNode(0, 1)); var newRoot = new TestNode(0, 1, x2 = new TestNode(0, 2)); var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, newRoot), }); // the root wins: Assert.True(m.TryGetNewNode(x1, out var n)); // matched Assert.Equal(x2, n); Assert.True(m.TryGetOldNode(newRoot, out n)); Assert.Equal(oldRoot, n); Assert.True(m.TryGetNewNode(oldRoot, out n)); Assert.Equal(newRoot, 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; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Differencing.UnitTests { public class MatchTests { [Fact] public void KnownMatches() { TestNode x1, x2; var oldRoot = new TestNode(0, 1, x1 = new TestNode(1, 1)); var newRoot = new TestNode(0, 1, x2 = new TestNode(1, 2)); var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(x1, x2) }); Assert.True(m.TryGetNewNode(x1, out var n)); Assert.Equal(n, x2); Assert.Throws<ArgumentException>(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x1) })); Assert.Throws<ArgumentException>(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(x1, new TestNode(0, 0)) })); } [Fact] public void KnownMatchesDups() { TestNode x1, x2, y1, y2; var oldRoot = new TestNode(0, 1, x1 = new TestNode(1, 1), y1 = new TestNode(1, 4)); var newRoot = new TestNode(0, 1, x2 = new TestNode(1, 2), y2 = new TestNode(1, 3)); var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(y1, x2), }); // the first one wins: Assert.True(m.TryGetNewNode(x1, out var n)); Assert.Equal(x2, n); Assert.True(m.TryGetOldNode(x2, out n)); Assert.Equal(x1, n); Assert.True(m.TryGetNewNode(y1, out n)); // matched Assert.Equal(y2, n); } [Fact] public void KnownMatchesRootMatch() { TestNode x1, x2; var oldRoot = new TestNode(0, 1, x1 = new TestNode(0, 1)); var newRoot = new TestNode(0, 1, x2 = new TestNode(0, 2)); var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, newRoot), }); // the root wins: Assert.True(m.TryGetNewNode(x1, out var n)); // matched Assert.Equal(x2, n); Assert.True(m.TryGetOldNode(newRoot, out n)); Assert.Equal(oldRoot, n); Assert.True(m.TryGetNewNode(oldRoot, out n)); Assert.Equal(newRoot, n); } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSyntaxNodeOrToken.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal struct EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> { public readonly TSyntaxNode? Node; public readonly EmbeddedSyntaxToken<TSyntaxKind> Token; private EmbeddedSyntaxNodeOrToken(TSyntaxNode node) : this() { RoslynDebug.AssertNotNull(node); Node = node; } private EmbeddedSyntaxNodeOrToken(EmbeddedSyntaxToken<TSyntaxKind> token) : this() { Debug.Assert((int)(object)token.Kind != 0); Token = token; } [MemberNotNullWhen(true, nameof(Node))] public bool IsNode => Node != null; public static implicit operator EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode>(TSyntaxNode node) => new(node); public static implicit operator EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode>(EmbeddedSyntaxToken<TSyntaxKind> token) => new(token); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal struct EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> { public readonly TSyntaxNode? Node; public readonly EmbeddedSyntaxToken<TSyntaxKind> Token; private EmbeddedSyntaxNodeOrToken(TSyntaxNode node) : this() { RoslynDebug.AssertNotNull(node); Node = node; } private EmbeddedSyntaxNodeOrToken(EmbeddedSyntaxToken<TSyntaxKind> token) : this() { Debug.Assert((int)(object)token.Kind != 0); Token = token; } [MemberNotNullWhen(true, nameof(Node))] public bool IsNode => Node != null; public static implicit operator EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode>(TSyntaxNode node) => new(node); public static implicit operator EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode>(EmbeddedSyntaxToken<TSyntaxKind> token) => new(token); } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Features/LanguageServer/Protocol/Handler/RequestContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.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.Handler { /// <summary> /// Context for requests handled by <see cref="IRequestHandler"/> /// </summary> internal readonly struct RequestContext { public static RequestContext Create( bool requiresLSPSolution, TextDocumentIdentifier? textDocument, string? clientName, ILspLogger _logger, RequestTelemetryLogger telemetryLogger, ClientCapabilities clientCapabilities, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, Dictionary<Workspace, (Solution workspaceSolution, Solution lspSolution)>? solutionCache, IDocumentChangeTracker? documentChangeTracker, out Workspace workspace) { // Go through each registered workspace, find the solution that contains the document that // this request is for, and then updates it based on the state of the world as we know it, based on the // text content in the document change tracker. // Assume the first workspace registered is the main one var workspaceSolution = lspWorkspaceRegistrationService.GetAllRegistrations().First().CurrentSolution; Document? document = null; // If we were given a document, find it in whichever workspace it exists in if (textDocument is null) { _logger.TraceInformation("Request contained no text document identifier"); } else { // There are multiple possible solutions that we could be interested in, so we need to find the document // first and then get the solution from there. If we're not given a document, this will return the default // solution document = FindDocument(_logger, telemetryLogger, lspWorkspaceRegistrationService, textDocument, clientName); if (document is not null) { // Where ever the document came from, thats the "main" solution for this request workspaceSolution = document.Project.Solution; } } documentChangeTracker ??= new NoOpDocumentChangeTracker(); // If the handler doesn't need an LSP solution we do two important things: // 1. We don't bother building the LSP solution for perf reasons // 2. We explicitly don't give the handler a solution or document, even if we could // so they're not accidentally operating on stale solution state. if (!requiresLSPSolution) { workspace = workspaceSolution.Workspace; return new RequestContext(solution: null, _logger.TraceInformation, clientCapabilities, clientName, document: null, documentChangeTracker); } var lspSolution = BuildLSPSolution(solutionCache, workspaceSolution, documentChangeTracker); // If we got a document back, we need pull it out of our updated solution so the handler is operating on the // latest document text. if (document != null) { document = lspSolution.GetRequiredDocument(document.Id); } workspace = lspSolution.Workspace; return new RequestContext(lspSolution, _logger.TraceInformation, clientCapabilities, clientName, document, documentChangeTracker); } private static Document? FindDocument( ILspLogger logger, RequestTelemetryLogger telemetryLogger, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, TextDocumentIdentifier textDocument, string? clientName) { logger.TraceInformation($"Finding document corresponding to {textDocument.Uri}"); using var workspaceKinds = TemporaryArray<string?>.Empty; foreach (var workspace in lspWorkspaceRegistrationService.GetAllRegistrations()) { workspaceKinds.Add(workspace.Kind); var documents = workspace.CurrentSolution.GetDocuments(textDocument.Uri, clientName, logger); if (!documents.IsEmpty) { var document = documents.FindDocumentInProjectContext(textDocument); logger.TraceInformation($"Found document in workspace {workspace.Kind}: {document.FilePath}"); telemetryLogger.UpdateFindDocumentTelemetryData(success: true, workspace.Kind); return document; } } var searchedWorkspaceKinds = string.Join(";", workspaceKinds.ToImmutableAndClear()); logger.TraceWarning($"No document found for '{textDocument.Uri}' after looking in {searchedWorkspaceKinds} workspaces, with client name '{clientName}'."); telemetryLogger.UpdateFindDocumentTelemetryData(success: false, workspaceKind: null); return null; } /// <summary> /// Gets the "LSP view of the world", either by forking the workspace solution and updating the documents we track /// or by simply returning our cached solution if it is still valid. /// </summary> private static Solution BuildLSPSolution(Dictionary<Workspace, (Solution workspaceSolution, Solution lspSolution)>? solutionCache, Solution workspaceSolution, IDocumentChangeTracker documentChangeTracker) { var workspace = workspaceSolution.Workspace; // If we have a cached solution we can use it, unless the workspace solution it was based on // is not the current one. if (solutionCache is null || !solutionCache.TryGetValue(workspace, out var cacheInfo) || workspaceSolution != cacheInfo.workspaceSolution) { var lspSolution = GetSolutionWithReplacedDocuments(workspaceSolution, documentChangeTracker); if (solutionCache is not null) { solutionCache[workspace] = (workspaceSolution, lspSolution); } return lspSolution; } return cacheInfo.lspSolution; } /// <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, IDocumentChangeTracker documentChangeTracker) { foreach (var (uri, text) in documentChangeTracker.GetTrackedDocuments()) { var documentIds = solution.GetDocumentIds(uri); // We are tracking documents from multiple solutions, so this might not be one we care about if (!documentIds.IsEmpty) { solution = solution.WithDocumentText(documentIds, text); } } return solution; } /// <summary> /// This will be null for non-mutating requests because they're not allowed to change documents /// </summary> private readonly IDocumentChangeTracker _documentChangeTracker; /// <summary> /// The solution state that the request should operate on, if the handler requires an LSP solution, or <see langword="null"/> otherwise /// </summary> public readonly Solution? Solution; /// <summary> /// The client capabilities for the request. /// </summary> public readonly ClientCapabilities ClientCapabilities; /// <summary> /// The LSP client making the request /// </summary> public readonly string? ClientName; /// <summary> /// The document that the request is for, if applicable. This comes from the <see cref="TextDocumentIdentifier"/> returned from the handler itself via a call to <see cref="IRequestHandler{RequestType, ResponseType}.GetTextDocumentIdentifier(RequestType)"/>. /// </summary> public readonly Document? Document; /// <summary> /// Tracing object that can be used to log information about the status of requests. /// </summary> private readonly Action<string> _traceInformation; public RequestContext( Solution? solution, Action<string> traceInformation, ClientCapabilities clientCapabilities, string? clientName, Document? document, IDocumentChangeTracker documentChangeTracker) { Document = document; Solution = solution; ClientCapabilities = clientCapabilities; ClientName = clientName; _documentChangeTracker = documentChangeTracker; _traceInformation = traceInformation; } /// <summary> /// Allows a mutating request to open a document and start it being tracked. /// </summary> public void StartTracking(Uri documentUri, SourceText initialText) => _documentChangeTracker.StartTracking(documentUri, initialText); /// <summary> /// Allows a mutating request to update the contents of a tracked document. /// </summary> public void UpdateTrackedDocument(Uri documentUri, SourceText changedText) => _documentChangeTracker.UpdateTrackedDocument(documentUri, changedText); public SourceText GetTrackedDocumentSourceText(Uri documentUri) => _documentChangeTracker.GetTrackedDocumentSourceText(documentUri); /// <summary> /// Allows a mutating request to close a document and stop it being tracked. /// </summary> public void StopTracking(Uri documentUri) => _documentChangeTracker.StopTracking(documentUri); public bool IsTracking(Uri documentUri) => _documentChangeTracker.IsTracking(documentUri); /// <summary> /// Logs an informational message. /// </summary> public void TraceInformation(string message) => _traceInformation(message); private class NoOpDocumentChangeTracker : IDocumentChangeTracker { public IEnumerable<(Uri DocumentUri, SourceText Text)> GetTrackedDocuments() => Enumerable.Empty<(Uri DocumentUri, SourceText Text)>(); public SourceText GetTrackedDocumentSourceText(Uri documentUri) => null!; public bool IsTracking(Uri documentUri) => false; public void StartTracking(Uri documentUri, SourceText initialText) { } public void StopTracking(Uri documentUri) { } public void UpdateTrackedDocument(Uri documentUri, SourceText text) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; 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.Handler { /// <summary> /// Context for requests handled by <see cref="IRequestHandler"/> /// </summary> internal readonly struct RequestContext { public static RequestContext Create( bool requiresLSPSolution, TextDocumentIdentifier? textDocument, string? clientName, ILspLogger _logger, RequestTelemetryLogger telemetryLogger, ClientCapabilities clientCapabilities, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, Dictionary<Workspace, (Solution workspaceSolution, Solution lspSolution)>? solutionCache, IDocumentChangeTracker? documentChangeTracker, out Workspace workspace) { // Go through each registered workspace, find the solution that contains the document that // this request is for, and then updates it based on the state of the world as we know it, based on the // text content in the document change tracker. // Assume the first workspace registered is the main one var workspaceSolution = lspWorkspaceRegistrationService.GetAllRegistrations().First().CurrentSolution; Document? document = null; // If we were given a document, find it in whichever workspace it exists in if (textDocument is null) { _logger.TraceInformation("Request contained no text document identifier"); } else { // There are multiple possible solutions that we could be interested in, so we need to find the document // first and then get the solution from there. If we're not given a document, this will return the default // solution document = FindDocument(_logger, telemetryLogger, lspWorkspaceRegistrationService, textDocument, clientName); if (document is not null) { // Where ever the document came from, thats the "main" solution for this request workspaceSolution = document.Project.Solution; } } documentChangeTracker ??= new NoOpDocumentChangeTracker(); // If the handler doesn't need an LSP solution we do two important things: // 1. We don't bother building the LSP solution for perf reasons // 2. We explicitly don't give the handler a solution or document, even if we could // so they're not accidentally operating on stale solution state. if (!requiresLSPSolution) { workspace = workspaceSolution.Workspace; return new RequestContext(solution: null, _logger.TraceInformation, clientCapabilities, clientName, document: null, documentChangeTracker); } var lspSolution = BuildLSPSolution(solutionCache, workspaceSolution, documentChangeTracker); // If we got a document back, we need pull it out of our updated solution so the handler is operating on the // latest document text. if (document != null) { document = lspSolution.GetRequiredDocument(document.Id); } workspace = lspSolution.Workspace; return new RequestContext(lspSolution, _logger.TraceInformation, clientCapabilities, clientName, document, documentChangeTracker); } private static Document? FindDocument( ILspLogger logger, RequestTelemetryLogger telemetryLogger, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, TextDocumentIdentifier textDocument, string? clientName) { logger.TraceInformation($"Finding document corresponding to {textDocument.Uri}"); using var workspaceKinds = TemporaryArray<string?>.Empty; foreach (var workspace in lspWorkspaceRegistrationService.GetAllRegistrations()) { workspaceKinds.Add(workspace.Kind); var documents = workspace.CurrentSolution.GetDocuments(textDocument.Uri, clientName, logger); if (!documents.IsEmpty) { var document = documents.FindDocumentInProjectContext(textDocument); logger.TraceInformation($"Found document in workspace {workspace.Kind}: {document.FilePath}"); telemetryLogger.UpdateFindDocumentTelemetryData(success: true, workspace.Kind); return document; } } var searchedWorkspaceKinds = string.Join(";", workspaceKinds.ToImmutableAndClear()); logger.TraceWarning($"No document found for '{textDocument.Uri}' after looking in {searchedWorkspaceKinds} workspaces, with client name '{clientName}'."); telemetryLogger.UpdateFindDocumentTelemetryData(success: false, workspaceKind: null); return null; } /// <summary> /// Gets the "LSP view of the world", either by forking the workspace solution and updating the documents we track /// or by simply returning our cached solution if it is still valid. /// </summary> private static Solution BuildLSPSolution(Dictionary<Workspace, (Solution workspaceSolution, Solution lspSolution)>? solutionCache, Solution workspaceSolution, IDocumentChangeTracker documentChangeTracker) { var workspace = workspaceSolution.Workspace; // If we have a cached solution we can use it, unless the workspace solution it was based on // is not the current one. if (solutionCache is null || !solutionCache.TryGetValue(workspace, out var cacheInfo) || workspaceSolution != cacheInfo.workspaceSolution) { var lspSolution = GetSolutionWithReplacedDocuments(workspaceSolution, documentChangeTracker); if (solutionCache is not null) { solutionCache[workspace] = (workspaceSolution, lspSolution); } return lspSolution; } return cacheInfo.lspSolution; } /// <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, IDocumentChangeTracker documentChangeTracker) { foreach (var (uri, text) in documentChangeTracker.GetTrackedDocuments()) { var documentIds = solution.GetDocumentIds(uri); // We are tracking documents from multiple solutions, so this might not be one we care about if (!documentIds.IsEmpty) { solution = solution.WithDocumentText(documentIds, text); } } return solution; } /// <summary> /// This will be null for non-mutating requests because they're not allowed to change documents /// </summary> private readonly IDocumentChangeTracker _documentChangeTracker; /// <summary> /// The solution state that the request should operate on, if the handler requires an LSP solution, or <see langword="null"/> otherwise /// </summary> public readonly Solution? Solution; /// <summary> /// The client capabilities for the request. /// </summary> public readonly ClientCapabilities ClientCapabilities; /// <summary> /// The LSP client making the request /// </summary> public readonly string? ClientName; /// <summary> /// The document that the request is for, if applicable. This comes from the <see cref="TextDocumentIdentifier"/> returned from the handler itself via a call to <see cref="IRequestHandler{RequestType, ResponseType}.GetTextDocumentIdentifier(RequestType)"/>. /// </summary> public readonly Document? Document; /// <summary> /// Tracing object that can be used to log information about the status of requests. /// </summary> private readonly Action<string> _traceInformation; public RequestContext( Solution? solution, Action<string> traceInformation, ClientCapabilities clientCapabilities, string? clientName, Document? document, IDocumentChangeTracker documentChangeTracker) { Document = document; Solution = solution; ClientCapabilities = clientCapabilities; ClientName = clientName; _documentChangeTracker = documentChangeTracker; _traceInformation = traceInformation; } /// <summary> /// Allows a mutating request to open a document and start it being tracked. /// </summary> public void StartTracking(Uri documentUri, SourceText initialText) => _documentChangeTracker.StartTracking(documentUri, initialText); /// <summary> /// Allows a mutating request to update the contents of a tracked document. /// </summary> public void UpdateTrackedDocument(Uri documentUri, SourceText changedText) => _documentChangeTracker.UpdateTrackedDocument(documentUri, changedText); public SourceText GetTrackedDocumentSourceText(Uri documentUri) => _documentChangeTracker.GetTrackedDocumentSourceText(documentUri); /// <summary> /// Allows a mutating request to close a document and stop it being tracked. /// </summary> public void StopTracking(Uri documentUri) => _documentChangeTracker.StopTracking(documentUri); public bool IsTracking(Uri documentUri) => _documentChangeTracker.IsTracking(documentUri); /// <summary> /// Logs an informational message. /// </summary> public void TraceInformation(string message) => _traceInformation(message); private class NoOpDocumentChangeTracker : IDocumentChangeTracker { public IEnumerable<(Uri DocumentUri, SourceText Text)> GetTrackedDocuments() => Enumerable.Empty<(Uri DocumentUri, SourceText Text)>(); public SourceText GetTrackedDocumentSourceText(Uri documentUri) => null!; public bool IsTracking(Uri documentUri) => false; public void StartTracking(Uri documentUri, SourceText initialText) { } public void StopTracking(Uri documentUri) { } public void UpdateTrackedDocument(Uri documentUri, SourceText text) { } } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/FormattingResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { /// <summary> /// this holds onto changes made by formatting engine. /// </summary> internal class FormattingResult : AbstractFormattingResult { internal FormattingResult(TreeData treeInfo, TokenStream tokenStream, TextSpan spanToFormat) : base(treeInfo, tokenStream, spanToFormat) { } protected override SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> changeMap, CancellationToken cancellationToken) { var rewriter = new TriviaRewriter(this.TreeInfo.Root, SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), this.FormattedSpan), changeMap, cancellationToken); return rewriter.Transform(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { /// <summary> /// this holds onto changes made by formatting engine. /// </summary> internal class FormattingResult : AbstractFormattingResult { internal FormattingResult(TreeData treeInfo, TokenStream tokenStream, TextSpan spanToFormat) : base(treeInfo, tokenStream, spanToFormat) { } protected override SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> changeMap, CancellationToken cancellationToken) { var rewriter = new TriviaRewriter(this.TreeInfo.Root, SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), this.FormattedSpan), changeMap, cancellationToken); return rewriter.Transform(); } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Compilers/Core/Portable/Syntax/SyntaxListBuilder`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Syntax { internal struct SyntaxListBuilder<TNode> where TNode : SyntaxNode { private readonly SyntaxListBuilder? _builder; public SyntaxListBuilder(int size) : this(new SyntaxListBuilder(size)) { } public static SyntaxListBuilder<TNode> Create() { return new SyntaxListBuilder<TNode>(8); } internal SyntaxListBuilder(SyntaxListBuilder? builder) { _builder = builder; } public bool IsNull { get { return _builder == null; } } public int Count { get { return _builder!.Count; } } public void Clear() { _builder!.Clear(); } public SyntaxListBuilder<TNode> Add(TNode node) { _builder!.Add(node); return this; } public void AddRange(TNode[] items, int offset, int length) { _builder!.AddRange(items, offset, length); } public void AddRange(SyntaxList<TNode> nodes) { _builder!.AddRange(nodes); } public void AddRange(SyntaxList<TNode> nodes, int offset, int length) { _builder!.AddRange(nodes, offset, length); } public bool Any(int kind) { return _builder!.Any(kind); } public SyntaxList<TNode> ToList() { return _builder.ToList(); } public static implicit operator SyntaxListBuilder?(SyntaxListBuilder<TNode> builder) { return builder._builder; } public static implicit operator SyntaxList<TNode>(SyntaxListBuilder<TNode> builder) { if (builder._builder != null) { return builder.ToList(); } return default; } } }
// Licensed to the .NET Foundation under one or more 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.Syntax { internal struct SyntaxListBuilder<TNode> where TNode : SyntaxNode { private readonly SyntaxListBuilder? _builder; public SyntaxListBuilder(int size) : this(new SyntaxListBuilder(size)) { } public static SyntaxListBuilder<TNode> Create() { return new SyntaxListBuilder<TNode>(8); } internal SyntaxListBuilder(SyntaxListBuilder? builder) { _builder = builder; } public bool IsNull { get { return _builder == null; } } public int Count { get { return _builder!.Count; } } public void Clear() { _builder!.Clear(); } public SyntaxListBuilder<TNode> Add(TNode node) { _builder!.Add(node); return this; } public void AddRange(TNode[] items, int offset, int length) { _builder!.AddRange(items, offset, length); } public void AddRange(SyntaxList<TNode> nodes) { _builder!.AddRange(nodes); } public void AddRange(SyntaxList<TNode> nodes, int offset, int length) { _builder!.AddRange(nodes, offset, length); } public bool Any(int kind) { return _builder!.Any(kind); } public SyntaxList<TNode> ToList() { return _builder.ToList(); } public static implicit operator SyntaxListBuilder?(SyntaxListBuilder<TNode> builder) { return builder._builder; } public static implicit operator SyntaxList<TNode>(SyntaxListBuilder<TNode> builder) { if (builder._builder != null) { return builder.ToList(); } return default; } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Compilers/Test/Core/Platform/CoreClr/SharedConsoleOutWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NETCOREAPP using System; using System.IO; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.CoreClr { internal static class SharedConsole { private static TextWriter s_savedConsoleOut; private static TextWriter s_savedConsoleError; private static AsyncLocal<StringWriter> s_currentOut; private static AsyncLocal<StringWriter> s_currentError; internal static void OverrideConsole() { s_savedConsoleOut = Console.Out; s_savedConsoleError = Console.Error; s_currentOut = new AsyncLocal<StringWriter>(); s_currentError = new AsyncLocal<StringWriter>(); Console.SetOut(new SharedConsoleOutWriter()); Console.SetError(new SharedConsoleErrorWriter()); } public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput) { var outputWriter = new CappedStringWriter(expectedLength); var errorOutputWriter = new CappedStringWriter(expectedLength); var savedOutput = s_currentOut.Value; var savedError = s_currentError.Value; try { s_currentOut.Value = outputWriter; s_currentError.Value = errorOutputWriter; action(); } finally { s_currentOut.Value = savedOutput; s_currentError.Value = savedError; } output = outputWriter.ToString(); errorOutput = errorOutputWriter.ToString(); } private sealed class SharedConsoleOutWriter : SharedConsoleWriter { public override TextWriter Underlying => s_currentOut.Value ?? s_savedConsoleOut; } private sealed class SharedConsoleErrorWriter : SharedConsoleWriter { public override TextWriter Underlying => s_currentError.Value ?? s_savedConsoleError; } private abstract class SharedConsoleWriter : TextWriter { public override Encoding Encoding => Underlying.Encoding; public abstract TextWriter Underlying { get; } public override void Write(char value) => Underlying.Write(value); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NETCOREAPP using System; using System.IO; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.CoreClr { internal static class SharedConsole { private static TextWriter s_savedConsoleOut; private static TextWriter s_savedConsoleError; private static AsyncLocal<StringWriter> s_currentOut; private static AsyncLocal<StringWriter> s_currentError; internal static void OverrideConsole() { s_savedConsoleOut = Console.Out; s_savedConsoleError = Console.Error; s_currentOut = new AsyncLocal<StringWriter>(); s_currentError = new AsyncLocal<StringWriter>(); Console.SetOut(new SharedConsoleOutWriter()); Console.SetError(new SharedConsoleErrorWriter()); } public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput) { var outputWriter = new CappedStringWriter(expectedLength); var errorOutputWriter = new CappedStringWriter(expectedLength); var savedOutput = s_currentOut.Value; var savedError = s_currentError.Value; try { s_currentOut.Value = outputWriter; s_currentError.Value = errorOutputWriter; action(); } finally { s_currentOut.Value = savedOutput; s_currentError.Value = savedError; } output = outputWriter.ToString(); errorOutput = errorOutputWriter.ToString(); } private sealed class SharedConsoleOutWriter : SharedConsoleWriter { public override TextWriter Underlying => s_currentOut.Value ?? s_savedConsoleOut; } private sealed class SharedConsoleErrorWriter : SharedConsoleWriter { public override TextWriter Underlying => s_currentError.Value ?? s_savedConsoleError; } private abstract class SharedConsoleWriter : TextWriter { public override Encoding Encoding => Underlying.Encoding; public abstract TextWriter Underlying { get; } public override void Write(char value) => Underlying.Write(value); } } } #endif
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Compilers/VisualBasic/Portable/Locations/EmbeddedTreeLocation.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A program location in source code. ''' </summary> Friend NotInheritable Class EmbeddedTreeLocation Inherits VBLocation Friend ReadOnly _embeddedKind As EmbeddedSymbolKind Friend ReadOnly _span As TextSpan Public Overrides ReadOnly Property Kind As LocationKind Get Return LocationKind.None End Get End Property Friend Overrides ReadOnly Property EmbeddedKind As EmbeddedSymbolKind Get Return _embeddedKind End Get End Property Friend Overrides ReadOnly Property PossiblyEmbeddedOrMySourceSpan As TextSpan Get Return _span End Get End Property Friend Overrides ReadOnly Property PossiblyEmbeddedOrMySourceTree As SyntaxTree Get Return EmbeddedSymbolManager.GetEmbeddedTree(Me._embeddedKind) End Get End Property Public Sub New(embeddedKind As EmbeddedSymbolKind, span As TextSpan) Debug.Assert(embeddedKind = EmbeddedSymbolKind.VbCore OrElse embeddedKind = EmbeddedSymbolKind.XmlHelper OrElse embeddedKind = EmbeddedSymbolKind.EmbeddedAttribute) _embeddedKind = embeddedKind _span = span End Sub Public Overloads Function Equals(other As EmbeddedTreeLocation) As Boolean If Me Is other Then Return True End If Return other IsNot Nothing AndAlso other.EmbeddedKind = Me._embeddedKind AndAlso other._span.Equals(Me._span) End Function Public Overloads Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, EmbeddedTreeLocation)) End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(CInt(_embeddedKind).GetHashCode(), _span.GetHashCode()) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A program location in source code. ''' </summary> Friend NotInheritable Class EmbeddedTreeLocation Inherits VBLocation Friend ReadOnly _embeddedKind As EmbeddedSymbolKind Friend ReadOnly _span As TextSpan Public Overrides ReadOnly Property Kind As LocationKind Get Return LocationKind.None End Get End Property Friend Overrides ReadOnly Property EmbeddedKind As EmbeddedSymbolKind Get Return _embeddedKind End Get End Property Friend Overrides ReadOnly Property PossiblyEmbeddedOrMySourceSpan As TextSpan Get Return _span End Get End Property Friend Overrides ReadOnly Property PossiblyEmbeddedOrMySourceTree As SyntaxTree Get Return EmbeddedSymbolManager.GetEmbeddedTree(Me._embeddedKind) End Get End Property Public Sub New(embeddedKind As EmbeddedSymbolKind, span As TextSpan) Debug.Assert(embeddedKind = EmbeddedSymbolKind.VbCore OrElse embeddedKind = EmbeddedSymbolKind.XmlHelper OrElse embeddedKind = EmbeddedSymbolKind.EmbeddedAttribute) _embeddedKind = embeddedKind _span = span End Sub Public Overloads Function Equals(other As EmbeddedTreeLocation) As Boolean If Me Is other Then Return True End If Return other IsNot Nothing AndAlso other.EmbeddedKind = Me._embeddedKind AndAlso other._span.Equals(Me._span) End Function Public Overloads Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, EmbeddedTreeLocation)) End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(CInt(_embeddedKind).GetHashCode(), _span.GetHashCode()) End Function End Class End Namespace
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Workspaces/MSBuildTest/MSBuildWorkspaceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using static Microsoft.CodeAnalysis.CSharp.LanguageVersionFacts; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTests : MSBuildWorkspaceTestBase { [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestCreateMSBuildWorkspace() { using var workspace = CreateMSBuildWorkspace(); Assert.NotNull(workspace); Assert.NotNull(workspace.Services); Assert.NotNull(workspace.Services.Workspace); Assert.Equal(workspace, workspace.Services.Workspace); Assert.NotNull(workspace.Services.HostServices); Assert.NotNull(workspace.Services.PersistentStorage); Assert.NotNull(workspace.Services.TemporaryStorage); Assert.NotNull(workspace.Services.TextFactory); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SingleProjectSolution() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_MultiProjectSolution() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // verify the dependent project has the correct metadata references (and does not include the output for the project references) var references = vbProject.MetadataReferences.ToList(); Assert.Equal(4, references.Count); var fileNames = new HashSet<string>(references.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath))); Assert.Contains("System.Core.dll", fileNames); Assert.Contains("System.dll", fileNames); Assert.Contains("Microsoft.VisualBasic.dll", fileNames); Assert.Contains("mscorlib.dll", fileNames); // the compilation references should have the metadata reference to the csharp project skeleton assembly var compilation = await vbProject.GetCompilationAsync(); var compReferences = compilation.References.ToList(); Assert.Equal(5, compReferences.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/41456"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(2824, "https://github.com/dotnet/roslyn/issues/2824")] public async Task Test_OpenProjectReferencingPortableProject() { var files = new FileSet( (@"CSharpProject\ReferencesPortableProject.csproj", Resources.ProjectFiles.CSharp.ReferencesPortableProject), (@"CSharpProject\Program.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\PortableProject.csproj", Resources.ProjectFiles.CSharp.PortableProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\ReferencesPortableProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); AssertFailures(workspace); var hasFacades = project.MetadataReferences.OfType<PortableExecutableReference>().Any(r => r.FilePath.Contains("Facade")); Assert.True(hasFacades, userMessage: "Expected to find facades in the project references:" + Environment.NewLine + string.Join(Environment.NewLine, project.MetadataReferences.OfType<PortableExecutableReference>().Select(r => r.FilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_SharedMetadataReferences() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var p0 = solution.Projects.ElementAt(0); var p1 = solution.Projects.ElementAt(1); Assert.NotSame(p0, p1); var p0mscorlib = GetMetadataReference(p0, "mscorlib"); var p1mscorlib = GetMetadataReference(p1, "mscorlib"); Assert.NotNull(p0mscorlib); Assert.NotNull(p1mscorlib); // metadata references to mscorlib in both projects are the same Assert.Same(p0mscorlib, p1mscorlib); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task Test_SharedMetadataReferencesWithAliases() { var projPath1 = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var projPath2 = @"CSharpProject\CSharpProject_ExternAlias2.csproj"; var files = new FileSet( (projPath1, Resources.ProjectFiles.CSharp.ExternAlias), (projPath2, Resources.ProjectFiles.CSharp.ExternAlias2), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath1 = GetSolutionFileName(projPath1); var fullPath2 = GetSolutionFileName(projPath2); using var workspace = CreateMSBuildWorkspace(); var proj1 = await workspace.OpenProjectAsync(fullPath1); var proj2 = await workspace.OpenProjectAsync(fullPath2); var p1Sys1 = GetMetadataReferenceByAlias(proj1, "Sys1"); var p1Sys2 = GetMetadataReferenceByAlias(proj1, "Sys2"); var p2Sys1 = GetMetadataReferenceByAlias(proj2, "Sys1"); var p2Sys3 = GetMetadataReferenceByAlias(proj2, "Sys3"); Assert.NotNull(p1Sys1); Assert.NotNull(p1Sys2); Assert.NotNull(p2Sys1); Assert.NotNull(p2Sys3); // same filepath but different alias so they are not the same instance Assert.NotSame(p1Sys1, p1Sys2); Assert.NotSame(p2Sys1, p2Sys3); // same filepath and alias so they are the same instance Assert.Same(p1Sys1, p2Sys1); var mdp1Sys1 = GetMetadata(p1Sys1); var mdp1Sys2 = GetMetadata(p1Sys2); var mdp2Sys1 = GetMetadata(p2Sys1); var mdp2Sys3 = GetMetadata(p2Sys1); Assert.NotNull(mdp1Sys1); Assert.NotNull(mdp1Sys2); Assert.NotNull(mdp2Sys1); Assert.NotNull(mdp2Sys3); // all references to System.dll share the same metadata bytes Assert.Same(mdp1Sys1.Id, mdp1Sys2.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys1.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys3.Id); } private static MetadataReference GetMetadataReference(Project project, string name) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => mr.FilePath.Contains(name)); private static MetadataReference GetMetadataReferenceByAlias(Project project, string aliasName) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => !mr.Properties.Aliases.IsDefault && mr.Properties.Aliases.Contains(aliasName)); private static Metadata GetMetadata(MetadataReference metadataReference) => ((PortableExecutableReference)metadataReference).GetMetadata(); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(552981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552981")] public async Task TestOpenSolution_DuplicateProjectGuids() { CreateFiles(GetSolutionWithDuplicatedGuidFiles()); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(831379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831379")] public async Task GetCompilationWithCircularProjectReferences() { CreateFiles(GetSolutionWithCircularProjectReferences()); var solutionFilePath = GetSolutionFileName("CircularSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Verify we can get compilations for both projects var projects = solution.Projects.ToArray(); // Exactly one of them should have a reference to the other. Which one it is, is unspecced Assert.True(projects[0].ProjectReferences.Any(r => r.ProjectId == projects[1].Id) || projects[1].ProjectReferences.Any(r => r.ProjectId == projects[0].Id)); var compilation1 = await projects[0].GetCompilationAsync(); var compilation2 = await projects[1].GetCompilationAsync(); // Exactly one of them should have a compilation to the other. Which one it is, is unspecced Assert.True(compilation1.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation2) || compilation2.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation1)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOutputFilePaths() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOutputInfo() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.CompilationOutputInfo.AssemblyPath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.CompilationOutputInfo.AssemblyPath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesUsesInMemoryGeneratedMetadata() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); // prove there is no existing metadata on disk for this project Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.False(File.Exists(p1.OutputFilePath)); // prove that vb project refers to csharp project via generated metadata (skeleton) assembly. // it should be a MetadataImageReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "CSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesWithOutOfDateMetadataOnDiskUsesInMemoryGeneratedMetadata() { await PrepareCrossLanguageProjectWithEmittedMetadataAsync(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); // recreate the solution so it will reload from disk using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); // update project with top level change that should now invalidate use of metadata from disk var d1 = p1.Documents.First(); var root = await d1.GetSyntaxRootAsync(); var decl = root.DescendantNodes().OfType<CS.Syntax.ClassDeclarationSyntax>().First(); var newDecl = decl.WithIdentifier(CS.SyntaxFactory.Identifier("Pogrom").WithLeadingTrivia(decl.Identifier.LeadingTrivia).WithTrailingTrivia(decl.Identifier.TrailingTrivia)); var newRoot = root.ReplaceNode(decl, newDecl); var newDoc = d1.WithSyntaxRoot(newRoot); p1 = newDoc.Project; var p2 = p1.Solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // we should now find a MetadataImageReference that was generated instead of a MetadataFileReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "EmittedCSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/54818"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInternalsVisibleToSigned() { var solution = await SolutionAsync( Project( ProjectName("Project1"), Sign, Document(string.Format( @"using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(""Project2, PublicKey={0}"")] class C1 {{ }}", PublicKey))), Project( ProjectName("Project2"), Sign, ProjectReference("Project1"), Document(@"class C2 : C1 { }"))); var project2 = solution.GetProjectsByName("Project2").First(); var compilation = await project2.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning) .ToArray(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestVersions() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var sversion = solution.Version; var latestPV = solution.GetLatestProjectVersion(); var project = solution.Projects.First(); var pversion = project.Version; var document = project.Documents.First(); var dversion = await document.GetTextVersionAsync(); var latestDV = await project.GetLatestDocumentVersionAsync(); // update document var solution1 = solution.WithDocumentText(document.Id, SourceText.From("using test;")); var document1 = solution1.GetDocument(document.Id); var dversion1 = await document1.GetTextVersionAsync(); Assert.NotEqual(dversion, dversion1); // new document version Assert.True(dversion1.GetTestAccessor().IsNewerThan(dversion)); Assert.Equal(solution.Version, solution1.Version); // updating document should not have changed solution version Assert.Equal(project.Version, document1.Project.Version); // updating doc should not have changed project version var latestDV1 = await document1.Project.GetLatestDocumentVersionAsync(); Assert.NotEqual(latestDV, latestDV1); Assert.True(latestDV1.GetTestAccessor().IsNewerThan(latestDV)); Assert.Equal(latestDV1, await document1.GetTextVersionAsync()); // projects latest doc version should be this doc's version // update project var solution2 = solution1.WithProjectCompilationOptions(project.Id, project.CompilationOptions.WithOutputKind(OutputKind.NetModule)); var document2 = solution2.GetDocument(document.Id); var dversion2 = await document2.GetTextVersionAsync(); Assert.Equal(dversion1, dversion2); // document didn't change, so version should be the same. Assert.NotEqual(document1.Project.Version, document2.Project.Version); // project did change, so project versions should be different Assert.True(document2.Project.Version.GetTestAccessor().IsNewerThan(document1.Project.Version)); Assert.Equal(solution1.Version, solution2.Version); // solution didn't change, just individual project. // update solution var pid2 = ProjectId.CreateNewId(); var solution3 = solution2.AddProject(pid2, "foo", "foo", LanguageNames.CSharp); Assert.NotEqual(solution2.Version, solution3.Version); // solution changed, added project. Assert.True(solution3.Version.GetTestAccessor().IsNewerThan(solution2.Version)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_LoadMetadataForReferencedProjects() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformDefault() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformTrue() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(("ShouldUnsetParentConfigurationAndPlatform", bool.TrueString)); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndWinMDObj() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutOutputPath() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutAssemblyName() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_CSharp_WithoutCSharpTargetsImported_DocumentsArePickedUp() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutCSharpTargetsImported)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutVBTargetsImported_DocumentsArePickedUp() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutVBTargetsImported)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndWinMDObj() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutOutputPath() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLanguageVersion15_3() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "15.3")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersion.VisualBasic15_3, ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLatestLanguageVersion() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "Latest")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersionFacts.MapSpecifiedToEffectiveVersion(VB.LanguageVersion.Latest), ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); Assert.Equal(VB.LanguageVersion.Latest, ((VB.VisualBasicParseOptions)project.ParseOptions).SpecifiedLanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutAssemblyName() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(workspace.Diagnostics); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_Respect_ReferenceOutputassembly_Flag() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"VisualBasicProject_Circular_Top.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Top) .WithFile(@"VisualBasicProject_Circular_Target.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Target)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject_Circular_Top.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(project.ProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithXaml() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithXaml) .WithFile(@"CSharpProject\App.xaml", Resources.SourceFiles.Xaml.App) .WithFile(@"CSharpProject\App.xaml.cs", Resources.SourceFiles.CSharp.App) .WithFile(@"CSharpProject\MainWindow.xaml", Resources.SourceFiles.Xaml.MainWindow) .WithFile(@"CSharpProject\MainWindow.xaml.cs", Resources.SourceFiles.CSharp.MainWindow)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // Ensure the Xaml compiler does not run in a separate appdomain. It appears that this won't work within xUnit. using var workspace = CreateMSBuildWorkspace(("AlwaysCompileMarkupFilesInSeparateDomain", "false")); var project = await workspace.OpenProjectAsync(projectFilePath); var documents = project.Documents.ToList(); // AssemblyInfo.cs, App.xaml.cs, MainWindow.xaml.cs, App.g.cs, MainWindow.g.cs, + unusual AssemblyAttributes.cs Assert.Equal(6, documents.Count); // both xaml code behind files are documents Assert.Contains(documents, d => d.Name == "App.xaml.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.xaml.cs"); // prove no xaml files are documents Assert.DoesNotContain(documents, d => d.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase)); // prove that generated source files for xaml files are included in documents list Assert.Contains(documents, d => d.Name == "App.g.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.g.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestMetadataReferenceHasBadHintPath() { // prove that even with bad hint path for metadata reference the workspace can succeed at finding the correct metadata reference. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadHintPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var refs = project.MetadataReferences.ToList(); var csharpLib = refs.OfType<PortableExecutableReference>().FirstOrDefault(r => r.FilePath.Contains("Microsoft.CSharp")); Assert.NotNull(csharpLib); } [ConditionalFact(typeof(VisualStudio16_9_Preview3OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath() { // prove that even if assembly name is specified as a path instead of just a name, workspace still succeeds at opening project. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.GetDirectoryName(project.FilePath); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(project.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath2() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath2)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.Combine(Path.GetDirectoryName(project.FilePath), @"bin"); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(Path.GetFullPath(project.OutputFilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithDuplicateFile() { // Verify that we don't throw in this case CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.DuplicateFile)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var documents = project.Documents.Where(d => d.Name == "CSharpClass.cs").ToList(); Assert.Equal(2, documents.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidFileExtensionAsync() { // make sure the file does in fact exist, but with an unrecognized extension const string ProjFileName = @"CSharpProject\CSharpProject.csproj.nyi"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(ProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var e = await Assert.ThrowsAsync<InvalidOperationException>(async delegate { await MSBuildWorkspace.Create().OpenProjectAsync(GetSolutionFileName(ProjFileName)); }); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, GetSolutionFileName(ProjFileName), ".nyi"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_ProjectFileExtensionAssociatedWithUnknownLanguageAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var language = "lingo"; var e = await Assert.ThrowsAsync<InvalidOperationException>(async delegate { var ws = MSBuildWorkspace.Create(); ws.AssociateFileExtensionWithLanguage("csproj", language); // non-existent language await ws.OpenProjectAsync(projFileName); }); // the exception should tell us something about the language being unrecognized. var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projFileName, language); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension1() { // make a CSharp solution with a project file having the incorrect extension 'vbproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.vbproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); workspace.AssociateFileExtensionWithLanguage("vbproj", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension2_IgnoreCase() { // make a CSharp solution with a project file having the incorrect extension 'anyproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.anyproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.anyproj"); using var workspace = CreateMSBuildWorkspace(); // prove that the association works even if the case is different workspace.AssociateFileExtensionWithLanguage("ANYPROJ", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentSolutionFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("NonExistentSolution.sln"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidSolutionFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidSolution.sln"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithTemporaryLockedFile_SucceedsWithoutFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); using var ws = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await ws.OpenSolutionAsync(GetSolutionFileName(@"TestSolution.sln")); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); // start reading text var getTextTask = doc.GetTextAsync(); // wait 1 unit of retry delay then close file var delay = TextLoader.RetryDelay; await Task.Delay(delay).ContinueWith(t => file.Close(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // finish reading text var text = await getTextTask; Assert.NotEmpty(text.ToString()); } finally { file.Close(); } Assert.Empty(ws.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithLockedFile_FailsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await workspace.OpenSolutionAsync(solutionFilePath); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); var text = await doc.GetTextAsync(); Assert.Empty(text.ToString()); } finally { file.Close(); } Assert.Equal(WorkspaceDiagnosticKind.Failure, workspace.Diagnostics.Single().Kind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [WorkItem(985906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/985906")] [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task HandleSolutionProjectTypeSolutionFolder() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.SolutionFolder)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipFalse_Fails() { // when not skipped we should get an exception for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await Assert.ThrowsAsync<InvalidOperationException>(() => workspace.OpenSolutionAsync(solutionFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipFalse_Fails() { // when skipped we should see an exception for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await Assert.ThrowsAsync<FileNotFoundException>(() => workspace.OpenSolutionAsync(solutionFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectFileExtension_Fails() { // proves that for solution open, project type guid and extension are both necessary CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidButRecognizedExtension_Succeeds() { // proves that if project type guid is not recognized, a known project file extension is all we need. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuid)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipTrue_SucceedsWithFailureEvent() { // proves that if both project type guid and file extension are unrecognized, then project is skipped. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipFalse_FailsAsync() { // proves that if both project type guid and file extension are unrecognized, then open project fails. const string NoProjFileName = @"CSharpProject\CSharpProject.noproj"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(NoProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); var e = await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenSolutionAsync(solutionFilePath); }); var noProjFullFileName = GetSolutionFileName(NoProjFileName); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, noProjFullFileName, ".noproj"); Assert.Equal(expected, e.Message); } private readonly IEnumerable<Assembly> _defaultAssembliesWithoutCSharp = MefHostServices.DefaultAssemblies.Where(a => !a.FullName.Contains("CSharp")); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipFalse_ThrowsAsync() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); var e = await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = false; await workspace.OpenSolutionAsync(solutionFilePath); }); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipTrue_SucceedsWithDiagnostic() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = true; var solution = await workspace.OpenSolutionAsync(solutionFilePath); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, workspace.Diagnostics.Single().Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenProject_WithMissingLanguageLibraries_Throws() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var projectName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = MSBuildWorkspace.Create(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); var e = await Assert.ThrowsAsync<InvalidOperationException>(() => workspace.OpenProjectAsync(projectName)); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectName, ".csproj"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidFilePath_Fails() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidProject.csproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\NonExistentProject.csproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipFalse_FailsAsync() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to unrecognized extension. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipTrue_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); var metaRefs = project.MetadataReferences.ToList(); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipFalse_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); Assert.Contains(project.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_BadMsbuildProject_SkipTrue_SucceedsWithDanglingProjectReference() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.Dlls.CSharpProject)); // use metadata file as stand-in for bad project file var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Single(project.AllProjectReferences); Assert.InRange(workspace.Diagnostics.Count, 2, 3); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_ExistingMetadata_Succeeds() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project got converted to a metadata reference var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Empty(projRefs); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_NonExistentMetadata_LoadsProjectInstead() { CreateFiles(GetMultiProjectSolutionFiles()); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project is still a project ref, did not get converted to metadata ref var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Single(projRefs); Assert.DoesNotContain(metaRefs, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_UpdateExistingReferences() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var vbProjectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var csProjectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; // first open vb project that references c# project, but only reference the c# project's built metadata using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); // prove vb project references c# project as a metadata reference Assert.Empty(vbProject.ProjectReferences); Assert.Contains(vbProject.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); // now explicitly open the c# project that got referenced as metadata var csProject = await workspace.OpenProjectAsync(csProjectFilePath); // show that the vb project now references the c# project directly (not as metadata) vbProject = workspace.CurrentSolution.GetProject(vbProject.Id); Assert.Single(vbProject.ProjectReferences); Assert.DoesNotContain(vbProject.MetadataReferences, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(Framework35Installed))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(528984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528984")] public async Task TestOpenProject_AddVBDefaultReferences() { var files = new FileSet( ("VisualBasicProject_3_5.vbproj", Resources.ProjectFiles.VisualBasic.VisualBasicProject_3_5), ("VisualBasicProject_VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName("VisualBasicProject_3_5.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Full() { CreateCSharpFilesWith("DebugType", "full"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_None() { CreateCSharpFilesWith("DebugType", "none"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_PDBOnly() { CreateCSharpFilesWith("DebugType", "pdbonly"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Portable() { CreateCSharpFilesWith("DebugType", "portable"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Embedded() { CreateCSharpFilesWith("DebugType", "embedded"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_DynamicallyLinkedLibrary() { CreateCSharpFilesWith("OutputType", "Library"); await AssertCSCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_ConsoleApplication() { CreateCSharpFilesWith("OutputType", "Exe"); await AssertCSCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_WindowsApplication() { CreateCSharpFilesWith("OutputType", "WinExe"); await AssertCSCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_NetModule() { CreateCSharpFilesWith("OutputType", "Module"); await AssertCSCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Release() { CreateCSharpFilesWith("Optimize", "True"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Release, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Debug() { CreateCSharpFilesWith("Optimize", "False"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Debug, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_MainFileName() { CreateCSharpFilesWith("StartupObject", "Foo"); await AssertCSCompilationOptionsAsync("Foo", options => options.MainTypeName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_Missing() { CreateCSharpFiles(); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_False() { CreateCSharpFilesWith("SignAssembly", "false"); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_True() { CreateCSharpFilesWith("SignAssembly", "true"); await AssertCSCompilationOptionsAsync("snKey.snk", options => Path.GetFileName(options.CryptoKeyFile)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_False() { CreateCSharpFilesWith("DelaySign", "false"); await AssertCSCompilationOptionsAsync(null, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_True() { CreateCSharpFilesWith("DelaySign", "true"); await AssertCSCompilationOptionsAsync(true, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_True() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "true"); await AssertCSCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_False() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "false"); await AssertCSCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA1() { CreateCSharpFilesWith("LangVersion", "ISO-1"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp1, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA2() { CreateCSharpFilesWith("LangVersion", "ISO-2"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp2, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_None() { CreateCSharpFilesWith("LangVersion", "3"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp3, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_LanguageVersion_Default() { CreateCSharpFiles(); await AssertCSParseOptionsAsync(CS.LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_PreprocessorSymbols() { CreateCSharpFilesWith("DefineConstants", "DEBUG;TRACE;X;Y"); await AssertCSParseOptionsAsync("DEBUG,TRACE,X,Y", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationDebug() { CreateCSharpFiles(); await AssertCSParseOptionsAsync("DEBUG,TRACE", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationRelease() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(("Configuration", "Release")); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); var options = project.ParseOptions; Assert.DoesNotContain(options.PreprocessorSymbolNames, name => name == "DEBUG"); Assert.Contains(options.PreprocessorSymbolNames, name => name == "TRACE"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Full() { CreateVBFilesWith("DebugType", "full"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_None() { CreateVBFilesWith("DebugType", "none"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_PDBOnly() { CreateVBFilesWith("DebugType", "pdbonly"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Portable() { CreateVBFilesWith("DebugType", "portable"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Embedded() { CreateVBFilesWith("DebugType", "embedded"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_VBRuntime_Embed() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.Embed)); await AssertVBCompilationOptionsAsync(true, options => options.EmbedVbCoreRuntime); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_DynamicallyLinkedLibrary() { CreateVBFilesWith("OutputType", "Library"); await AssertVBCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_ConsoleApplication() { CreateVBFilesWith("OutputType", "Exe"); await AssertVBCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_WindowsApplication() { CreateVBFilesWith("OutputType", "WinExe"); await AssertVBCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_NetModule() { CreateVBFilesWith("OutputType", "Module"); await AssertVBCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_RootNamespace() { CreateVBFilesWith("RootNamespace", "Foo.Bar"); await AssertVBCompilationOptionsAsync("Foo.Bar", options => options.RootNamespace); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_On() { CreateVBFilesWith("OptionStrict", "On"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.On, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Off() { CreateVBFilesWith("OptionStrict", "Off"); // The VBC MSBuild task specifies '/optionstrict:custom' rather than '/optionstrict-' // See https://github.com/dotnet/roslyn/blob/58f44c39048032c6b823ddeedddd20fa589912f5/src/Compilers/Core/MSBuildTask/Vbc.cs#L390-L418 for details. await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Custom() { CreateVBFilesWith("OptionStrictType", "Custom"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_True() { CreateVBFilesWith("OptionInfer", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_False() { CreateVBFilesWith("OptionInfer", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_True() { CreateVBFilesWith("OptionExplicit", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_False() { CreateVBFilesWith("OptionExplicit", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_True() { CreateVBFilesWith("OptionCompare", "Text"); await AssertVBCompilationOptionsAsync(true, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_False() { CreateVBFilesWith("OptionCompare", "Binary"); await AssertVBCompilationOptionsAsync(false, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_True() { CreateVBFilesWith("RemoveIntegerChecks", "true"); await AssertVBCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_False() { CreateVBFilesWith("RemoveIntegerChecks", "false"); await AssertVBCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionAssemblyOriginatorKeyFile_SignAssemblyFalse() { CreateVBFilesWith("SignAssembly", "false"); await AssertVBCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_GlobalImports() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicCompilationOptions)project.CompilationOptions; var imports = options.GlobalImports; AssertEx.Equal( expected: new[] { "Microsoft.VisualBasic", "System", "System.Collections", "System.Collections.Generic", "System.Diagnostics", "System.Linq", }, actual: imports.Select(i => i.Name)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_VisualBasic_PreprocessorSymbols() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "X=1,Y=2,Z,T=-1,VBC_VER=123,F=false")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; var defines = new List<KeyValuePair<string, object>>(options.PreprocessorSymbols); defines.Sort((x, y) => x.Key.CompareTo(y.Key)); AssertEx.Equal( expected: new[] { new KeyValuePair<string, object>("_MyType", "Windows"), new KeyValuePair<string, object>("CONFIG", "Debug"), new KeyValuePair<string, object>("DEBUG", -1), new KeyValuePair<string, object>("F", false), new KeyValuePair<string, object>("PLATFORM", "AnyCPU"), new KeyValuePair<string, object>("T", -1), new KeyValuePair<string, object>("TARGET", "library"), new KeyValuePair<string, object>("TRACE", -1), new KeyValuePair<string, object>("VBC_VER", 123), new KeyValuePair<string, object>("X", 1), new KeyValuePair<string, object>("Y", 2), new KeyValuePair<string, object>("Z", true), }, actual: defines); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.True(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeNotEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.False(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.Contains("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeNotEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.DoesNotContain("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithLinkedDocument() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithLink) .WithFile(@"OtherStuff\Foo.cs", Resources.SourceFiles.CSharp.OtherStuff_Foo)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project.Documents.ToList(); var fooDoc = documents.Single(d => d.Name == "Foo.cs"); var folder = Assert.Single(fooDoc.Folders); Assert.Equal("Blah", folder); // prove that the file path is the correct full path to the actual file Assert.Contains("OtherStuff", fooDoc.FilePath); Assert.True(File.Exists(fooDoc.FilePath)); var text = File.ReadAllText(fooDoc.FilePath); Assert.Equal(Resources.SourceFiles.CSharp.OtherStuff_Foo, text); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newText = SourceText.From("public class Bar { }"); workspace.AddDocument(project.Id, new string[] { "NewFolder" }, "Bar.cs", newText); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(4, documents.Count); var document2 = documents.Single(d => d.Name == "Bar.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); Assert.Single(document2.Folders); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check project file on disk var projectFileText = File.ReadAllText(project2.FilePath); Assert.Contains(@"NewFolder\Bar.cs", projectFileText); // reload project & solution to prove project file change was good using var workspaceB = CreateMSBuildWorkspace(); var solutionB = await workspaceB.OpenSolutionAsync(solutionFilePath); var projectB = workspaceB.CurrentSolution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documentsB = projectB.Documents.ToList(); Assert.Equal(4, documentsB.Count); var documentB = documentsB.Single(d => d.Name == "Bar.cs"); Assert.Single(documentB.Folders); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestUpdateDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); var newText = SourceText.From("public class Bar { }"); workspace.TryApplyChanges(solution.WithDocumentText(document.Id, newText, PreservationMode.PreserveIdentity)); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(3, documents.Count); var document2 = documents.Single(d => d.Name == "CSharpClass.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestRemoveDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); workspace.RemoveDocument(document.Id); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); Assert.DoesNotContain(project2.Documents, d => d.Name == "CSharpClass.cs"); // check actual file on disk... Assert.False(File.Exists(document.FilePath)); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateDocumentText() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().Documents.ToList(); var document = documents.Single(d => d.Name.Contains("CSharpClass")); var text = await document.GetTextAsync(); var newText = SourceText.From("using System.Diagnostics;\r\n" + text.ToString()); var newSolution = solution.WithDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateAdditionalDocumentText() { CreateFiles(GetSimpleCSharpSolutionWithAdditionaFile()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().AdditionalDocuments.ToList(); var document = documents.Single(d => d.Name.Contains("ValidAdditionalFile")); var text = await document.GetTextAsync(); var newText = SourceText.From("New Text In Additional File.\r\n" + text.ToString()); var newSolution = solution.WithAdditionalDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetAdditionalDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_AddDocument() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newDocId = DocumentId.CreateNewId(project.Id); var newText = SourceText.From("public class Bar { }"); var newSolution = solution.AddDocument(newDocId, "Bar.cs", newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(newDocId); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_NotSupportedChangesFail() { var csharpProjPath = @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"; var vbProjPath = @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj"; CreateFiles(GetAnalyzerReferenceSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var csProjectFilePath = GetSolutionFileName(csharpProjPath); var csProject = await workspace.OpenProjectAsync(csProjectFilePath); var csProjectId = csProject.Id; var vbProjectFilePath = GetSolutionFileName(vbProjPath); var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); var vbProjectId = vbProject.Id; // adding additional documents not supported. Assert.False(workspace.CanApplyChange(ApplyChangesKind.AddAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.AddAdditionalDocument(DocumentId.CreateNewId(csProjectId), "foo.xaml", SourceText.From("<foo></foo>"))); }); var xaml = workspace.CurrentSolution.GetProject(csProjectId).AdditionalDocuments.FirstOrDefault(d => d.Name == "XamlFile.xaml"); Assert.NotNull(xaml); // removing additional documents not supported Assert.False(workspace.CanApplyChange(ApplyChangesKind.RemoveAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.RemoveAdditionalDocument(xaml.Id)); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWaiter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWaiter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedWeakEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWanter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges( workspace .CurrentSolution .WithDocumentText( doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWanter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(529276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529276"), WorkItem(12086, "DevDiv_Projects/Roslyn")] public async Task TestOpenProject_LoadMetadataForReferenceProjects_NoMetadata() { var projPath = @"CSharpProject\CSharpProject_ProjectReference.csproj"; var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var projectFullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var proj = await workspace.OpenProjectAsync(projectFullPath); // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); // and all is well var comp = await proj.GetCompilationAsync(); var errs = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error); Assert.Empty(errs); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(918072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918072")] public async Task TestAnalyzerReferenceLoadStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); Assert.Equal(1, proj.AnalyzerReferences.Count); var analyzerReference = proj.AnalyzerReferences[0] as AnalyzerFileReference; Assert.NotNull(analyzerReference); Assert.True(analyzerReference.FullPath.EndsWith("CSharpProject.dll", StringComparison.OrdinalIgnoreCase)); } // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAdditionalFilesStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = Assert.Single(proj.AdditionalDocuments); Assert.Equal("XamlFile.xaml", doc.Name); var text = await doc.GetTextAsync(); Assert.Contains("Window", text.ToString(), StringComparison.Ordinal); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestLoadTextSync() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = new AdhocWorkspace(MSBuildMefHostServices.DefaultServices, WorkspaceKind.MSBuild); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var loader = new MSBuildProjectLoader(workspace); var infos = await loader.LoadProjectInfoAsync(projectFullPath); var doc = infos[0].Documents[0]; var tav = doc.TextLoader.LoadTextAndVersionSynchronously(workspace, doc.Id, CancellationToken.None); var adoc = infos[0].AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atav = adoc.TextLoader.LoadTextAndVersionSynchronously(workspace, adoc.Id, CancellationToken.None); Assert.Contains("Window", atav.Text.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestGetTextSynchronously() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = proj.Documents.First(); var text = doc.State.GetTextSynchronously(CancellationToken.None); var adoc = proj.AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atext = adoc.State.GetTextSynchronously(CancellationToken.None); Assert.Contains("Window", atext.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task TestCSharpExternAlias() { var projPath = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var files = new FileSet( (projPath, Resources.ProjectFiles.CSharp.ExternAlias), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(fullPath); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(530337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530337")] public async Task TestProjectReferenceWithExternAlias() { var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); var proj = sol.Projects.First(); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithReferenceOutputAssemblyFalse() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Add(new XElement(XName.Get("ReferenceOutputAssembly", MSBuildNamespace), "false"))); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.Empty(project.ProjectReferences); } } private static FileSet VisitProjectReferences(FileSet files, Action<XElement> visitProjectReference) { var result = new List<(string, object)>(); foreach (var (fileName, fileContent) in files) { var text = fileContent.ToString(); if (fileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase)) { text = VisitProjectReferences(text, visitProjectReference); } result.Add((fileName, text)); } return new FileSet(result.ToArray()); } private static string VisitProjectReferences(string projectFileText, Action<XElement> visitProjectReference) { var document = XDocument.Parse(projectFileText); var projectReferenceItems = document.Descendants(XName.Get("ProjectReference", MSBuildNamespace)); foreach (var projectReferenceItem in projectReferenceItems) { visitProjectReference(projectReferenceItem); } return document.ToString(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithNoGuid() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Elements(XName.Get("Project", MSBuildNamespace)).Remove()); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.InRange(project.ProjectReferences.Count(), 0, 1); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/23685"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(5668, "https://github.com/dotnet/roslyn/issues/5668")] public async Task TestOpenProject_MetadataReferenceHasDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("System.Console"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_HasSourceDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var parseOptions = (CS.CSharpParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Parse, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_HasSourceDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var parseOptions = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CrossLanguageSkeletonReferenceHasDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.CSharp); var csoptions = (CS.CSharpParseOptions)csproject.ParseOptions; Assert.Equal(DocumentationMode.Parse, csoptions.DocumentationMode); var cscomp = await csproject.GetCompilationAsync(); var cssymbol = cscomp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var cscomment = cssymbol.GetDocumentationCommentXml(); Assert.NotNull(cscomment); var vbproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var vboptions = (VB.VisualBasicParseOptions)vbproject.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, vboptions.DocumentationMode); var vbcomp = await vbproject.GetCompilationAsync(); var vbsymbol = vbcomp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var parent = vbsymbol.BaseType; // this is the vb imported version of the csharp symbol var vbcomment = parent.GetDocumentationCommentXml(); Assert.Equal(cscomment, vbcomment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithProjectFileLockedAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using (File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite)) { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFile); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.Contains("The process cannot access the file", diagnostic.Message); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectFileAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\NoProject.csproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFile); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentSolutionFileAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var solutionFile = GetSolutionFileName(@"NoSolution.sln"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFile); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SolutionFileHasEmptyLinesAndWhitespaceOnlyLines() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.CSharp_EmptyLines), (@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.CSharpProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\Properties\AssemblyInfo.cs", Resources.SourceFiles.CSharp.AssemblyInfo)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531543")] public async Task TestOpenSolution_SolutionFileHasEmptyLineBetweenProjectBlock() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.EmptyLineBetweenProjectBlock)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "MSBuild parsing API throws InvalidProjectFileException")] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531283, "DevDiv")] public async Task TestOpenSolution_SolutionFileHasMissingEndProject() { var files = new FileSet( (@"TestSolution1.sln", Resources.SolutionFiles.MissingEndProject1), (@"TestSolution2.sln", Resources.SolutionFiles.MissingEndProject2), (@"TestSolution3.sln", Resources.SolutionFiles.MissingEndProject3)); CreateFiles(files); using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution1.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution2.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution3.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeSelfReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeSelfReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary1)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(2, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var libraryProject = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(libraryProject); Assert.Empty(libraryProject.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeCircularReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeCircularReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary3), (@"Library2\Library2.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary4)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(3, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var library1Project = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(library1Project); Assert.Single(library1Project.AllProjectReferences); var library2Project = solution.Projects.FirstOrDefault(p => p.Name == "Library2"); Assert.NotNull(library2Project); Assert.Empty(library2Project.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithMissingDebugType() { CreateFiles(new FileSet( (@"ProjectLoadErrorOnMissingDebugType.sln", Resources.SolutionFiles.ProjectLoadErrorOnMissingDebugType), (@"ProjectLoadErrorOnMissingDebugType\ProjectLoadErrorOnMissingDebugType.csproj", Resources.ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType))); var solutionFilePath = GetSolutionFileName(@"ProjectLoadErrorOnMissingDebugType.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>1254</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(Encoding.GetEncoding(1254), text.Encoding); // The smart quote (“) in class1.cs shows up as "“" in codepage 1254. Do a sanity // check here to make sure this file hasn't been corrupted in a way that would // impact subsequent asserts. Assert.Equal(5, "//\u00E2\u20AC\u0153".Length); Assert.Equal("//\u00E2\u20AC\u0153".Length, text.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>-1</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty2() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>Broken</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleDefaultCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); Assert.Equal("//\u201C", text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(981208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981208")] [WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")] public void DisposeMSBuildWorkspaceAndServicesCollected() { CreateFiles(GetSimpleCSharpSolutionFiles()); var sol = ObjectReference.CreateFromFactory(() => MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")).Result); var workspace = sol.GetObjectReference(static s => s.Workspace); var project = sol.GetObjectReference(static s => s.Projects.First()); var document = project.GetObjectReference(static p => p.Documents.First()); var tree = document.UseReference(static d => d.GetSyntaxTreeAsync().Result); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); var compilation = document.GetObjectReference(static d => d.GetSemanticModelAsync(CancellationToken.None).Result); Assert.NotNull(compilation); // MSBuildWorkspace doesn't have a cache service Assert.Null(workspace.UseReference(static w => w.CurrentSolution.Services.CacheService)); document.ReleaseStrongReference(); project.ReleaseStrongReference(); workspace.UseReference(static w => w.Dispose()); compilation.AssertReleased(); sol.AssertReleased(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] public async Task MSBuildWorkspacePreservesEncoding() { var encoding = Encoding.BigEndianUnicode; var fileContent = @"//“ class C { }"; var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", encoding.GetBytesWithPreamble(fileContent))); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); // update root without first looking at text (no encoding is known) var gen = Editing.SyntaxGenerator.GetGenerator(document); var doc2 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc2text = await doc2.GetTextAsync(); Assert.Null(doc2text.Encoding); var doc2tree = await doc2.GetSyntaxTreeAsync(); Assert.Null(doc2tree.Encoding); Assert.Null(doc2tree.GetText().Encoding); // observe original text to discover encoding var text = await document.GetTextAsync(); Assert.Equal(encoding.EncodingName, text.Encoding.EncodingName); Assert.Equal(fileContent, text.ToString()); // update root blindly again, after observing encoding, see that now encoding is known var doc3 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc3text = await doc3.GetTextAsync(); Assert.NotNull(doc3text.Encoding); Assert.Equal(encoding.EncodingName, doc3text.Encoding.EncodingName); var doc3tree = await doc3.GetSyntaxTreeAsync(); Assert.Equal(doc3text.Encoding, doc3tree.GetText().Encoding); Assert.Equal(doc3text.Encoding, doc3tree.Encoding); // change doc to have no encoding, still succeeds at writing to disk with old encoding var root = await document.GetSyntaxRootAsync(); var noEncodingDoc = document.WithText(SourceText.From(text.ToString(), encoding: null)); var noEncodingDocText = await noEncodingDoc.GetTextAsync(); Assert.Null(noEncodingDocText.Encoding); // apply changes (this writes the changed document) var noEncodingSolution = noEncodingDoc.Project.Solution; Assert.True(noEncodingSolution.Workspace.TryApplyChanges(noEncodingSolution)); // prove the written document still has the same encoding var filePath = GetSolutionFileName("Class1.cs"); using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var reloadedText = EncodedStringText.Create(stream); Assert.Equal(encoding.EncodingName, reloadedText.Encoding.EncodingName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_GAC() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"System.Xaml")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var mref = MetadataReference.CreateFromFile(typeof(System.Xaml.XamlObjectReader).Assembly.Location); // add reference to System.Xaml workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""System.Xaml,", projFileText); // remove reference to System.Xaml workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""System.Xaml,", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_ReferenceAssembly() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithSystemNumerics)); var csProjFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var csProjFileText = File.ReadAllText(csProjFile); Assert.True(csProjFileText.Contains(@"<Reference Include=""System.Numerics""")); var vbProjFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var vbProjFileText = File.ReadAllText(vbProjFile); Assert.False(vbProjFileText.Contains(@"System.Numerics")); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")); var csProject = solution.Projects.First(p => p.Language == LanguageNames.CSharp); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var numericsMetadata = csProject.MetadataReferences.Single(m => m.Display.Contains("System.Numerics")); // add reference to System.Xaml workspace.TryApplyChanges(vbProject.AddMetadataReference(numericsMetadata).Solution); var newVbProjFileText = File.ReadAllText(vbProjFile); Assert.Contains(@"<Reference Include=""System.Numerics""", newVbProjFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(vbProject.Id).RemoveMetadataReference(numericsMetadata).Solution); var newVbProjFileText2 = File.ReadAllText(vbProjFile); Assert.DoesNotContain(@"<Reference Include=""System.Numerics""", newVbProjFileText2); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_NonGACorRefAssembly() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"References\MyAssembly.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"MyAssembly")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAssemblyPath = GetSolutionFileName(@"References\MyAssembly.dll"); var mref = MetadataReference.CreateFromFile(myAssemblyPath); // add reference to MyAssembly.dll workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""MyAssembly""", projFileText); Assert.Contains(@"<HintPath>..\References\MyAssembly.dll", projFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""MyAssembly""", projFileText); Assert.DoesNotContain(@"<HintPath>..\References\MyAssembly.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveAnalyzerReference() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"Analyzers\MyAnalyzer.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAnalyzerPath = GetSolutionFileName(@"Analyzers\MyAnalyzer.dll"); var aref = new AnalyzerFileReference(myAnalyzerPath, new InMemoryAssemblyLoader()); // add reference to MyAnalyzer.dll workspace.TryApplyChanges(project.AddAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); // remove reference MyAnalyzer.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveProjectReference() { CreateFiles(GetMultiProjectSolutionFiles()); var projFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var projFileText = File.ReadAllText(projFile); Assert.True(projFileText.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var pref = project.ProjectReferences.First(); // remove project reference workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveProjectReference(pref).Solution); Assert.Empty(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); // add it back workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).AddProjectReference(pref).Solution); Assert.Single(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1101040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101040")] public async Task TestOpenProject_BadLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadLink)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var docs = proj.Documents.ToList(); Assert.Equal(3, docs.Count); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadElement() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadElement)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); var project = Assert.Single(solution.Projects); Assert.Empty(project.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_MsbuildError() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MsbuildError)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WildcardsWithLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.Wildcards)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); // prove that the file identified with a wildcard and remapped to a computed link is named correctly. Assert.Contains(proj.Documents, d => d.Name == "AssemblyInfo.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CommandLineArgsHaveNoErrors() { CreateFiles(GetSimpleCSharpSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var loader = workspace.Services .GetLanguageServices(LanguageNames.CSharp) .GetRequiredService<IProjectFileLoader>(); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var buildManager = new ProjectBuildManager(ImmutableDictionary<string, string>.Empty); buildManager.StartBatchBuild(); var projectFile = await loader.LoadProjectFileAsync(projectFilePath, buildManager, CancellationToken.None); var projectFileInfo = (await projectFile.GetProjectFileInfosAsync(CancellationToken.None)).Single(); buildManager.EndBatchBuild(); var commandLineParser = workspace.Services .GetLanguageServices(loader.Language) .GetRequiredService<ICommandLineParserService>(); var projectDirectory = Path.GetDirectoryName(projectFilePath); var commandLineArgs = commandLineParser.Parse( arguments: projectFileInfo.CommandLineArgs, baseDirectory: projectDirectory, isInteractive: false, sdkDirectory: System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()); Assert.Empty(commandLineArgs.Errors); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29122, "https://github.com/dotnet/roslyn/issues/29122")] public async Task TestOpenSolution_ProjectReferencesWithUnconventionalOutputPaths() { CreateFiles(GetBaseFiles() .WithFile(@"TestVB2.sln", Resources.SolutionFiles.Issue29122_Solution) .WithFile(@"Proj1\ClassLibrary1.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary1) .WithFile(@"Proj1\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj1\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj1\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj1\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj1\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj1\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj1\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj1\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings) .WithFile(@"Proj2\ClassLibrary2.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary2) .WithFile(@"Proj2\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj2\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj2\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj2\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj2\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj2\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj2\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj2\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings)); var solutionFilePath = GetSolutionFileName(@"TestVB2.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Neither project should contain any unresolved metadata references foreach (var project in solution.Projects) { Assert.DoesNotContain(project.MetadataReferences, mr => mr is UnresolvedMetadataReference); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29494, "https://github.com/dotnet/roslyn/issues/29494")] public async Task TestOpenProjectAsync_MalformedAdditionalFilePath() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MallformedAdditionalFilePath) .WithFile(@"CSharpProject\ValidAdditionalFile.txt", Resources.SourceFiles.Text.ValidAdditionalFile); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); // Project should open without an exception being thrown. Assert.NotNull(project); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "COM1"); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "TEST::"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(31390, "https://github.com/dotnet/roslyn/issues/31390")] public async Task TestDuplicateProjectAndMetadataReferences() { var files = GetDuplicateProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(fullPath); var project = solution.Projects.Single(p => p.FilePath.EndsWith("CSharpProject_ProjectReference.csproj")); Assert.Single(project.ProjectReferences); AssertEx.Equal( new[] { "EmptyLibrary.dll", "System.Core.dll", "mscorlib.dll" }, project.MetadataReferences.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath)).OrderBy(StringComparer.Ordinal)); var compilation = await project.GetCompilationAsync(); Assert.Single(compilation.References.OfType<CompilationReference>()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscovery() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .WithFile(".editorconfig", "root = true"); CreateFiles(files); var expectedEditorConfigPath = SolutionDirectory.CreateOrOpenFile(".editorconfig").Path; using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); // We should have exactly one .editorconfig corresponding to the file we had. We may also // have other files if there is a .editorconfig floating around somewhere higher on the disk. var analyzerConfigDocument = Assert.Single(project.AnalyzerConfigDocuments.Where(d => d.FilePath == expectedEditorConfigPath)); Assert.Equal(".editorconfig", analyzerConfigDocument.Name); var text = await analyzerConfigDocument.GetTextAsync(); Assert.Equal("root = true", text.ToString()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscoveryDisabled() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DiscoverEditorConfigFiles", "false") .WithFile(".editorconfig", "root = true"); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); Assert.Empty(project.AnalyzerConfigDocuments); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestSolutionFilterSupport() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpSolutionFilter.slnf", Resources.SolutionFilters.CSharp)); var solutionFilePath = GetSolutionFileName(@"CSharpSolutionFilter.slnf"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csharpProject = solution.Projects.Single(); Assert.Equal(LanguageNames.CSharp, csharpProject.Language); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInvalidSolutionFilterDoesNotLoad() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"InvalidSolutionFilter.slnf", Resources.SolutionFilters.Invalid)); var solutionFilePath = GetSolutionFileName(@"InvalidSolutionFilter.slnf"); using var workspace = CreateMSBuildWorkspace(); var exception = await Assert.ThrowsAsync<Exception>(() => workspace.OpenSolutionAsync(solutionFilePath)); Assert.Equal(0, workspace.CurrentSolution.ProjectIds.Count); } private class InMemoryAssemblyLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { var bytes = File.ReadAllBytes(fullPath); return Assembly.Load(bytes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using static Microsoft.CodeAnalysis.CSharp.LanguageVersionFacts; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTests : MSBuildWorkspaceTestBase { [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestCreateMSBuildWorkspace() { using var workspace = CreateMSBuildWorkspace(); Assert.NotNull(workspace); Assert.NotNull(workspace.Services); Assert.NotNull(workspace.Services.Workspace); Assert.Equal(workspace, workspace.Services.Workspace); Assert.NotNull(workspace.Services.HostServices); Assert.NotNull(workspace.Services.PersistentStorage); Assert.NotNull(workspace.Services.TemporaryStorage); Assert.NotNull(workspace.Services.TextFactory); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SingleProjectSolution() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_MultiProjectSolution() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // verify the dependent project has the correct metadata references (and does not include the output for the project references) var references = vbProject.MetadataReferences.ToList(); Assert.Equal(4, references.Count); var fileNames = new HashSet<string>(references.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath))); Assert.Contains("System.Core.dll", fileNames); Assert.Contains("System.dll", fileNames); Assert.Contains("Microsoft.VisualBasic.dll", fileNames); Assert.Contains("mscorlib.dll", fileNames); // the compilation references should have the metadata reference to the csharp project skeleton assembly var compilation = await vbProject.GetCompilationAsync(); var compReferences = compilation.References.ToList(); Assert.Equal(5, compReferences.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/41456"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(2824, "https://github.com/dotnet/roslyn/issues/2824")] public async Task Test_OpenProjectReferencingPortableProject() { var files = new FileSet( (@"CSharpProject\ReferencesPortableProject.csproj", Resources.ProjectFiles.CSharp.ReferencesPortableProject), (@"CSharpProject\Program.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\PortableProject.csproj", Resources.ProjectFiles.CSharp.PortableProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\ReferencesPortableProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); AssertFailures(workspace); var hasFacades = project.MetadataReferences.OfType<PortableExecutableReference>().Any(r => r.FilePath.Contains("Facade")); Assert.True(hasFacades, userMessage: "Expected to find facades in the project references:" + Environment.NewLine + string.Join(Environment.NewLine, project.MetadataReferences.OfType<PortableExecutableReference>().Select(r => r.FilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_SharedMetadataReferences() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var p0 = solution.Projects.ElementAt(0); var p1 = solution.Projects.ElementAt(1); Assert.NotSame(p0, p1); var p0mscorlib = GetMetadataReference(p0, "mscorlib"); var p1mscorlib = GetMetadataReference(p1, "mscorlib"); Assert.NotNull(p0mscorlib); Assert.NotNull(p1mscorlib); // metadata references to mscorlib in both projects are the same Assert.Same(p0mscorlib, p1mscorlib); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task Test_SharedMetadataReferencesWithAliases() { var projPath1 = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var projPath2 = @"CSharpProject\CSharpProject_ExternAlias2.csproj"; var files = new FileSet( (projPath1, Resources.ProjectFiles.CSharp.ExternAlias), (projPath2, Resources.ProjectFiles.CSharp.ExternAlias2), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath1 = GetSolutionFileName(projPath1); var fullPath2 = GetSolutionFileName(projPath2); using var workspace = CreateMSBuildWorkspace(); var proj1 = await workspace.OpenProjectAsync(fullPath1); var proj2 = await workspace.OpenProjectAsync(fullPath2); var p1Sys1 = GetMetadataReferenceByAlias(proj1, "Sys1"); var p1Sys2 = GetMetadataReferenceByAlias(proj1, "Sys2"); var p2Sys1 = GetMetadataReferenceByAlias(proj2, "Sys1"); var p2Sys3 = GetMetadataReferenceByAlias(proj2, "Sys3"); Assert.NotNull(p1Sys1); Assert.NotNull(p1Sys2); Assert.NotNull(p2Sys1); Assert.NotNull(p2Sys3); // same filepath but different alias so they are not the same instance Assert.NotSame(p1Sys1, p1Sys2); Assert.NotSame(p2Sys1, p2Sys3); // same filepath and alias so they are the same instance Assert.Same(p1Sys1, p2Sys1); var mdp1Sys1 = GetMetadata(p1Sys1); var mdp1Sys2 = GetMetadata(p1Sys2); var mdp2Sys1 = GetMetadata(p2Sys1); var mdp2Sys3 = GetMetadata(p2Sys1); Assert.NotNull(mdp1Sys1); Assert.NotNull(mdp1Sys2); Assert.NotNull(mdp2Sys1); Assert.NotNull(mdp2Sys3); // all references to System.dll share the same metadata bytes Assert.Same(mdp1Sys1.Id, mdp1Sys2.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys1.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys3.Id); } private static MetadataReference GetMetadataReference(Project project, string name) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => mr.FilePath.Contains(name)); private static MetadataReference GetMetadataReferenceByAlias(Project project, string aliasName) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => !mr.Properties.Aliases.IsDefault && mr.Properties.Aliases.Contains(aliasName)); private static Metadata GetMetadata(MetadataReference metadataReference) => ((PortableExecutableReference)metadataReference).GetMetadata(); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(552981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552981")] public async Task TestOpenSolution_DuplicateProjectGuids() { CreateFiles(GetSolutionWithDuplicatedGuidFiles()); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(831379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831379")] public async Task GetCompilationWithCircularProjectReferences() { CreateFiles(GetSolutionWithCircularProjectReferences()); var solutionFilePath = GetSolutionFileName("CircularSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Verify we can get compilations for both projects var projects = solution.Projects.ToArray(); // Exactly one of them should have a reference to the other. Which one it is, is unspecced Assert.True(projects[0].ProjectReferences.Any(r => r.ProjectId == projects[1].Id) || projects[1].ProjectReferences.Any(r => r.ProjectId == projects[0].Id)); var compilation1 = await projects[0].GetCompilationAsync(); var compilation2 = await projects[1].GetCompilationAsync(); // Exactly one of them should have a compilation to the other. Which one it is, is unspecced Assert.True(compilation1.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation2) || compilation2.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation1)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOutputFilePaths() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOutputInfo() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.CompilationOutputInfo.AssemblyPath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.CompilationOutputInfo.AssemblyPath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesUsesInMemoryGeneratedMetadata() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); // prove there is no existing metadata on disk for this project Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.False(File.Exists(p1.OutputFilePath)); // prove that vb project refers to csharp project via generated metadata (skeleton) assembly. // it should be a MetadataImageReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "CSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesWithOutOfDateMetadataOnDiskUsesInMemoryGeneratedMetadata() { await PrepareCrossLanguageProjectWithEmittedMetadataAsync(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); // recreate the solution so it will reload from disk using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); // update project with top level change that should now invalidate use of metadata from disk var d1 = p1.Documents.First(); var root = await d1.GetSyntaxRootAsync(); var decl = root.DescendantNodes().OfType<CS.Syntax.ClassDeclarationSyntax>().First(); var newDecl = decl.WithIdentifier(CS.SyntaxFactory.Identifier("Pogrom").WithLeadingTrivia(decl.Identifier.LeadingTrivia).WithTrailingTrivia(decl.Identifier.TrailingTrivia)); var newRoot = root.ReplaceNode(decl, newDecl); var newDoc = d1.WithSyntaxRoot(newRoot); p1 = newDoc.Project; var p2 = p1.Solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // we should now find a MetadataImageReference that was generated instead of a MetadataFileReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "EmittedCSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/54818"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInternalsVisibleToSigned() { var solution = await SolutionAsync( Project( ProjectName("Project1"), Sign, Document(string.Format( @"using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(""Project2, PublicKey={0}"")] class C1 {{ }}", PublicKey))), Project( ProjectName("Project2"), Sign, ProjectReference("Project1"), Document(@"class C2 : C1 { }"))); var project2 = solution.GetProjectsByName("Project2").First(); var compilation = await project2.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning) .ToArray(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestVersions() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var sversion = solution.Version; var latestPV = solution.GetLatestProjectVersion(); var project = solution.Projects.First(); var pversion = project.Version; var document = project.Documents.First(); var dversion = await document.GetTextVersionAsync(); var latestDV = await project.GetLatestDocumentVersionAsync(); // update document var solution1 = solution.WithDocumentText(document.Id, SourceText.From("using test;")); var document1 = solution1.GetDocument(document.Id); var dversion1 = await document1.GetTextVersionAsync(); Assert.NotEqual(dversion, dversion1); // new document version Assert.True(dversion1.GetTestAccessor().IsNewerThan(dversion)); Assert.Equal(solution.Version, solution1.Version); // updating document should not have changed solution version Assert.Equal(project.Version, document1.Project.Version); // updating doc should not have changed project version var latestDV1 = await document1.Project.GetLatestDocumentVersionAsync(); Assert.NotEqual(latestDV, latestDV1); Assert.True(latestDV1.GetTestAccessor().IsNewerThan(latestDV)); Assert.Equal(latestDV1, await document1.GetTextVersionAsync()); // projects latest doc version should be this doc's version // update project var solution2 = solution1.WithProjectCompilationOptions(project.Id, project.CompilationOptions.WithOutputKind(OutputKind.NetModule)); var document2 = solution2.GetDocument(document.Id); var dversion2 = await document2.GetTextVersionAsync(); Assert.Equal(dversion1, dversion2); // document didn't change, so version should be the same. Assert.NotEqual(document1.Project.Version, document2.Project.Version); // project did change, so project versions should be different Assert.True(document2.Project.Version.GetTestAccessor().IsNewerThan(document1.Project.Version)); Assert.Equal(solution1.Version, solution2.Version); // solution didn't change, just individual project. // update solution var pid2 = ProjectId.CreateNewId(); var solution3 = solution2.AddProject(pid2, "foo", "foo", LanguageNames.CSharp); Assert.NotEqual(solution2.Version, solution3.Version); // solution changed, added project. Assert.True(solution3.Version.GetTestAccessor().IsNewerThan(solution2.Version)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_LoadMetadataForReferencedProjects() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformDefault() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformTrue() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(("ShouldUnsetParentConfigurationAndPlatform", bool.TrueString)); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndWinMDObj() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutOutputPath() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutAssemblyName() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_CSharp_WithoutCSharpTargetsImported_DocumentsArePickedUp() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutCSharpTargetsImported)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutVBTargetsImported_DocumentsArePickedUp() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutVBTargetsImported)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndWinMDObj() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutOutputPath() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLanguageVersion15_3() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "15.3")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersion.VisualBasic15_3, ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLatestLanguageVersion() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "Latest")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersionFacts.MapSpecifiedToEffectiveVersion(VB.LanguageVersion.Latest), ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); Assert.Equal(VB.LanguageVersion.Latest, ((VB.VisualBasicParseOptions)project.ParseOptions).SpecifiedLanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutAssemblyName() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(workspace.Diagnostics); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_Respect_ReferenceOutputassembly_Flag() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"VisualBasicProject_Circular_Top.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Top) .WithFile(@"VisualBasicProject_Circular_Target.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Target)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject_Circular_Top.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(project.ProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithXaml() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithXaml) .WithFile(@"CSharpProject\App.xaml", Resources.SourceFiles.Xaml.App) .WithFile(@"CSharpProject\App.xaml.cs", Resources.SourceFiles.CSharp.App) .WithFile(@"CSharpProject\MainWindow.xaml", Resources.SourceFiles.Xaml.MainWindow) .WithFile(@"CSharpProject\MainWindow.xaml.cs", Resources.SourceFiles.CSharp.MainWindow)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // Ensure the Xaml compiler does not run in a separate appdomain. It appears that this won't work within xUnit. using var workspace = CreateMSBuildWorkspace(("AlwaysCompileMarkupFilesInSeparateDomain", "false")); var project = await workspace.OpenProjectAsync(projectFilePath); var documents = project.Documents.ToList(); // AssemblyInfo.cs, App.xaml.cs, MainWindow.xaml.cs, App.g.cs, MainWindow.g.cs, + unusual AssemblyAttributes.cs Assert.Equal(6, documents.Count); // both xaml code behind files are documents Assert.Contains(documents, d => d.Name == "App.xaml.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.xaml.cs"); // prove no xaml files are documents Assert.DoesNotContain(documents, d => d.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase)); // prove that generated source files for xaml files are included in documents list Assert.Contains(documents, d => d.Name == "App.g.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.g.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestMetadataReferenceHasBadHintPath() { // prove that even with bad hint path for metadata reference the workspace can succeed at finding the correct metadata reference. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadHintPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var refs = project.MetadataReferences.ToList(); var csharpLib = refs.OfType<PortableExecutableReference>().FirstOrDefault(r => r.FilePath.Contains("Microsoft.CSharp")); Assert.NotNull(csharpLib); } [ConditionalFact(typeof(VisualStudio16_9_Preview3OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath() { // prove that even if assembly name is specified as a path instead of just a name, workspace still succeeds at opening project. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.GetDirectoryName(project.FilePath); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(project.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath2() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath2)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.Combine(Path.GetDirectoryName(project.FilePath), @"bin"); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(Path.GetFullPath(project.OutputFilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithDuplicateFile() { // Verify that we don't throw in this case CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.DuplicateFile)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var documents = project.Documents.Where(d => d.Name == "CSharpClass.cs").ToList(); Assert.Equal(2, documents.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidFileExtensionAsync() { // make sure the file does in fact exist, but with an unrecognized extension const string ProjFileName = @"CSharpProject\CSharpProject.csproj.nyi"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(ProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var e = await Assert.ThrowsAsync<InvalidOperationException>(async delegate { await MSBuildWorkspace.Create().OpenProjectAsync(GetSolutionFileName(ProjFileName)); }); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, GetSolutionFileName(ProjFileName), ".nyi"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_ProjectFileExtensionAssociatedWithUnknownLanguageAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var language = "lingo"; var e = await Assert.ThrowsAsync<InvalidOperationException>(async delegate { var ws = MSBuildWorkspace.Create(); ws.AssociateFileExtensionWithLanguage("csproj", language); // non-existent language await ws.OpenProjectAsync(projFileName); }); // the exception should tell us something about the language being unrecognized. var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projFileName, language); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension1() { // make a CSharp solution with a project file having the incorrect extension 'vbproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.vbproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); workspace.AssociateFileExtensionWithLanguage("vbproj", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension2_IgnoreCase() { // make a CSharp solution with a project file having the incorrect extension 'anyproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.anyproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.anyproj"); using var workspace = CreateMSBuildWorkspace(); // prove that the association works even if the case is different workspace.AssociateFileExtensionWithLanguage("ANYPROJ", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentSolutionFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("NonExistentSolution.sln"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidSolutionFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidSolution.sln"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithTemporaryLockedFile_SucceedsWithoutFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); using var ws = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await ws.OpenSolutionAsync(GetSolutionFileName(@"TestSolution.sln")); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); // start reading text var getTextTask = doc.GetTextAsync(); // wait 1 unit of retry delay then close file var delay = TextLoader.RetryDelay; await Task.Delay(delay).ContinueWith(t => file.Close(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // finish reading text var text = await getTextTask; Assert.NotEmpty(text.ToString()); } finally { file.Close(); } Assert.Empty(ws.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithLockedFile_FailsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await workspace.OpenSolutionAsync(solutionFilePath); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); var text = await doc.GetTextAsync(); Assert.Empty(text.ToString()); } finally { file.Close(); } Assert.Equal(WorkspaceDiagnosticKind.Failure, workspace.Diagnostics.Single().Kind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [WorkItem(985906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/985906")] [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task HandleSolutionProjectTypeSolutionFolder() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.SolutionFolder)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipFalse_Fails() { // when not skipped we should get an exception for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await Assert.ThrowsAsync<InvalidOperationException>(() => workspace.OpenSolutionAsync(solutionFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipFalse_Fails() { // when skipped we should see an exception for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await Assert.ThrowsAsync<FileNotFoundException>(() => workspace.OpenSolutionAsync(solutionFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectFileExtension_Fails() { // proves that for solution open, project type guid and extension are both necessary CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidButRecognizedExtension_Succeeds() { // proves that if project type guid is not recognized, a known project file extension is all we need. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuid)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipTrue_SucceedsWithFailureEvent() { // proves that if both project type guid and file extension are unrecognized, then project is skipped. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipFalse_FailsAsync() { // proves that if both project type guid and file extension are unrecognized, then open project fails. const string NoProjFileName = @"CSharpProject\CSharpProject.noproj"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(NoProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); var e = await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenSolutionAsync(solutionFilePath); }); var noProjFullFileName = GetSolutionFileName(NoProjFileName); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, noProjFullFileName, ".noproj"); Assert.Equal(expected, e.Message); } private readonly IEnumerable<Assembly> _defaultAssembliesWithoutCSharp = MefHostServices.DefaultAssemblies.Where(a => !a.FullName.Contains("CSharp")); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipFalse_ThrowsAsync() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); var e = await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = false; await workspace.OpenSolutionAsync(solutionFilePath); }); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipTrue_SucceedsWithDiagnostic() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = true; var solution = await workspace.OpenSolutionAsync(solutionFilePath); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, workspace.Diagnostics.Single().Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenProject_WithMissingLanguageLibraries_Throws() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var projectName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = MSBuildWorkspace.Create(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); var e = await Assert.ThrowsAsync<InvalidOperationException>(() => workspace.OpenProjectAsync(projectName)); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectName, ".csproj"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidFilePath_Fails() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidProject.csproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\NonExistentProject.csproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipFalse_FailsAsync() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to unrecognized extension. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipTrue_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); var metaRefs = project.MetadataReferences.ToList(); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipFalse_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); Assert.Contains(project.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_BadMsbuildProject_SkipTrue_SucceedsWithDanglingProjectReference() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.Dlls.CSharpProject)); // use metadata file as stand-in for bad project file var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Single(project.AllProjectReferences); Assert.InRange(workspace.Diagnostics.Count, 2, 3); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_ExistingMetadata_Succeeds() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project got converted to a metadata reference var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Empty(projRefs); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_NonExistentMetadata_LoadsProjectInstead() { CreateFiles(GetMultiProjectSolutionFiles()); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project is still a project ref, did not get converted to metadata ref var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Single(projRefs); Assert.DoesNotContain(metaRefs, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_UpdateExistingReferences() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var vbProjectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var csProjectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; // first open vb project that references c# project, but only reference the c# project's built metadata using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); // prove vb project references c# project as a metadata reference Assert.Empty(vbProject.ProjectReferences); Assert.Contains(vbProject.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); // now explicitly open the c# project that got referenced as metadata var csProject = await workspace.OpenProjectAsync(csProjectFilePath); // show that the vb project now references the c# project directly (not as metadata) vbProject = workspace.CurrentSolution.GetProject(vbProject.Id); Assert.Single(vbProject.ProjectReferences); Assert.DoesNotContain(vbProject.MetadataReferences, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(Framework35Installed))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(528984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528984")] public async Task TestOpenProject_AddVBDefaultReferences() { var files = new FileSet( ("VisualBasicProject_3_5.vbproj", Resources.ProjectFiles.VisualBasic.VisualBasicProject_3_5), ("VisualBasicProject_VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName("VisualBasicProject_3_5.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Full() { CreateCSharpFilesWith("DebugType", "full"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_None() { CreateCSharpFilesWith("DebugType", "none"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_PDBOnly() { CreateCSharpFilesWith("DebugType", "pdbonly"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Portable() { CreateCSharpFilesWith("DebugType", "portable"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Embedded() { CreateCSharpFilesWith("DebugType", "embedded"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_DynamicallyLinkedLibrary() { CreateCSharpFilesWith("OutputType", "Library"); await AssertCSCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_ConsoleApplication() { CreateCSharpFilesWith("OutputType", "Exe"); await AssertCSCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_WindowsApplication() { CreateCSharpFilesWith("OutputType", "WinExe"); await AssertCSCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_NetModule() { CreateCSharpFilesWith("OutputType", "Module"); await AssertCSCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Release() { CreateCSharpFilesWith("Optimize", "True"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Release, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Debug() { CreateCSharpFilesWith("Optimize", "False"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Debug, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_MainFileName() { CreateCSharpFilesWith("StartupObject", "Foo"); await AssertCSCompilationOptionsAsync("Foo", options => options.MainTypeName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_Missing() { CreateCSharpFiles(); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_False() { CreateCSharpFilesWith("SignAssembly", "false"); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_True() { CreateCSharpFilesWith("SignAssembly", "true"); await AssertCSCompilationOptionsAsync("snKey.snk", options => Path.GetFileName(options.CryptoKeyFile)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_False() { CreateCSharpFilesWith("DelaySign", "false"); await AssertCSCompilationOptionsAsync(null, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_True() { CreateCSharpFilesWith("DelaySign", "true"); await AssertCSCompilationOptionsAsync(true, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_True() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "true"); await AssertCSCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_False() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "false"); await AssertCSCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA1() { CreateCSharpFilesWith("LangVersion", "ISO-1"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp1, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA2() { CreateCSharpFilesWith("LangVersion", "ISO-2"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp2, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_None() { CreateCSharpFilesWith("LangVersion", "3"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp3, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_LanguageVersion_Default() { CreateCSharpFiles(); await AssertCSParseOptionsAsync(CS.LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_PreprocessorSymbols() { CreateCSharpFilesWith("DefineConstants", "DEBUG;TRACE;X;Y"); await AssertCSParseOptionsAsync("DEBUG,TRACE,X,Y", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationDebug() { CreateCSharpFiles(); await AssertCSParseOptionsAsync("DEBUG,TRACE", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationRelease() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(("Configuration", "Release")); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); var options = project.ParseOptions; Assert.DoesNotContain(options.PreprocessorSymbolNames, name => name == "DEBUG"); Assert.Contains(options.PreprocessorSymbolNames, name => name == "TRACE"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Full() { CreateVBFilesWith("DebugType", "full"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_None() { CreateVBFilesWith("DebugType", "none"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_PDBOnly() { CreateVBFilesWith("DebugType", "pdbonly"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Portable() { CreateVBFilesWith("DebugType", "portable"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Embedded() { CreateVBFilesWith("DebugType", "embedded"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_VBRuntime_Embed() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.Embed)); await AssertVBCompilationOptionsAsync(true, options => options.EmbedVbCoreRuntime); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_DynamicallyLinkedLibrary() { CreateVBFilesWith("OutputType", "Library"); await AssertVBCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_ConsoleApplication() { CreateVBFilesWith("OutputType", "Exe"); await AssertVBCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_WindowsApplication() { CreateVBFilesWith("OutputType", "WinExe"); await AssertVBCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_NetModule() { CreateVBFilesWith("OutputType", "Module"); await AssertVBCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_RootNamespace() { CreateVBFilesWith("RootNamespace", "Foo.Bar"); await AssertVBCompilationOptionsAsync("Foo.Bar", options => options.RootNamespace); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_On() { CreateVBFilesWith("OptionStrict", "On"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.On, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Off() { CreateVBFilesWith("OptionStrict", "Off"); // The VBC MSBuild task specifies '/optionstrict:custom' rather than '/optionstrict-' // See https://github.com/dotnet/roslyn/blob/58f44c39048032c6b823ddeedddd20fa589912f5/src/Compilers/Core/MSBuildTask/Vbc.cs#L390-L418 for details. await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Custom() { CreateVBFilesWith("OptionStrictType", "Custom"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_True() { CreateVBFilesWith("OptionInfer", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_False() { CreateVBFilesWith("OptionInfer", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_True() { CreateVBFilesWith("OptionExplicit", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_False() { CreateVBFilesWith("OptionExplicit", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_True() { CreateVBFilesWith("OptionCompare", "Text"); await AssertVBCompilationOptionsAsync(true, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_False() { CreateVBFilesWith("OptionCompare", "Binary"); await AssertVBCompilationOptionsAsync(false, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_True() { CreateVBFilesWith("RemoveIntegerChecks", "true"); await AssertVBCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_False() { CreateVBFilesWith("RemoveIntegerChecks", "false"); await AssertVBCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionAssemblyOriginatorKeyFile_SignAssemblyFalse() { CreateVBFilesWith("SignAssembly", "false"); await AssertVBCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_GlobalImports() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicCompilationOptions)project.CompilationOptions; var imports = options.GlobalImports; AssertEx.Equal( expected: new[] { "Microsoft.VisualBasic", "System", "System.Collections", "System.Collections.Generic", "System.Diagnostics", "System.Linq", }, actual: imports.Select(i => i.Name)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_VisualBasic_PreprocessorSymbols() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "X=1,Y=2,Z,T=-1,VBC_VER=123,F=false")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; var defines = new List<KeyValuePair<string, object>>(options.PreprocessorSymbols); defines.Sort((x, y) => x.Key.CompareTo(y.Key)); AssertEx.Equal( expected: new[] { new KeyValuePair<string, object>("_MyType", "Windows"), new KeyValuePair<string, object>("CONFIG", "Debug"), new KeyValuePair<string, object>("DEBUG", -1), new KeyValuePair<string, object>("F", false), new KeyValuePair<string, object>("PLATFORM", "AnyCPU"), new KeyValuePair<string, object>("T", -1), new KeyValuePair<string, object>("TARGET", "library"), new KeyValuePair<string, object>("TRACE", -1), new KeyValuePair<string, object>("VBC_VER", 123), new KeyValuePair<string, object>("X", 1), new KeyValuePair<string, object>("Y", 2), new KeyValuePair<string, object>("Z", true), }, actual: defines); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.True(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeNotEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.False(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.Contains("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeNotEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.DoesNotContain("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithLinkedDocument() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithLink) .WithFile(@"OtherStuff\Foo.cs", Resources.SourceFiles.CSharp.OtherStuff_Foo)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project.Documents.ToList(); var fooDoc = documents.Single(d => d.Name == "Foo.cs"); var folder = Assert.Single(fooDoc.Folders); Assert.Equal("Blah", folder); // prove that the file path is the correct full path to the actual file Assert.Contains("OtherStuff", fooDoc.FilePath); Assert.True(File.Exists(fooDoc.FilePath)); var text = File.ReadAllText(fooDoc.FilePath); Assert.Equal(Resources.SourceFiles.CSharp.OtherStuff_Foo, text); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newText = SourceText.From("public class Bar { }"); workspace.AddDocument(project.Id, new string[] { "NewFolder" }, "Bar.cs", newText); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(4, documents.Count); var document2 = documents.Single(d => d.Name == "Bar.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); Assert.Single(document2.Folders); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check project file on disk var projectFileText = File.ReadAllText(project2.FilePath); Assert.Contains(@"NewFolder\Bar.cs", projectFileText); // reload project & solution to prove project file change was good using var workspaceB = CreateMSBuildWorkspace(); var solutionB = await workspaceB.OpenSolutionAsync(solutionFilePath); var projectB = workspaceB.CurrentSolution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documentsB = projectB.Documents.ToList(); Assert.Equal(4, documentsB.Count); var documentB = documentsB.Single(d => d.Name == "Bar.cs"); Assert.Single(documentB.Folders); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestUpdateDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); var newText = SourceText.From("public class Bar { }"); workspace.TryApplyChanges(solution.WithDocumentText(document.Id, newText, PreservationMode.PreserveIdentity)); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(3, documents.Count); var document2 = documents.Single(d => d.Name == "CSharpClass.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestRemoveDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); workspace.RemoveDocument(document.Id); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); Assert.DoesNotContain(project2.Documents, d => d.Name == "CSharpClass.cs"); // check actual file on disk... Assert.False(File.Exists(document.FilePath)); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateDocumentText() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().Documents.ToList(); var document = documents.Single(d => d.Name.Contains("CSharpClass")); var text = await document.GetTextAsync(); var newText = SourceText.From("using System.Diagnostics;\r\n" + text.ToString()); var newSolution = solution.WithDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateAdditionalDocumentText() { CreateFiles(GetSimpleCSharpSolutionWithAdditionaFile()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().AdditionalDocuments.ToList(); var document = documents.Single(d => d.Name.Contains("ValidAdditionalFile")); var text = await document.GetTextAsync(); var newText = SourceText.From("New Text In Additional File.\r\n" + text.ToString()); var newSolution = solution.WithAdditionalDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetAdditionalDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_AddDocument() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newDocId = DocumentId.CreateNewId(project.Id); var newText = SourceText.From("public class Bar { }"); var newSolution = solution.AddDocument(newDocId, "Bar.cs", newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(newDocId); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_NotSupportedChangesFail() { var csharpProjPath = @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"; var vbProjPath = @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj"; CreateFiles(GetAnalyzerReferenceSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var csProjectFilePath = GetSolutionFileName(csharpProjPath); var csProject = await workspace.OpenProjectAsync(csProjectFilePath); var csProjectId = csProject.Id; var vbProjectFilePath = GetSolutionFileName(vbProjPath); var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); var vbProjectId = vbProject.Id; // adding additional documents not supported. Assert.False(workspace.CanApplyChange(ApplyChangesKind.AddAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.AddAdditionalDocument(DocumentId.CreateNewId(csProjectId), "foo.xaml", SourceText.From("<foo></foo>"))); }); var xaml = workspace.CurrentSolution.GetProject(csProjectId).AdditionalDocuments.FirstOrDefault(d => d.Name == "XamlFile.xaml"); Assert.NotNull(xaml); // removing additional documents not supported Assert.False(workspace.CanApplyChange(ApplyChangesKind.RemoveAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.RemoveAdditionalDocument(xaml.Id)); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWaiter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWaiter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedWeakEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWanter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges( workspace .CurrentSolution .WithDocumentText( doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWanter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(529276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529276"), WorkItem(12086, "DevDiv_Projects/Roslyn")] public async Task TestOpenProject_LoadMetadataForReferenceProjects_NoMetadata() { var projPath = @"CSharpProject\CSharpProject_ProjectReference.csproj"; var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var projectFullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var proj = await workspace.OpenProjectAsync(projectFullPath); // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); // and all is well var comp = await proj.GetCompilationAsync(); var errs = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error); Assert.Empty(errs); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(918072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918072")] public async Task TestAnalyzerReferenceLoadStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); Assert.Equal(1, proj.AnalyzerReferences.Count); var analyzerReference = proj.AnalyzerReferences[0] as AnalyzerFileReference; Assert.NotNull(analyzerReference); Assert.True(analyzerReference.FullPath.EndsWith("CSharpProject.dll", StringComparison.OrdinalIgnoreCase)); } // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAdditionalFilesStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = Assert.Single(proj.AdditionalDocuments); Assert.Equal("XamlFile.xaml", doc.Name); var text = await doc.GetTextAsync(); Assert.Contains("Window", text.ToString(), StringComparison.Ordinal); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestLoadTextSync() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = new AdhocWorkspace(MSBuildMefHostServices.DefaultServices, WorkspaceKind.MSBuild); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var loader = new MSBuildProjectLoader(workspace); var infos = await loader.LoadProjectInfoAsync(projectFullPath); var doc = infos[0].Documents[0]; var tav = doc.TextLoader.LoadTextAndVersionSynchronously(workspace, doc.Id, CancellationToken.None); var adoc = infos[0].AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atav = adoc.TextLoader.LoadTextAndVersionSynchronously(workspace, adoc.Id, CancellationToken.None); Assert.Contains("Window", atav.Text.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestGetTextSynchronously() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = proj.Documents.First(); var text = doc.State.GetTextSynchronously(CancellationToken.None); var adoc = proj.AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atext = adoc.State.GetTextSynchronously(CancellationToken.None); Assert.Contains("Window", atext.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task TestCSharpExternAlias() { var projPath = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var files = new FileSet( (projPath, Resources.ProjectFiles.CSharp.ExternAlias), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(fullPath); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(530337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530337")] public async Task TestProjectReferenceWithExternAlias() { var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); var proj = sol.Projects.First(); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithReferenceOutputAssemblyFalse() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Add(new XElement(XName.Get("ReferenceOutputAssembly", MSBuildNamespace), "false"))); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.Empty(project.ProjectReferences); } } private static FileSet VisitProjectReferences(FileSet files, Action<XElement> visitProjectReference) { var result = new List<(string, object)>(); foreach (var (fileName, fileContent) in files) { var text = fileContent.ToString(); if (fileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase)) { text = VisitProjectReferences(text, visitProjectReference); } result.Add((fileName, text)); } return new FileSet(result.ToArray()); } private static string VisitProjectReferences(string projectFileText, Action<XElement> visitProjectReference) { var document = XDocument.Parse(projectFileText); var projectReferenceItems = document.Descendants(XName.Get("ProjectReference", MSBuildNamespace)); foreach (var projectReferenceItem in projectReferenceItems) { visitProjectReference(projectReferenceItem); } return document.ToString(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithNoGuid() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Elements(XName.Get("Project", MSBuildNamespace)).Remove()); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.InRange(project.ProjectReferences.Count(), 0, 1); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/23685"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(5668, "https://github.com/dotnet/roslyn/issues/5668")] public async Task TestOpenProject_MetadataReferenceHasDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("System.Console"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_HasSourceDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var parseOptions = (CS.CSharpParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Parse, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_HasSourceDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var parseOptions = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CrossLanguageSkeletonReferenceHasDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.CSharp); var csoptions = (CS.CSharpParseOptions)csproject.ParseOptions; Assert.Equal(DocumentationMode.Parse, csoptions.DocumentationMode); var cscomp = await csproject.GetCompilationAsync(); var cssymbol = cscomp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var cscomment = cssymbol.GetDocumentationCommentXml(); Assert.NotNull(cscomment); var vbproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var vboptions = (VB.VisualBasicParseOptions)vbproject.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, vboptions.DocumentationMode); var vbcomp = await vbproject.GetCompilationAsync(); var vbsymbol = vbcomp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var parent = vbsymbol.BaseType; // this is the vb imported version of the csharp symbol var vbcomment = parent.GetDocumentationCommentXml(); Assert.Equal(cscomment, vbcomment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithProjectFileLockedAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using (File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite)) { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFile); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.Contains("The process cannot access the file", diagnostic.Message); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectFileAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\NoProject.csproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFile); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentSolutionFileAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var solutionFile = GetSolutionFileName(@"NoSolution.sln"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFile); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SolutionFileHasEmptyLinesAndWhitespaceOnlyLines() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.CSharp_EmptyLines), (@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.CSharpProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\Properties\AssemblyInfo.cs", Resources.SourceFiles.CSharp.AssemblyInfo)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531543")] public async Task TestOpenSolution_SolutionFileHasEmptyLineBetweenProjectBlock() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.EmptyLineBetweenProjectBlock)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "MSBuild parsing API throws InvalidProjectFileException")] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531283, "DevDiv")] public async Task TestOpenSolution_SolutionFileHasMissingEndProject() { var files = new FileSet( (@"TestSolution1.sln", Resources.SolutionFiles.MissingEndProject1), (@"TestSolution2.sln", Resources.SolutionFiles.MissingEndProject2), (@"TestSolution3.sln", Resources.SolutionFiles.MissingEndProject3)); CreateFiles(files); using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution1.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution2.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution3.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeSelfReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeSelfReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary1)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(2, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var libraryProject = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(libraryProject); Assert.Empty(libraryProject.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeCircularReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeCircularReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary3), (@"Library2\Library2.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary4)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(3, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var library1Project = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(library1Project); Assert.Single(library1Project.AllProjectReferences); var library2Project = solution.Projects.FirstOrDefault(p => p.Name == "Library2"); Assert.NotNull(library2Project); Assert.Empty(library2Project.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithMissingDebugType() { CreateFiles(new FileSet( (@"ProjectLoadErrorOnMissingDebugType.sln", Resources.SolutionFiles.ProjectLoadErrorOnMissingDebugType), (@"ProjectLoadErrorOnMissingDebugType\ProjectLoadErrorOnMissingDebugType.csproj", Resources.ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType))); var solutionFilePath = GetSolutionFileName(@"ProjectLoadErrorOnMissingDebugType.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>1254</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(Encoding.GetEncoding(1254), text.Encoding); // The smart quote (“) in class1.cs shows up as "“" in codepage 1254. Do a sanity // check here to make sure this file hasn't been corrupted in a way that would // impact subsequent asserts. Assert.Equal(5, "//\u00E2\u20AC\u0153".Length); Assert.Equal("//\u00E2\u20AC\u0153".Length, text.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>-1</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty2() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>Broken</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleDefaultCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); Assert.Equal("//\u201C", text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(981208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981208")] [WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")] public void DisposeMSBuildWorkspaceAndServicesCollected() { CreateFiles(GetSimpleCSharpSolutionFiles()); var sol = ObjectReference.CreateFromFactory(() => MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")).Result); var workspace = sol.GetObjectReference(static s => s.Workspace); var project = sol.GetObjectReference(static s => s.Projects.First()); var document = project.GetObjectReference(static p => p.Documents.First()); var tree = document.UseReference(static d => d.GetSyntaxTreeAsync().Result); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); var compilation = document.GetObjectReference(static d => d.GetSemanticModelAsync(CancellationToken.None).Result); Assert.NotNull(compilation); // MSBuildWorkspace doesn't have a cache service Assert.Null(workspace.UseReference(static w => w.CurrentSolution.Services.CacheService)); document.ReleaseStrongReference(); project.ReleaseStrongReference(); workspace.UseReference(static w => w.Dispose()); compilation.AssertReleased(); sol.AssertReleased(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] public async Task MSBuildWorkspacePreservesEncoding() { var encoding = Encoding.BigEndianUnicode; var fileContent = @"//“ class C { }"; var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", encoding.GetBytesWithPreamble(fileContent))); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); // update root without first looking at text (no encoding is known) var gen = Editing.SyntaxGenerator.GetGenerator(document); var doc2 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc2text = await doc2.GetTextAsync(); Assert.Null(doc2text.Encoding); var doc2tree = await doc2.GetSyntaxTreeAsync(); Assert.Null(doc2tree.Encoding); Assert.Null(doc2tree.GetText().Encoding); // observe original text to discover encoding var text = await document.GetTextAsync(); Assert.Equal(encoding.EncodingName, text.Encoding.EncodingName); Assert.Equal(fileContent, text.ToString()); // update root blindly again, after observing encoding, see that now encoding is known var doc3 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc3text = await doc3.GetTextAsync(); Assert.NotNull(doc3text.Encoding); Assert.Equal(encoding.EncodingName, doc3text.Encoding.EncodingName); var doc3tree = await doc3.GetSyntaxTreeAsync(); Assert.Equal(doc3text.Encoding, doc3tree.GetText().Encoding); Assert.Equal(doc3text.Encoding, doc3tree.Encoding); // change doc to have no encoding, still succeeds at writing to disk with old encoding var root = await document.GetSyntaxRootAsync(); var noEncodingDoc = document.WithText(SourceText.From(text.ToString(), encoding: null)); var noEncodingDocText = await noEncodingDoc.GetTextAsync(); Assert.Null(noEncodingDocText.Encoding); // apply changes (this writes the changed document) var noEncodingSolution = noEncodingDoc.Project.Solution; Assert.True(noEncodingSolution.Workspace.TryApplyChanges(noEncodingSolution)); // prove the written document still has the same encoding var filePath = GetSolutionFileName("Class1.cs"); using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var reloadedText = EncodedStringText.Create(stream); Assert.Equal(encoding.EncodingName, reloadedText.Encoding.EncodingName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_GAC() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"System.Xaml")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var mref = MetadataReference.CreateFromFile(typeof(System.Xaml.XamlObjectReader).Assembly.Location); // add reference to System.Xaml workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""System.Xaml,", projFileText); // remove reference to System.Xaml workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""System.Xaml,", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_ReferenceAssembly() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithSystemNumerics)); var csProjFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var csProjFileText = File.ReadAllText(csProjFile); Assert.True(csProjFileText.Contains(@"<Reference Include=""System.Numerics""")); var vbProjFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var vbProjFileText = File.ReadAllText(vbProjFile); Assert.False(vbProjFileText.Contains(@"System.Numerics")); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")); var csProject = solution.Projects.First(p => p.Language == LanguageNames.CSharp); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var numericsMetadata = csProject.MetadataReferences.Single(m => m.Display.Contains("System.Numerics")); // add reference to System.Xaml workspace.TryApplyChanges(vbProject.AddMetadataReference(numericsMetadata).Solution); var newVbProjFileText = File.ReadAllText(vbProjFile); Assert.Contains(@"<Reference Include=""System.Numerics""", newVbProjFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(vbProject.Id).RemoveMetadataReference(numericsMetadata).Solution); var newVbProjFileText2 = File.ReadAllText(vbProjFile); Assert.DoesNotContain(@"<Reference Include=""System.Numerics""", newVbProjFileText2); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_NonGACorRefAssembly() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"References\MyAssembly.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"MyAssembly")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAssemblyPath = GetSolutionFileName(@"References\MyAssembly.dll"); var mref = MetadataReference.CreateFromFile(myAssemblyPath); // add reference to MyAssembly.dll workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""MyAssembly""", projFileText); Assert.Contains(@"<HintPath>..\References\MyAssembly.dll", projFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""MyAssembly""", projFileText); Assert.DoesNotContain(@"<HintPath>..\References\MyAssembly.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveAnalyzerReference() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"Analyzers\MyAnalyzer.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAnalyzerPath = GetSolutionFileName(@"Analyzers\MyAnalyzer.dll"); var aref = new AnalyzerFileReference(myAnalyzerPath, new InMemoryAssemblyLoader()); // add reference to MyAnalyzer.dll workspace.TryApplyChanges(project.AddAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); // remove reference MyAnalyzer.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveProjectReference() { CreateFiles(GetMultiProjectSolutionFiles()); var projFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var projFileText = File.ReadAllText(projFile); Assert.True(projFileText.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var pref = project.ProjectReferences.First(); // remove project reference workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveProjectReference(pref).Solution); Assert.Empty(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); // add it back workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).AddProjectReference(pref).Solution); Assert.Single(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1101040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101040")] public async Task TestOpenProject_BadLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadLink)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var docs = proj.Documents.ToList(); Assert.Equal(3, docs.Count); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadElement() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadElement)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); var project = Assert.Single(solution.Projects); Assert.Empty(project.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_MsbuildError() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MsbuildError)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WildcardsWithLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.Wildcards)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); // prove that the file identified with a wildcard and remapped to a computed link is named correctly. Assert.Contains(proj.Documents, d => d.Name == "AssemblyInfo.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CommandLineArgsHaveNoErrors() { CreateFiles(GetSimpleCSharpSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var loader = workspace.Services .GetLanguageServices(LanguageNames.CSharp) .GetRequiredService<IProjectFileLoader>(); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var buildManager = new ProjectBuildManager(ImmutableDictionary<string, string>.Empty); buildManager.StartBatchBuild(); var projectFile = await loader.LoadProjectFileAsync(projectFilePath, buildManager, CancellationToken.None); var projectFileInfo = (await projectFile.GetProjectFileInfosAsync(CancellationToken.None)).Single(); buildManager.EndBatchBuild(); var commandLineParser = workspace.Services .GetLanguageServices(loader.Language) .GetRequiredService<ICommandLineParserService>(); var projectDirectory = Path.GetDirectoryName(projectFilePath); var commandLineArgs = commandLineParser.Parse( arguments: projectFileInfo.CommandLineArgs, baseDirectory: projectDirectory, isInteractive: false, sdkDirectory: System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()); Assert.Empty(commandLineArgs.Errors); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29122, "https://github.com/dotnet/roslyn/issues/29122")] public async Task TestOpenSolution_ProjectReferencesWithUnconventionalOutputPaths() { CreateFiles(GetBaseFiles() .WithFile(@"TestVB2.sln", Resources.SolutionFiles.Issue29122_Solution) .WithFile(@"Proj1\ClassLibrary1.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary1) .WithFile(@"Proj1\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj1\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj1\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj1\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj1\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj1\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj1\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj1\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings) .WithFile(@"Proj2\ClassLibrary2.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary2) .WithFile(@"Proj2\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj2\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj2\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj2\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj2\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj2\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj2\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj2\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings)); var solutionFilePath = GetSolutionFileName(@"TestVB2.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Neither project should contain any unresolved metadata references foreach (var project in solution.Projects) { Assert.DoesNotContain(project.MetadataReferences, mr => mr is UnresolvedMetadataReference); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29494, "https://github.com/dotnet/roslyn/issues/29494")] public async Task TestOpenProjectAsync_MalformedAdditionalFilePath() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MallformedAdditionalFilePath) .WithFile(@"CSharpProject\ValidAdditionalFile.txt", Resources.SourceFiles.Text.ValidAdditionalFile); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); // Project should open without an exception being thrown. Assert.NotNull(project); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "COM1"); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "TEST::"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(31390, "https://github.com/dotnet/roslyn/issues/31390")] public async Task TestDuplicateProjectAndMetadataReferences() { var files = GetDuplicateProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(fullPath); var project = solution.Projects.Single(p => p.FilePath.EndsWith("CSharpProject_ProjectReference.csproj")); Assert.Single(project.ProjectReferences); AssertEx.Equal( new[] { "EmptyLibrary.dll", "System.Core.dll", "mscorlib.dll" }, project.MetadataReferences.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath)).OrderBy(StringComparer.Ordinal)); var compilation = await project.GetCompilationAsync(); Assert.Single(compilation.References.OfType<CompilationReference>()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscovery() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .WithFile(".editorconfig", "root = true"); CreateFiles(files); var expectedEditorConfigPath = SolutionDirectory.CreateOrOpenFile(".editorconfig").Path; using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); // We should have exactly one .editorconfig corresponding to the file we had. We may also // have other files if there is a .editorconfig floating around somewhere higher on the disk. var analyzerConfigDocument = Assert.Single(project.AnalyzerConfigDocuments.Where(d => d.FilePath == expectedEditorConfigPath)); Assert.Equal(".editorconfig", analyzerConfigDocument.Name); var text = await analyzerConfigDocument.GetTextAsync(); Assert.Equal("root = true", text.ToString()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscoveryDisabled() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DiscoverEditorConfigFiles", "false") .WithFile(".editorconfig", "root = true"); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); Assert.Empty(project.AnalyzerConfigDocuments); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestSolutionFilterSupport() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpSolutionFilter.slnf", Resources.SolutionFilters.CSharp)); var solutionFilePath = GetSolutionFileName(@"CSharpSolutionFilter.slnf"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csharpProject = solution.Projects.Single(); Assert.Equal(LanguageNames.CSharp, csharpProject.Language); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInvalidSolutionFilterDoesNotLoad() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"InvalidSolutionFilter.slnf", Resources.SolutionFilters.Invalid)); var solutionFilePath = GetSolutionFileName(@"InvalidSolutionFilter.slnf"); using var workspace = CreateMSBuildWorkspace(); var exception = await Assert.ThrowsAsync<Exception>(() => workspace.OpenSolutionAsync(solutionFilePath)); Assert.Equal(0, workspace.CurrentSolution.ProjectIds.Count); } private class InMemoryAssemblyLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { var bytes = File.ReadAllBytes(fullPath); return Assembly.Load(bytes); } } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Features/CSharp/Portable/AssignOutParameters/AssignOutParametersAboveReturnCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.AssignOutParameters { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AssignOutParametersAboveReturn), Shared] internal class AssignOutParametersAboveReturnCodeFixProvider : AbstractAssignOutParametersCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AssignOutParametersAboveReturnCodeFixProvider() { } protected override void TryRegisterFix(CodeFixContext context, Document document, SyntaxNode container, SyntaxNode location) { context.RegisterCodeFix(new MyCodeAction( CSharpFeaturesResources.Assign_out_parameters, c => FixAsync(document, context.Diagnostics[0], c)), context.Diagnostics); } protected override void AssignOutParameters( SyntaxEditor editor, SyntaxNode container, MultiDictionary<SyntaxNode, (SyntaxNode exprOrStatement, ImmutableArray<IParameterSymbol> unassignedParameters)>.ValueSet values, CancellationToken cancellationToken) { foreach (var (exprOrStatement, unassignedParameters) in values) { var statements = GenerateAssignmentStatements(editor.Generator, unassignedParameters); AddAssignmentStatements(editor, exprOrStatement, statements); } } private static void AddAssignmentStatements( SyntaxEditor editor, SyntaxNode exprOrStatement, ImmutableArray<SyntaxNode> statements) { var generator = editor.Generator; if (exprOrStatement is LocalFunctionStatementSyntax { ExpressionBody: { } localFunctionExpressionBody }) { // Expression-bodied local functions report CS0177 on the method name instead of the expression. // Reassign exprOrStatement so the code fix implementation works as it does for other expression-bodied // members. exprOrStatement = localFunctionExpressionBody.Expression; } var parent = exprOrStatement.Parent; if (parent.IsEmbeddedStatementOwner()) { var newBody = editor.Generator.ScopeBlock(statements.Add(exprOrStatement)); editor.ReplaceNode(exprOrStatement, newBody); editor.ReplaceNode( exprOrStatement.Parent, (c, _) => c.WithAdditionalAnnotations(Formatter.Annotation)); } else if (parent is BlockSyntax || parent is SwitchSectionSyntax) { editor.InsertBefore(exprOrStatement, statements); } else if (parent is ArrowExpressionClauseSyntax) { statements = statements.Add(generator.ReturnStatement(exprOrStatement)); editor.ReplaceNode( parent.Parent, generator.WithStatements(parent.Parent, statements)); } else { var lambda = (LambdaExpressionSyntax)parent; var newBody = editor.Generator.ScopeBlock(statements.Add(generator.ReturnStatement(exprOrStatement))); editor.ReplaceNode( lambda, lambda.WithBody((CSharpSyntaxNode)newBody) .WithAdditionalAnnotations(Formatter.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; using System.Collections.Immutable; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.AssignOutParameters { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AssignOutParametersAboveReturn), Shared] internal class AssignOutParametersAboveReturnCodeFixProvider : AbstractAssignOutParametersCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AssignOutParametersAboveReturnCodeFixProvider() { } protected override void TryRegisterFix(CodeFixContext context, Document document, SyntaxNode container, SyntaxNode location) { context.RegisterCodeFix(new MyCodeAction( CSharpFeaturesResources.Assign_out_parameters, c => FixAsync(document, context.Diagnostics[0], c)), context.Diagnostics); } protected override void AssignOutParameters( SyntaxEditor editor, SyntaxNode container, MultiDictionary<SyntaxNode, (SyntaxNode exprOrStatement, ImmutableArray<IParameterSymbol> unassignedParameters)>.ValueSet values, CancellationToken cancellationToken) { foreach (var (exprOrStatement, unassignedParameters) in values) { var statements = GenerateAssignmentStatements(editor.Generator, unassignedParameters); AddAssignmentStatements(editor, exprOrStatement, statements); } } private static void AddAssignmentStatements( SyntaxEditor editor, SyntaxNode exprOrStatement, ImmutableArray<SyntaxNode> statements) { var generator = editor.Generator; if (exprOrStatement is LocalFunctionStatementSyntax { ExpressionBody: { } localFunctionExpressionBody }) { // Expression-bodied local functions report CS0177 on the method name instead of the expression. // Reassign exprOrStatement so the code fix implementation works as it does for other expression-bodied // members. exprOrStatement = localFunctionExpressionBody.Expression; } var parent = exprOrStatement.Parent; if (parent.IsEmbeddedStatementOwner()) { var newBody = editor.Generator.ScopeBlock(statements.Add(exprOrStatement)); editor.ReplaceNode(exprOrStatement, newBody); editor.ReplaceNode( exprOrStatement.Parent, (c, _) => c.WithAdditionalAnnotations(Formatter.Annotation)); } else if (parent is BlockSyntax || parent is SwitchSectionSyntax) { editor.InsertBefore(exprOrStatement, statements); } else if (parent is ArrowExpressionClauseSyntax) { statements = statements.Add(generator.ReturnStatement(exprOrStatement)); editor.ReplaceNode( parent.Parent, generator.WithStatements(parent.Parent, statements)); } else { var lambda = (LambdaExpressionSyntax)parent; var newBody = editor.Generator.ScopeBlock(statements.Add(generator.ReturnStatement(exprOrStatement))); editor.ReplaceNode( lambda, lambda.WithBody((CSharpSyntaxNode)newBody) .WithAdditionalAnnotations(Formatter.Annotation)); } } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../BasicVSResources.resx"> <body> <trans-unit id="Add_missing_imports_on_paste"> <source>Add missing imports on paste</source> <target state="translated">Agregar las importaciones que faltan al pegar</target> <note>'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</source> <target state="translated">En los operadores relacionales: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</target> <note /> </trans-unit> <trans-unit id="Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments"> <source>Insert ' at the start of new lines when writing ' comments</source> <target state="translated">Insertar ' al comienzo de las líneas nuevas al escribir comentarios '</target> <note /> </trans-unit> <trans-unit id="Microsoft_Visual_Basic"> <source>Microsoft Visual Basic</source> <target state="translated">Microsoft Visual Basic</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">Insertar fragmento de código</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="Automatic_insertion_of_Interface_and_MustOverride_members"> <source>Automatic _insertion of Interface and MustOverride members</source> <target state="translated">I_nserción automática de miembros Interface y MustOverride</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Nunca</target> <note /> </trans-unit> <trans-unit id="Prefer_IsNot_expression"> <source>Prefer 'IsNot' expression</source> <target state="translated">Anteponer expresión "IsNot"</target> <note /> </trans-unit> <trans-unit id="Prefer_Is_Nothing_for_reference_equality_checks"> <source>Prefer 'Is Nothing' for reference equality checks</source> <target state="translated">Preferir “Is Nothing” para comprobaciones de igualdad de referencias</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_object_creation"> <source>Prefer simplified object creation</source> <target state="translated">Preferir la creación de objetos simplificados</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_Imports"> <source>Remove unnecessary Imports</source> <target state="translated">Quitar instrucciones Import innecesarias</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Show_hints_for_New_expressions"> <source>Show hints for 'New' expressions</source> <target state="translated">Mostrar sugerencias para las expresiones "new"</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">Mostrar elementos de espacios de nombres no importados</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">Mo_strar separadores de líneas de procedimientos</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ByRef_on_custom_structure"> <source>_Don't put ByRef on custom structure</source> <target state="translated">_No poner ByRef en una estructura personalizada</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">Ayuda de editor</target> <note /> </trans-unit> <trans-unit id="A_utomatic_insertion_of_end_constructs"> <source>A_utomatic insertion of end constructs</source> <target state="translated">Inserción a_utomática de construcciones end</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">Resaltar palabras cla_ve relacionadas bajo el cursor</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">_Resaltar referencias al símbolo bajo el cursor</target> <note /> </trans-unit> <trans-unit id="Pretty_listing_reformatting_of_code"> <source>_Pretty listing (reformatting) of code</source> <target state="translated">_Lista descriptiva (nuevo formato) de código</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>_Enter outlining mode when files open</source> <target state="translated">_Especificar el modo de esquematización al abrir los archivos</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Extraer método</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for '''</source> <target state="translated">_Generar comentarios de documentación XML con '''</target> <note>{Locked="'''"} "'''" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">Resaltar</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">Optimizar para tamaño de la solución</target> <note /> </trans-unit> <trans-unit id="Large"> <source>Large</source> <target state="translated">Grande</target> <note /> </trans-unit> <trans-unit id="Regular"> <source>Regular</source> <target state="translated">Normal</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">Mostrar comentarios en Información rápida</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">Pequeño</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">Rendimiento</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">Mostrar vista previa para _seguimiento de cambio de nombre</target> <note /> </trans-unit> <trans-unit id="Navigate_to_Object_Browser_for_symbols_defined_in_metadata"> <source>_Navigate to Object Browser for symbols defined in metadata</source> <target state="translated">_Vaya al Examinador de objetos para obtener los símbolos definidos en los metadatos</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Ir a definición</target> <note /> </trans-unit> <trans-unit id="Import_Directives"> <source>Import Directives</source> <target state="translated">Directivas de importación</target> <note /> </trans-unit> <trans-unit id="Sort_imports"> <source>Sort imports</source> <target state="translated">Ordenar instrucciones Import</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_NuGet_packages"> <source>Suggest imports for types in _NuGet packages</source> <target state="translated">Sugerir importaciones para tipos de paquetes _NuGet</target> <note /> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_reference_assemblies"> <source>Suggest imports for types in _reference assemblies</source> <target state="translated">Sugerir importaciones para tipos de ensamblados de r_eferencia</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_imports"> <source>_Place 'System' directives first when sorting imports</source> <target state="translated">_Poner directivas del sistema en primer lugar cuando se ordenen las importaciones</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_Me"> <source>Qualify event access with 'Me'</source> <target state="translated">Calificar el acceso a eventos con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_Me"> <source>Qualify field access with 'Me'</source> <target state="translated">Calificar el acceso a campos con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_Me"> <source>Qualify method access with 'Me'</source> <target state="translated">Calificar el acceso a métodos con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_Me"> <source>Qualify property access with 'Me'</source> <target state="translated">Calificar el acceso a propiedades con 'Me'</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_Me"> <source>Do not prefer 'Me.'</source> <target state="translated">No preferir 'Me.'</target> <note /> </trans-unit> <trans-unit id="Prefer_Me"> <source>Prefer 'Me.'</source> <target state="translated">Preferir 'Me.'</target> <note /> </trans-unit> <trans-unit id="Me_preferences_colon"> <source>'Me.' preferences:</source> <target state="translated">'Preferencias de "Me.":</target> <note /> </trans-unit> <trans-unit id="Predefined_type_preferences_colon"> <source>Predefined type preferences:</source> <target state="translated">Preferencias de tipos predefinidos:</target> <note /> </trans-unit> <trans-unit id="Highlight_matching_portions_of_completion_list_items"> <source>_Highlight matching portions of completion list items</source> <target state="translated">_Resaltar partes coincidentes de elementos de lista de finalización</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">Mostrar _filtros de elementos de finalización</target> <note /> </trans-unit> <trans-unit id="Completion_Lists"> <source>Completion Lists</source> <target state="translated">Listas de finalización</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Comportamiento de la tecla Entrar:</target> <note /> </trans-unit> <trans-unit id="Only_add_new_line_on_enter_after_end_of_fully_typed_word"> <source>_Only add new line on enter after end of fully typed word</source> <target state="translated">_Agregar solo una nueva línea con Entrar al final de palabras</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">_Agregar siempre una nueva línea al presionar Entrar</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">_No agregar nunca una nueva línea al presionar Entrar</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">Incluir siempre fragmentos de código</target> <note /> </trans-unit> <trans-unit id="Include_snippets_when_Tab_is_typed_after_an_identifier"> <source>Include snippets when ?-Tab is typed after an identifier</source> <target state="translated">Incluir fragmentos de código cuando ?-Tab se escriba después de un identificador</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">No incluir nunca fragmentos de código</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">Comportamiento de los fragmentos de código</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_deleted"> <source>Show completion list after a character is _deleted</source> <target state="translated">Mostrar lista de finalización después de _eliminar un carácter</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_typed"> <source>_Show completion list after a character is typed</source> <target state="translated">_Mostrar lista de finalización después de escribir un carácter</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Local sin uso</target> <note /> </trans-unit> <trans-unit id="VB_Coding_Conventions"> <source>VB Coding Conventions</source> <target state="translated">Convenciones de código de VB</target> <note /> </trans-unit> <trans-unit id="nothing_checking_colon"> <source>'nothing' checking:</source> <target state="translated">'Comprobación de "nothing":</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_imports"> <source>Fade out unused imports</source> <target state="translated">Atenuar importaciones no utilizadas</target> <note /> </trans-unit> <trans-unit id="Report_invalid_placeholders_in_string_dot_format_calls"> <source>Report invalid placeholders in 'String.Format' calls</source> <target state="translated">Informar sobre marcadores de posición no válidos en llamadas a "String.Format"</target> <note /> </trans-unit> <trans-unit id="Separate_import_directive_groups"> <source>Separate import directive groups</source> <target state="translated">Separar grupos de directivas import</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</source> <target state="translated">En operadores aritméticos: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: And AndAlso Or OrElse</source> <target state="translated">En otros operadores binarios: Y AndAlso o OrElse</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../BasicVSResources.resx"> <body> <trans-unit id="Add_missing_imports_on_paste"> <source>Add missing imports on paste</source> <target state="translated">Agregar las importaciones que faltan al pegar</target> <note>'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</source> <target state="translated">En los operadores relacionales: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</target> <note /> </trans-unit> <trans-unit id="Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments"> <source>Insert ' at the start of new lines when writing ' comments</source> <target state="translated">Insertar ' al comienzo de las líneas nuevas al escribir comentarios '</target> <note /> </trans-unit> <trans-unit id="Microsoft_Visual_Basic"> <source>Microsoft Visual Basic</source> <target state="translated">Microsoft Visual Basic</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">Insertar fragmento de código</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="Automatic_insertion_of_Interface_and_MustOverride_members"> <source>Automatic _insertion of Interface and MustOverride members</source> <target state="translated">I_nserción automática de miembros Interface y MustOverride</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Nunca</target> <note /> </trans-unit> <trans-unit id="Prefer_IsNot_expression"> <source>Prefer 'IsNot' expression</source> <target state="translated">Anteponer expresión "IsNot"</target> <note /> </trans-unit> <trans-unit id="Prefer_Is_Nothing_for_reference_equality_checks"> <source>Prefer 'Is Nothing' for reference equality checks</source> <target state="translated">Preferir “Is Nothing” para comprobaciones de igualdad de referencias</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_object_creation"> <source>Prefer simplified object creation</source> <target state="translated">Preferir la creación de objetos simplificados</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_Imports"> <source>Remove unnecessary Imports</source> <target state="translated">Quitar instrucciones Import innecesarias</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Show_hints_for_New_expressions"> <source>Show hints for 'New' expressions</source> <target state="translated">Mostrar sugerencias para las expresiones "new"</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">Mostrar elementos de espacios de nombres no importados</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">Mo_strar separadores de líneas de procedimientos</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ByRef_on_custom_structure"> <source>_Don't put ByRef on custom structure</source> <target state="translated">_No poner ByRef en una estructura personalizada</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">Ayuda de editor</target> <note /> </trans-unit> <trans-unit id="A_utomatic_insertion_of_end_constructs"> <source>A_utomatic insertion of end constructs</source> <target state="translated">Inserción a_utomática de construcciones end</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">Resaltar palabras cla_ve relacionadas bajo el cursor</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">_Resaltar referencias al símbolo bajo el cursor</target> <note /> </trans-unit> <trans-unit id="Pretty_listing_reformatting_of_code"> <source>_Pretty listing (reformatting) of code</source> <target state="translated">_Lista descriptiva (nuevo formato) de código</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>_Enter outlining mode when files open</source> <target state="translated">_Especificar el modo de esquematización al abrir los archivos</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Extraer método</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for '''</source> <target state="translated">_Generar comentarios de documentación XML con '''</target> <note>{Locked="'''"} "'''" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">Resaltar</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">Optimizar para tamaño de la solución</target> <note /> </trans-unit> <trans-unit id="Large"> <source>Large</source> <target state="translated">Grande</target> <note /> </trans-unit> <trans-unit id="Regular"> <source>Regular</source> <target state="translated">Normal</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">Mostrar comentarios en Información rápida</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">Pequeño</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">Rendimiento</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">Mostrar vista previa para _seguimiento de cambio de nombre</target> <note /> </trans-unit> <trans-unit id="Navigate_to_Object_Browser_for_symbols_defined_in_metadata"> <source>_Navigate to Object Browser for symbols defined in metadata</source> <target state="translated">_Vaya al Examinador de objetos para obtener los símbolos definidos en los metadatos</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Ir a definición</target> <note /> </trans-unit> <trans-unit id="Import_Directives"> <source>Import Directives</source> <target state="translated">Directivas de importación</target> <note /> </trans-unit> <trans-unit id="Sort_imports"> <source>Sort imports</source> <target state="translated">Ordenar instrucciones Import</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_NuGet_packages"> <source>Suggest imports for types in _NuGet packages</source> <target state="translated">Sugerir importaciones para tipos de paquetes _NuGet</target> <note /> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_reference_assemblies"> <source>Suggest imports for types in _reference assemblies</source> <target state="translated">Sugerir importaciones para tipos de ensamblados de r_eferencia</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_imports"> <source>_Place 'System' directives first when sorting imports</source> <target state="translated">_Poner directivas del sistema en primer lugar cuando se ordenen las importaciones</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_Me"> <source>Qualify event access with 'Me'</source> <target state="translated">Calificar el acceso a eventos con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_Me"> <source>Qualify field access with 'Me'</source> <target state="translated">Calificar el acceso a campos con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_Me"> <source>Qualify method access with 'Me'</source> <target state="translated">Calificar el acceso a métodos con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_Me"> <source>Qualify property access with 'Me'</source> <target state="translated">Calificar el acceso a propiedades con 'Me'</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_Me"> <source>Do not prefer 'Me.'</source> <target state="translated">No preferir 'Me.'</target> <note /> </trans-unit> <trans-unit id="Prefer_Me"> <source>Prefer 'Me.'</source> <target state="translated">Preferir 'Me.'</target> <note /> </trans-unit> <trans-unit id="Me_preferences_colon"> <source>'Me.' preferences:</source> <target state="translated">'Preferencias de "Me.":</target> <note /> </trans-unit> <trans-unit id="Predefined_type_preferences_colon"> <source>Predefined type preferences:</source> <target state="translated">Preferencias de tipos predefinidos:</target> <note /> </trans-unit> <trans-unit id="Highlight_matching_portions_of_completion_list_items"> <source>_Highlight matching portions of completion list items</source> <target state="translated">_Resaltar partes coincidentes de elementos de lista de finalización</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">Mostrar _filtros de elementos de finalización</target> <note /> </trans-unit> <trans-unit id="Completion_Lists"> <source>Completion Lists</source> <target state="translated">Listas de finalización</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Comportamiento de la tecla Entrar:</target> <note /> </trans-unit> <trans-unit id="Only_add_new_line_on_enter_after_end_of_fully_typed_word"> <source>_Only add new line on enter after end of fully typed word</source> <target state="translated">_Agregar solo una nueva línea con Entrar al final de palabras</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">_Agregar siempre una nueva línea al presionar Entrar</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">_No agregar nunca una nueva línea al presionar Entrar</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">Incluir siempre fragmentos de código</target> <note /> </trans-unit> <trans-unit id="Include_snippets_when_Tab_is_typed_after_an_identifier"> <source>Include snippets when ?-Tab is typed after an identifier</source> <target state="translated">Incluir fragmentos de código cuando ?-Tab se escriba después de un identificador</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">No incluir nunca fragmentos de código</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">Comportamiento de los fragmentos de código</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_deleted"> <source>Show completion list after a character is _deleted</source> <target state="translated">Mostrar lista de finalización después de _eliminar un carácter</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_typed"> <source>_Show completion list after a character is typed</source> <target state="translated">_Mostrar lista de finalización después de escribir un carácter</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Local sin uso</target> <note /> </trans-unit> <trans-unit id="VB_Coding_Conventions"> <source>VB Coding Conventions</source> <target state="translated">Convenciones de código de VB</target> <note /> </trans-unit> <trans-unit id="nothing_checking_colon"> <source>'nothing' checking:</source> <target state="translated">'Comprobación de "nothing":</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_imports"> <source>Fade out unused imports</source> <target state="translated">Atenuar importaciones no utilizadas</target> <note /> </trans-unit> <trans-unit id="Report_invalid_placeholders_in_string_dot_format_calls"> <source>Report invalid placeholders in 'String.Format' calls</source> <target state="translated">Informar sobre marcadores de posición no válidos en llamadas a "String.Format"</target> <note /> </trans-unit> <trans-unit id="Separate_import_directive_groups"> <source>Separate import directive groups</source> <target state="translated">Separar grupos de directivas import</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</source> <target state="translated">En operadores aritméticos: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: And AndAlso Or OrElse</source> <target state="translated">En otros operadores binarios: Y AndAlso o OrElse</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeManager.Templates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created on module level. All requests for anonymous type symbols /// go via the instance of this class, the symbol will be either created or returned from cache. /// </summary> internal sealed partial class AnonymousTypeManager { /// <summary> /// Cache of created anonymous type templates used as an implementation of anonymous /// types in emit phase. /// </summary> private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> _lazyAnonymousTypeTemplates; /// <summary> /// Maps delegate signature shape (number of parameters and their ref-ness) to a synthesized generic delegate symbol. /// Unlike anonymous types synthesized delegates are not available through symbol APIs. They are only used in lowered bound trees. /// Currently used for dynamic call-site sites whose signature doesn't match any of the well-known Func or Action types. /// </summary> private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> _lazySynthesizedDelegates; private struct SynthesizedDelegateKey : IEquatable<SynthesizedDelegateKey> { private readonly RefKindVector _byRefs; private readonly ushort _parameterCount; private readonly bool _returnsVoid; private readonly int _generation; public SynthesizedDelegateKey(int parameterCount, RefKindVector byRefs, bool returnsVoid, int generation) { _parameterCount = (ushort)parameterCount; _returnsVoid = returnsVoid; _generation = generation; _byRefs = byRefs; } public string MakeTypeName() { return GeneratedNames.MakeDynamicCallSiteDelegateName(_byRefs, _returnsVoid, _generation); } public override bool Equals(object obj) { return obj is SynthesizedDelegateKey && Equals((SynthesizedDelegateKey)obj); } public bool Equals(SynthesizedDelegateKey other) { return _parameterCount == other._parameterCount && _returnsVoid == other._returnsVoid && _generation == other._generation && _byRefs.Equals(other._byRefs); } public override int GetHashCode() { return Hash.Combine( Hash.Combine((int)_parameterCount, _generation), Hash.Combine(_returnsVoid.GetHashCode(), _byRefs.GetHashCode())); } } private struct SynthesizedDelegateValue { public readonly SynthesizedDelegateSymbol Delegate; // the manager that created this delegate: public readonly AnonymousTypeManager Manager; public SynthesizedDelegateValue(AnonymousTypeManager manager, SynthesizedDelegateSymbol @delegate) { Debug.Assert(manager != null && (object)@delegate != null); this.Manager = manager; this.Delegate = @delegate; } } #if DEBUG /// <summary> /// Holds a collection of all the locations of anonymous types and delegates from source /// </summary> private readonly ConcurrentDictionary<Location, bool> _sourceLocationsSeen = new ConcurrentDictionary<Location, bool>(); #endif [Conditional("DEBUG")] private void CheckSourceLocationSeen(AnonymousTypePublicSymbol anonymous) { #if DEBUG Location location = anonymous.Locations[0]; if (location.IsInSource) { if (this.AreTemplatesSealed) { Debug.Assert(_sourceLocationsSeen.ContainsKey(location)); } else { _sourceLocationsSeen.TryAdd(location, true); } } #endif } private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> AnonymousTypeTemplates { get { // Lazily create a template types cache if (_lazyAnonymousTypeTemplates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager.AnonymousTypeTemplates; Interlocked.CompareExchange(ref _lazyAnonymousTypeTemplates, previousCache == null ? new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>() : new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>(previousCache), null); } return _lazyAnonymousTypeTemplates; } } private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> SynthesizedDelegates { get { if (_lazySynthesizedDelegates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager._lazySynthesizedDelegates; Interlocked.CompareExchange(ref _lazySynthesizedDelegates, previousCache == null ? new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>() : new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>(previousCache), null); } return _lazySynthesizedDelegates; } } internal SynthesizedDelegateSymbol SynthesizeDelegate(int parameterCount, RefKindVector refKinds, bool returnsVoid, int generation) { // parameterCount doesn't include return type Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (returnsVoid ? 0 : 1)); var key = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); SynthesizedDelegateValue result; if (this.SynthesizedDelegates.TryGetValue(key, out result)) { return result.Delegate; } // NOTE: the newly created template may be thrown away if another thread wins var synthesizedDelegate = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, key.MakeTypeName(), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return this.SynthesizedDelegates.GetOrAdd(key, new SynthesizedDelegateValue(this, synthesizedDelegate)).Delegate; } /// <summary> /// Given anonymous type provided constructs an implementation type symbol to be used in emit phase; /// if the anonymous type has at least one field the implementation type symbol will be created based on /// a generic type template generated for each 'unique' anonymous type structure, otherwise the template /// type will be non-generic. /// </summary> private NamedTypeSymbol ConstructAnonymousTypeImplementationSymbol(AnonymousTypePublicSymbol anonymous) { Debug.Assert(ReferenceEquals(this, anonymous.Manager)); CheckSourceLocationSeen(anonymous); AnonymousTypeDescriptor typeDescr = anonymous.TypeDescriptor; typeDescr.AssertIsGood(); // Get anonymous type template AnonymousTypeTemplateSymbol template; if (!this.AnonymousTypeTemplates.TryGetValue(typeDescr.Key, out template)) { // NOTE: the newly created template may be thrown away if another thread wins template = this.AnonymousTypeTemplates.GetOrAdd(typeDescr.Key, new AnonymousTypeTemplateSymbol(this, typeDescr)); } // Adjust template location if the template is owned by this manager if (ReferenceEquals(template.Manager, this)) { template.AdjustLocation(typeDescr.Location); } // In case template is not generic, just return it if (template.Arity == 0) { return template; } // otherwise construct type using the field types var typeArguments = typeDescr.Fields.SelectAsArray(f => f.Type); return template.Construct(typeArguments); } private AnonymousTypeTemplateSymbol CreatePlaceholderTemplate(Microsoft.CodeAnalysis.Emit.AnonymousTypeKey key) { var fields = key.Fields.SelectAsArray(f => new AnonymousTypeField(f.Name, Location.None, default)); var typeDescr = new AnonymousTypeDescriptor(fields, Location.None); return new AnonymousTypeTemplateSymbol(this, typeDescr); } /// <summary> /// Resets numbering in anonymous type names and compiles the /// anonymous type methods. Also seals the collection of templates. /// </summary> public void AssignTemplatesNamesAndCompile(MethodCompiler compiler, PEModuleBuilder moduleBeingBuilt, BindingDiagnosticBag diagnostics) { // Ensure all previous anonymous type templates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousAnonymousTypes()) { var templateKey = AnonymousTypeDescriptor.ComputeKey(key.Fields, f => f.Name); this.AnonymousTypeTemplates.GetOrAdd(templateKey, k => this.CreatePlaceholderTemplate(key)); } // Get all anonymous types owned by this manager var builder = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(builder); // If the collection is not sealed yet we should assign // new indexes to the created anonymous type templates if (!this.AreTemplatesSealed) { // If we are emitting .NET module, include module's name into type's name to ensure // uniqueness across added modules. string moduleId; if (moduleBeingBuilt.OutputKind == OutputKind.NetModule) { moduleId = moduleBeingBuilt.Name; string extension = OutputKind.NetModule.GetDefaultExtension(); if (moduleId.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) { moduleId = moduleId.Substring(0, moduleId.Length - extension.Length); } moduleId = MetadataHelpers.MangleForTypeNameIfNeeded(moduleId); } else { moduleId = string.Empty; } int nextIndex = moduleBeingBuilt.GetNextAnonymousTypeIndex(); foreach (var template in builder) { string name; int index; if (!moduleBeingBuilt.TryGetAnonymousTypeName(template, out name, out index)) { index = nextIndex++; name = GeneratedNames.MakeAnonymousTypeTemplateName(index, this.Compilation.GetSubmissionSlotIndex(), moduleId); } // normally it should only happen once, but in case there is a race // NameAndIndex.set has an assert which guarantees that the // template name provided is the same as the one already assigned template.NameAndIndex = new NameAndIndex(name, index); } this.SealTemplates(); } if (builder.Count > 0 && !ReportMissingOrErroneousSymbols(diagnostics)) { // Process all the templates foreach (var template in builder) { foreach (var method in template.SpecialMembers) { moduleBeingBuilt.AddSynthesizedDefinition(template, method.GetCciAdapter()); } compiler.Visit(template, null); } } builder.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var synthesizedDelegate in synthesizedDelegates) { compiler.Visit(synthesizedDelegate, null); } synthesizedDelegates.Free(); } /// <summary> /// The set of anonymous type templates created by /// this AnonymousTypeManager, in fixed order. /// </summary> private void GetCreatedAnonymousTypeTemplates(ArrayBuilder<AnonymousTypeTemplateSymbol> builder) { Debug.Assert(!builder.Any()); var anonymousTypes = _lazyAnonymousTypeTemplates; if (anonymousTypes != null) { foreach (var template in anonymousTypes.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template); } } // Sort type templates using smallest location builder.Sort(new AnonymousTypeComparer(this.Compilation)); } } /// <summary> /// The set of synthesized delegates created by /// this AnonymousTypeManager. /// </summary> private void GetCreatedSynthesizedDelegates(ArrayBuilder<SynthesizedDelegateSymbol> builder) { Debug.Assert(!builder.Any()); var delegates = _lazySynthesizedDelegates; if (delegates != null) { foreach (var template in delegates.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template.Delegate); } } builder.Sort(SynthesizedDelegateSymbolComparer.Instance); } } private class SynthesizedDelegateSymbolComparer : IComparer<SynthesizedDelegateSymbol> { public static readonly SynthesizedDelegateSymbolComparer Instance = new SynthesizedDelegateSymbolComparer(); public int Compare(SynthesizedDelegateSymbol x, SynthesizedDelegateSymbol y) { return x.MetadataName.CompareTo(y.MetadataName); } } internal IReadOnlyDictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue> GetAnonymousTypeMap() { var result = new Dictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue>(); var templates = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); // Get anonymous types but not synthesized delegates. (Delegate types are // not reused across generations since reuse would add complexity (such // as parsing delegate type names from metadata) without a clear benefit.) GetCreatedAnonymousTypeTemplates(templates); foreach (var template in templates) { var nameAndIndex = template.NameAndIndex; var key = template.GetAnonymousTypeKey(); var value = new Microsoft.CodeAnalysis.Emit.AnonymousTypeValue(nameAndIndex.Name, nameAndIndex.Index, template.GetCciAdapter()); result.Add(key, value); } templates.Free(); return result; } /// <summary> /// Returns all templates owned by this type manager /// </summary> internal ImmutableArray<NamedTypeSymbol> GetAllCreatedTemplates() { // NOTE: templates may not be sealed in case metadata is being emitted without IL var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var anonymousTypes = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(anonymousTypes); builder.AddRange(anonymousTypes); anonymousTypes.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); builder.AddRange(synthesizedDelegates); synthesizedDelegates.Free(); return builder.ToImmutableAndFree(); } /// <summary> /// Returns true if the named type is an implementation template for an anonymous type /// </summary> internal static bool IsAnonymousTypeTemplate(NamedTypeSymbol type) { return type is AnonymousTypeTemplateSymbol; } /// <summary> /// Retrieves methods of anonymous type template which are not placed to symbol table. /// In current implementation those are overridden 'ToString', 'Equals' and 'GetHashCode' /// </summary> internal static ImmutableArray<MethodSymbol> GetAnonymousTypeHiddenMethods(NamedTypeSymbol type) { Debug.Assert((object)type != null); return ((AnonymousTypeTemplateSymbol)type).SpecialMembers; } /// <summary> /// Translates anonymous type public symbol into an implementation type symbol to be used in emit. /// </summary> internal static NamedTypeSymbol TranslateAnonymousTypeSymbol(NamedTypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeImplementationSymbol(anonymous); } /// <summary> /// Translates anonymous type method symbol into an implementation method symbol to be used in emit. /// </summary> internal static MethodSymbol TranslateAnonymousTypeMethodSymbol(MethodSymbol method) { Debug.Assert((object)method != null); NamedTypeSymbol translatedType = TranslateAnonymousTypeSymbol(method.ContainingType); // find a method in anonymous type template by name foreach (var member in ((NamedTypeSymbol)translatedType.OriginalDefinition).GetMembers(method.Name)) { if (member.Kind == SymbolKind.Method) { // found a method definition, get a constructed method return ((MethodSymbol)member).AsMember(translatedType); } } throw ExceptionUtilities.Unreachable; } /// <summary> /// Comparator being used for stable ordering in anonymous type indices. /// </summary> private sealed class AnonymousTypeComparer : IComparer<AnonymousTypeTemplateSymbol> { private readonly CSharpCompilation _compilation; public AnonymousTypeComparer(CSharpCompilation compilation) { _compilation = compilation; } public int Compare(AnonymousTypeTemplateSymbol x, AnonymousTypeTemplateSymbol y) { if ((object)x == (object)y) { return 0; } // We compare two anonymous type templated by comparing their locations and descriptor keys // NOTE: If anonymous type got to this phase it must have the location set int result = this.CompareLocations(x.SmallestLocation, y.SmallestLocation); if (result == 0) { // It is still possible for two templates to have the same smallest location // in case they are implicitly created and use the same syntax for location result = string.CompareOrdinal(x.TypeDescriptorKey, y.TypeDescriptorKey); } return result; } private int CompareLocations(Location x, Location y) { if (x == y) { return 0; } else if (x == Location.None) { return -1; } else if (y == Location.None) { return 1; } else { return _compilation.CompareSourceLocations(x, 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.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created on module level. All requests for anonymous type symbols /// go via the instance of this class, the symbol will be either created or returned from cache. /// </summary> internal sealed partial class AnonymousTypeManager { /// <summary> /// Cache of created anonymous type templates used as an implementation of anonymous /// types in emit phase. /// </summary> private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> _lazyAnonymousTypeTemplates; /// <summary> /// Maps delegate signature shape (number of parameters and their ref-ness) to a synthesized generic delegate symbol. /// Unlike anonymous types synthesized delegates are not available through symbol APIs. They are only used in lowered bound trees. /// Currently used for dynamic call-site sites whose signature doesn't match any of the well-known Func or Action types. /// </summary> private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> _lazySynthesizedDelegates; private struct SynthesizedDelegateKey : IEquatable<SynthesizedDelegateKey> { private readonly RefKindVector _byRefs; private readonly ushort _parameterCount; private readonly bool _returnsVoid; private readonly int _generation; public SynthesizedDelegateKey(int parameterCount, RefKindVector byRefs, bool returnsVoid, int generation) { _parameterCount = (ushort)parameterCount; _returnsVoid = returnsVoid; _generation = generation; _byRefs = byRefs; } public string MakeTypeName() { return GeneratedNames.MakeDynamicCallSiteDelegateName(_byRefs, _returnsVoid, _generation); } public override bool Equals(object obj) { return obj is SynthesizedDelegateKey && Equals((SynthesizedDelegateKey)obj); } public bool Equals(SynthesizedDelegateKey other) { return _parameterCount == other._parameterCount && _returnsVoid == other._returnsVoid && _generation == other._generation && _byRefs.Equals(other._byRefs); } public override int GetHashCode() { return Hash.Combine( Hash.Combine((int)_parameterCount, _generation), Hash.Combine(_returnsVoid.GetHashCode(), _byRefs.GetHashCode())); } } private struct SynthesizedDelegateValue { public readonly SynthesizedDelegateSymbol Delegate; // the manager that created this delegate: public readonly AnonymousTypeManager Manager; public SynthesizedDelegateValue(AnonymousTypeManager manager, SynthesizedDelegateSymbol @delegate) { Debug.Assert(manager != null && (object)@delegate != null); this.Manager = manager; this.Delegate = @delegate; } } #if DEBUG /// <summary> /// Holds a collection of all the locations of anonymous types and delegates from source /// </summary> private readonly ConcurrentDictionary<Location, bool> _sourceLocationsSeen = new ConcurrentDictionary<Location, bool>(); #endif [Conditional("DEBUG")] private void CheckSourceLocationSeen(AnonymousTypePublicSymbol anonymous) { #if DEBUG Location location = anonymous.Locations[0]; if (location.IsInSource) { if (this.AreTemplatesSealed) { Debug.Assert(_sourceLocationsSeen.ContainsKey(location)); } else { _sourceLocationsSeen.TryAdd(location, true); } } #endif } private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> AnonymousTypeTemplates { get { // Lazily create a template types cache if (_lazyAnonymousTypeTemplates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager.AnonymousTypeTemplates; Interlocked.CompareExchange(ref _lazyAnonymousTypeTemplates, previousCache == null ? new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>() : new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>(previousCache), null); } return _lazyAnonymousTypeTemplates; } } private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> SynthesizedDelegates { get { if (_lazySynthesizedDelegates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager._lazySynthesizedDelegates; Interlocked.CompareExchange(ref _lazySynthesizedDelegates, previousCache == null ? new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>() : new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>(previousCache), null); } return _lazySynthesizedDelegates; } } internal SynthesizedDelegateSymbol SynthesizeDelegate(int parameterCount, RefKindVector refKinds, bool returnsVoid, int generation) { // parameterCount doesn't include return type Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (returnsVoid ? 0 : 1)); var key = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); SynthesizedDelegateValue result; if (this.SynthesizedDelegates.TryGetValue(key, out result)) { return result.Delegate; } // NOTE: the newly created template may be thrown away if another thread wins var synthesizedDelegate = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, key.MakeTypeName(), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return this.SynthesizedDelegates.GetOrAdd(key, new SynthesizedDelegateValue(this, synthesizedDelegate)).Delegate; } /// <summary> /// Given anonymous type provided constructs an implementation type symbol to be used in emit phase; /// if the anonymous type has at least one field the implementation type symbol will be created based on /// a generic type template generated for each 'unique' anonymous type structure, otherwise the template /// type will be non-generic. /// </summary> private NamedTypeSymbol ConstructAnonymousTypeImplementationSymbol(AnonymousTypePublicSymbol anonymous) { Debug.Assert(ReferenceEquals(this, anonymous.Manager)); CheckSourceLocationSeen(anonymous); AnonymousTypeDescriptor typeDescr = anonymous.TypeDescriptor; typeDescr.AssertIsGood(); // Get anonymous type template AnonymousTypeTemplateSymbol template; if (!this.AnonymousTypeTemplates.TryGetValue(typeDescr.Key, out template)) { // NOTE: the newly created template may be thrown away if another thread wins template = this.AnonymousTypeTemplates.GetOrAdd(typeDescr.Key, new AnonymousTypeTemplateSymbol(this, typeDescr)); } // Adjust template location if the template is owned by this manager if (ReferenceEquals(template.Manager, this)) { template.AdjustLocation(typeDescr.Location); } // In case template is not generic, just return it if (template.Arity == 0) { return template; } // otherwise construct type using the field types var typeArguments = typeDescr.Fields.SelectAsArray(f => f.Type); return template.Construct(typeArguments); } private AnonymousTypeTemplateSymbol CreatePlaceholderTemplate(Microsoft.CodeAnalysis.Emit.AnonymousTypeKey key) { var fields = key.Fields.SelectAsArray(f => new AnonymousTypeField(f.Name, Location.None, default)); var typeDescr = new AnonymousTypeDescriptor(fields, Location.None); return new AnonymousTypeTemplateSymbol(this, typeDescr); } /// <summary> /// Resets numbering in anonymous type names and compiles the /// anonymous type methods. Also seals the collection of templates. /// </summary> public void AssignTemplatesNamesAndCompile(MethodCompiler compiler, PEModuleBuilder moduleBeingBuilt, BindingDiagnosticBag diagnostics) { // Ensure all previous anonymous type templates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousAnonymousTypes()) { var templateKey = AnonymousTypeDescriptor.ComputeKey(key.Fields, f => f.Name); this.AnonymousTypeTemplates.GetOrAdd(templateKey, k => this.CreatePlaceholderTemplate(key)); } // Get all anonymous types owned by this manager var builder = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(builder); // If the collection is not sealed yet we should assign // new indexes to the created anonymous type templates if (!this.AreTemplatesSealed) { // If we are emitting .NET module, include module's name into type's name to ensure // uniqueness across added modules. string moduleId; if (moduleBeingBuilt.OutputKind == OutputKind.NetModule) { moduleId = moduleBeingBuilt.Name; string extension = OutputKind.NetModule.GetDefaultExtension(); if (moduleId.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) { moduleId = moduleId.Substring(0, moduleId.Length - extension.Length); } moduleId = MetadataHelpers.MangleForTypeNameIfNeeded(moduleId); } else { moduleId = string.Empty; } int nextIndex = moduleBeingBuilt.GetNextAnonymousTypeIndex(); foreach (var template in builder) { string name; int index; if (!moduleBeingBuilt.TryGetAnonymousTypeName(template, out name, out index)) { index = nextIndex++; name = GeneratedNames.MakeAnonymousTypeTemplateName(index, this.Compilation.GetSubmissionSlotIndex(), moduleId); } // normally it should only happen once, but in case there is a race // NameAndIndex.set has an assert which guarantees that the // template name provided is the same as the one already assigned template.NameAndIndex = new NameAndIndex(name, index); } this.SealTemplates(); } if (builder.Count > 0 && !ReportMissingOrErroneousSymbols(diagnostics)) { // Process all the templates foreach (var template in builder) { foreach (var method in template.SpecialMembers) { moduleBeingBuilt.AddSynthesizedDefinition(template, method.GetCciAdapter()); } compiler.Visit(template, null); } } builder.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var synthesizedDelegate in synthesizedDelegates) { compiler.Visit(synthesizedDelegate, null); } synthesizedDelegates.Free(); } /// <summary> /// The set of anonymous type templates created by /// this AnonymousTypeManager, in fixed order. /// </summary> private void GetCreatedAnonymousTypeTemplates(ArrayBuilder<AnonymousTypeTemplateSymbol> builder) { Debug.Assert(!builder.Any()); var anonymousTypes = _lazyAnonymousTypeTemplates; if (anonymousTypes != null) { foreach (var template in anonymousTypes.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template); } } // Sort type templates using smallest location builder.Sort(new AnonymousTypeComparer(this.Compilation)); } } /// <summary> /// The set of synthesized delegates created by /// this AnonymousTypeManager. /// </summary> private void GetCreatedSynthesizedDelegates(ArrayBuilder<SynthesizedDelegateSymbol> builder) { Debug.Assert(!builder.Any()); var delegates = _lazySynthesizedDelegates; if (delegates != null) { foreach (var template in delegates.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template.Delegate); } } builder.Sort(SynthesizedDelegateSymbolComparer.Instance); } } private class SynthesizedDelegateSymbolComparer : IComparer<SynthesizedDelegateSymbol> { public static readonly SynthesizedDelegateSymbolComparer Instance = new SynthesizedDelegateSymbolComparer(); public int Compare(SynthesizedDelegateSymbol x, SynthesizedDelegateSymbol y) { return x.MetadataName.CompareTo(y.MetadataName); } } internal IReadOnlyDictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue> GetAnonymousTypeMap() { var result = new Dictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue>(); var templates = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); // Get anonymous types but not synthesized delegates. (Delegate types are // not reused across generations since reuse would add complexity (such // as parsing delegate type names from metadata) without a clear benefit.) GetCreatedAnonymousTypeTemplates(templates); foreach (var template in templates) { var nameAndIndex = template.NameAndIndex; var key = template.GetAnonymousTypeKey(); var value = new Microsoft.CodeAnalysis.Emit.AnonymousTypeValue(nameAndIndex.Name, nameAndIndex.Index, template.GetCciAdapter()); result.Add(key, value); } templates.Free(); return result; } /// <summary> /// Returns all templates owned by this type manager /// </summary> internal ImmutableArray<NamedTypeSymbol> GetAllCreatedTemplates() { // NOTE: templates may not be sealed in case metadata is being emitted without IL var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var anonymousTypes = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(anonymousTypes); builder.AddRange(anonymousTypes); anonymousTypes.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); builder.AddRange(synthesizedDelegates); synthesizedDelegates.Free(); return builder.ToImmutableAndFree(); } /// <summary> /// Returns true if the named type is an implementation template for an anonymous type /// </summary> internal static bool IsAnonymousTypeTemplate(NamedTypeSymbol type) { return type is AnonymousTypeTemplateSymbol; } /// <summary> /// Retrieves methods of anonymous type template which are not placed to symbol table. /// In current implementation those are overridden 'ToString', 'Equals' and 'GetHashCode' /// </summary> internal static ImmutableArray<MethodSymbol> GetAnonymousTypeHiddenMethods(NamedTypeSymbol type) { Debug.Assert((object)type != null); return ((AnonymousTypeTemplateSymbol)type).SpecialMembers; } /// <summary> /// Translates anonymous type public symbol into an implementation type symbol to be used in emit. /// </summary> internal static NamedTypeSymbol TranslateAnonymousTypeSymbol(NamedTypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeImplementationSymbol(anonymous); } /// <summary> /// Translates anonymous type method symbol into an implementation method symbol to be used in emit. /// </summary> internal static MethodSymbol TranslateAnonymousTypeMethodSymbol(MethodSymbol method) { Debug.Assert((object)method != null); NamedTypeSymbol translatedType = TranslateAnonymousTypeSymbol(method.ContainingType); // find a method in anonymous type template by name foreach (var member in ((NamedTypeSymbol)translatedType.OriginalDefinition).GetMembers(method.Name)) { if (member.Kind == SymbolKind.Method) { // found a method definition, get a constructed method return ((MethodSymbol)member).AsMember(translatedType); } } throw ExceptionUtilities.Unreachable; } /// <summary> /// Comparator being used for stable ordering in anonymous type indices. /// </summary> private sealed class AnonymousTypeComparer : IComparer<AnonymousTypeTemplateSymbol> { private readonly CSharpCompilation _compilation; public AnonymousTypeComparer(CSharpCompilation compilation) { _compilation = compilation; } public int Compare(AnonymousTypeTemplateSymbol x, AnonymousTypeTemplateSymbol y) { if ((object)x == (object)y) { return 0; } // We compare two anonymous type templated by comparing their locations and descriptor keys // NOTE: If anonymous type got to this phase it must have the location set int result = this.CompareLocations(x.SmallestLocation, y.SmallestLocation); if (result == 0) { // It is still possible for two templates to have the same smallest location // in case they are implicitly created and use the same syntax for location result = string.CompareOrdinal(x.TypeDescriptorKey, y.TypeDescriptorKey); } return result; } private int CompareLocations(Location x, Location y) { if (x == y) { return 0; } else if (x == Location.None) { return -1; } else if (y == Location.None) { return 1; } else { return _compilation.CompareSourceLocations(x, y); } } } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/EditorFeatures/Test2/KeywordHighlighting/CSharpKeywordHighlightingTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting Public Class CSharpKeywordHighlightingTests Inherits AbstractKeywordHighlightingTests <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestVerifyNoHighlightsWhenOptionDisabled() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { void M() { $$if (true) { } else { } } } </Document> </Project> </Workspace>, optionIsEnabled:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestVerifyHighlightsWhenOptionEnabled() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { void M() { $$[|if|] (true) { } [|else|] { } } } </Document> </Project> </Workspace>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting Public Class CSharpKeywordHighlightingTests Inherits AbstractKeywordHighlightingTests <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestVerifyNoHighlightsWhenOptionDisabled() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { void M() { $$if (true) { } else { } } } </Document> </Project> </Workspace>, optionIsEnabled:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestVerifyHighlightsWhenOptionEnabled() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { void M() { $$[|if|] (true) { } [|else|] { } } } </Document> </Project> </Workspace>) End Function End Class End Namespace
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Dependencies/Collections/Internal/ThrowHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This file defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Collections.Internal { internal static class ThrowHelper { [DoesNotReturn] internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_IndexException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowArgumentException_BadComparer(object? comparer) { throw new ArgumentException(string.Format(SR.Arg_BogusIComparer, comparer)); } [DoesNotReturn] internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() { throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() { throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() { throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } [DoesNotReturn] internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongKeyTypeArgumentException((object?)key, targetType); } [DoesNotReturn] internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongValueTypeArgumentException((object?)value, targetType); } private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object? key) { return new ArgumentException(string.Format(SR.Argument_AddingDuplicateWithKey, key)); } [DoesNotReturn] internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetAddingDuplicateWithKeyArgumentException((object?)key); } [DoesNotReturn] internal static void ThrowKeyNotFoundException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetKeyNotFoundException((object?)key); } [DoesNotReturn] internal static void ThrowArgumentException(ExceptionResource resource) { throw GetArgumentException(resource); } private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw GetArgumentNullException(argument); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, resource); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) { throw new InvalidOperationException(GetResourceString(resource), e); } [DoesNotReturn] internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowArgumentException_Argument_InvalidArrayType() { throw new ArgumentException(SR.Argument_InvalidArrayType); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } [DoesNotReturn] internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported() { throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported); } private static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceString(resource)); } private static ArgumentException GetWrongKeyTypeArgumentException(object? key, Type targetType) { return new ArgumentException(string.Format(SR.Arg_WrongType, key, targetType), nameof(key)); } private static ArgumentException GetWrongValueTypeArgumentException(object? value, Type targetType) { return new ArgumentException(string.Format(SR.Arg_WrongType, value, targetType), nameof(value)); } private static KeyNotFoundException GetKeyNotFoundException(object? key) { return new KeyNotFoundException(string.Format(SR.Arg_KeyNotFoundWithKey, key)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); } // Allow nulls for reference types and Nullable<U>, but not for value types. // Aggressively inline so the jit evaluates the if in place and either drops the call altogether // Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void IfNullAndNullsAreIllegalThenThrow<T>(object? value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (!(default(T) == null) && value == null) ThrowHelper.ThrowArgumentNullException(argName); } private static string GetArgumentName(ExceptionArgument argument) { switch (argument) { case ExceptionArgument.dictionary: return "dictionary"; case ExceptionArgument.array: return "array"; case ExceptionArgument.key: return "key"; case ExceptionArgument.value: return "value"; case ExceptionArgument.startIndex: return "startIndex"; case ExceptionArgument.index: return "index"; case ExceptionArgument.capacity: return "capacity"; case ExceptionArgument.collection: return "collection"; case ExceptionArgument.item: return "item"; case ExceptionArgument.converter: return "converter"; case ExceptionArgument.match: return "match"; case ExceptionArgument.count: return "count"; case ExceptionArgument.action: return "action"; case ExceptionArgument.comparison: return "comparison"; case ExceptionArgument.source: return "source"; case ExceptionArgument.length: return "length"; case ExceptionArgument.destinationArray: return "destinationArray"; default: Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum."); return ""; } } private static string GetResourceString(ExceptionResource resource) { switch (resource) { case ExceptionResource.ArgumentOutOfRange_Index: return SR.ArgumentOutOfRange_Index; case ExceptionResource.ArgumentOutOfRange_Count: return SR.ArgumentOutOfRange_Count; case ExceptionResource.Arg_ArrayPlusOffTooSmall: return SR.Arg_ArrayPlusOffTooSmall; case ExceptionResource.Arg_RankMultiDimNotSupported: return SR.Arg_RankMultiDimNotSupported; case ExceptionResource.Arg_NonZeroLowerBound: return SR.Arg_NonZeroLowerBound; case ExceptionResource.ArgumentOutOfRange_ListInsert: return SR.ArgumentOutOfRange_ListInsert; case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum: return SR.ArgumentOutOfRange_NeedNonNegNum; case ExceptionResource.ArgumentOutOfRange_SmallCapacity: return SR.ArgumentOutOfRange_SmallCapacity; case ExceptionResource.Argument_InvalidOffLen: return SR.Argument_InvalidOffLen; case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection: return SR.ArgumentOutOfRange_BiggerThanCollection; case ExceptionResource.NotSupported_KeyCollectionSet: return SR.NotSupported_KeyCollectionSet; case ExceptionResource.NotSupported_ValueCollectionSet: return SR.NotSupported_ValueCollectionSet; case ExceptionResource.InvalidOperation_IComparerFailed: return SR.InvalidOperation_IComparerFailed; default: Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum."); return ""; } } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { dictionary, array, key, value, startIndex, index, capacity, collection, item, converter, match, count, action, comparison, source, length, destinationArray, } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { ArgumentOutOfRange_Index, ArgumentOutOfRange_Count, Arg_ArrayPlusOffTooSmall, Arg_RankMultiDimNotSupported, Arg_NonZeroLowerBound, ArgumentOutOfRange_ListInsert, ArgumentOutOfRange_NeedNonNegNum, ArgumentOutOfRange_SmallCapacity, Argument_InvalidOffLen, ArgumentOutOfRange_BiggerThanCollection, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, InvalidOperation_IComparerFailed, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This file defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Collections.Internal { internal static class ThrowHelper { [DoesNotReturn] internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_IndexException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowArgumentException_BadComparer(object? comparer) { throw new ArgumentException(string.Format(SR.Arg_BogusIComparer, comparer)); } [DoesNotReturn] internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() { throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() { throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() { throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } [DoesNotReturn] internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongKeyTypeArgumentException((object?)key, targetType); } [DoesNotReturn] internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongValueTypeArgumentException((object?)value, targetType); } private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object? key) { return new ArgumentException(string.Format(SR.Argument_AddingDuplicateWithKey, key)); } [DoesNotReturn] internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetAddingDuplicateWithKeyArgumentException((object?)key); } [DoesNotReturn] internal static void ThrowKeyNotFoundException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetKeyNotFoundException((object?)key); } [DoesNotReturn] internal static void ThrowArgumentException(ExceptionResource resource) { throw GetArgumentException(resource); } private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw GetArgumentNullException(argument); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, resource); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) { throw new InvalidOperationException(GetResourceString(resource), e); } [DoesNotReturn] internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowArgumentException_Argument_InvalidArrayType() { throw new ArgumentException(SR.Argument_InvalidArrayType); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } [DoesNotReturn] internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported() { throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported); } private static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceString(resource)); } private static ArgumentException GetWrongKeyTypeArgumentException(object? key, Type targetType) { return new ArgumentException(string.Format(SR.Arg_WrongType, key, targetType), nameof(key)); } private static ArgumentException GetWrongValueTypeArgumentException(object? value, Type targetType) { return new ArgumentException(string.Format(SR.Arg_WrongType, value, targetType), nameof(value)); } private static KeyNotFoundException GetKeyNotFoundException(object? key) { return new KeyNotFoundException(string.Format(SR.Arg_KeyNotFoundWithKey, key)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); } // Allow nulls for reference types and Nullable<U>, but not for value types. // Aggressively inline so the jit evaluates the if in place and either drops the call altogether // Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void IfNullAndNullsAreIllegalThenThrow<T>(object? value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (!(default(T) == null) && value == null) ThrowHelper.ThrowArgumentNullException(argName); } private static string GetArgumentName(ExceptionArgument argument) { switch (argument) { case ExceptionArgument.dictionary: return "dictionary"; case ExceptionArgument.array: return "array"; case ExceptionArgument.key: return "key"; case ExceptionArgument.value: return "value"; case ExceptionArgument.startIndex: return "startIndex"; case ExceptionArgument.index: return "index"; case ExceptionArgument.capacity: return "capacity"; case ExceptionArgument.collection: return "collection"; case ExceptionArgument.item: return "item"; case ExceptionArgument.converter: return "converter"; case ExceptionArgument.match: return "match"; case ExceptionArgument.count: return "count"; case ExceptionArgument.action: return "action"; case ExceptionArgument.comparison: return "comparison"; case ExceptionArgument.source: return "source"; case ExceptionArgument.length: return "length"; case ExceptionArgument.destinationArray: return "destinationArray"; default: Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum."); return ""; } } private static string GetResourceString(ExceptionResource resource) { switch (resource) { case ExceptionResource.ArgumentOutOfRange_Index: return SR.ArgumentOutOfRange_Index; case ExceptionResource.ArgumentOutOfRange_Count: return SR.ArgumentOutOfRange_Count; case ExceptionResource.Arg_ArrayPlusOffTooSmall: return SR.Arg_ArrayPlusOffTooSmall; case ExceptionResource.Arg_RankMultiDimNotSupported: return SR.Arg_RankMultiDimNotSupported; case ExceptionResource.Arg_NonZeroLowerBound: return SR.Arg_NonZeroLowerBound; case ExceptionResource.ArgumentOutOfRange_ListInsert: return SR.ArgumentOutOfRange_ListInsert; case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum: return SR.ArgumentOutOfRange_NeedNonNegNum; case ExceptionResource.ArgumentOutOfRange_SmallCapacity: return SR.ArgumentOutOfRange_SmallCapacity; case ExceptionResource.Argument_InvalidOffLen: return SR.Argument_InvalidOffLen; case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection: return SR.ArgumentOutOfRange_BiggerThanCollection; case ExceptionResource.NotSupported_KeyCollectionSet: return SR.NotSupported_KeyCollectionSet; case ExceptionResource.NotSupported_ValueCollectionSet: return SR.NotSupported_ValueCollectionSet; case ExceptionResource.InvalidOperation_IComparerFailed: return SR.InvalidOperation_IComparerFailed; default: Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum."); return ""; } } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { dictionary, array, key, value, startIndex, index, capacity, collection, item, converter, match, count, action, comparison, source, length, destinationArray, } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { ArgumentOutOfRange_Index, ArgumentOutOfRange_Count, Arg_ArrayPlusOffTooSmall, Arg_RankMultiDimNotSupported, Arg_NonZeroLowerBound, ArgumentOutOfRange_ListInsert, ArgumentOutOfRange_NeedNonNegNum, ArgumentOutOfRange_SmallCapacity, Argument_InvalidOffLen, ArgumentOutOfRange_BiggerThanCollection, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, InvalidOperation_IComparerFailed, } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class CSharpCodeFixVerifier<TAnalyzer, TCodeFix> where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic()"/> public static DiagnosticResult Diagnostic() => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(string)"/> public static DiagnosticResult Diagnostic(string diagnosticId) => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(diagnosticId); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(DiagnosticDescriptor)"/> public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(descriptor); /// <summary> /// Verify standard properties of <typeparamref name="TAnalyzer"/>. /// </summary> /// <remarks> /// This validation method is largely specific to dotnet/roslyn scenarios. /// </remarks> public static void VerifyStandardProperty(AnalyzerProperty property) => CodeFixVerifierHelper.VerifyStandardProperty(new TAnalyzer(), property); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyAnalyzerAsync(string, DiagnosticResult[])"/> public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected) { var test = new Test { TestCode = source, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, string)"/> public static async Task VerifyCodeFixAsync(string source, string fixedSource) => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult, string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult[], string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { var test = new Test { TestCode = source, FixedCode = fixedSource, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class CSharpCodeFixVerifier<TAnalyzer, TCodeFix> where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic()"/> public static DiagnosticResult Diagnostic() => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(string)"/> public static DiagnosticResult Diagnostic(string diagnosticId) => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(diagnosticId); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(DiagnosticDescriptor)"/> public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(descriptor); /// <summary> /// Verify standard properties of <typeparamref name="TAnalyzer"/>. /// </summary> /// <remarks> /// This validation method is largely specific to dotnet/roslyn scenarios. /// </remarks> public static void VerifyStandardProperty(AnalyzerProperty property) => CodeFixVerifierHelper.VerifyStandardProperty(new TAnalyzer(), property); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyAnalyzerAsync(string, DiagnosticResult[])"/> public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected) { var test = new Test { TestCode = source, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, string)"/> public static async Task VerifyCodeFixAsync(string source, string fixedSource) => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult, string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult[], string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { var test = new Test { TestCode = source, FixedCode = fixedSource, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptDebugLocationInfoWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDebugLocationInfoWrapper { internal readonly DebugLocationInfo UnderlyingObject; public VSTypeScriptDebugLocationInfoWrapper(string name, int lineOffset) => UnderlyingObject = new DebugLocationInfo(name, lineOffset); public readonly string Name => UnderlyingObject.Name; public readonly int LineOffset => UnderlyingObject.LineOffset; internal bool IsDefault => UnderlyingObject.IsDefault; } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDebugLocationInfoWrapper { internal readonly DebugLocationInfo UnderlyingObject; public VSTypeScriptDebugLocationInfoWrapper(string name, int lineOffset) => UnderlyingObject = new DebugLocationInfo(name, lineOffset); public readonly string Name => UnderlyingObject.Name; public readonly int LineOffset => UnderlyingObject.LineOffset; internal bool IsDefault => UnderlyingObject.IsDefault; } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.Refactoring.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; namespace Microsoft.CodeAnalysis.CodeStyle { // This part contains all the logic for hooking up the CodeRefactoring 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 refactorings // is contained in AbstractCodeStyleProvider.cs internal abstract partial class AbstractCodeStyleProvider<TOptionKind, TCodeStyleProvider> { private async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var optionValue = optionSet.GetOption(_option); var severity = GetOptionSeverity(optionValue); switch (severity) { case ReportDiagnostic.Suppress: case ReportDiagnostic.Hidden: // if the severity is Hidden that's equivalent to 'refactoring only', so we want // to try to compute the refactoring here. // // If the severity is 'suppress', that means the user doesn't want the actual // analyzer to run here. However, we can still check to see if we could offer // the feature here as a refactoring. await ComputeRefactoringsAsync(context, optionValue.Value, analyzerActive: false).ConfigureAwait(false); return; case ReportDiagnostic.Error: case ReportDiagnostic.Warn: case ReportDiagnostic.Info: // User has this option set at a level where we want it checked by the // DiagnosticAnalyser and not the CodeRefactoringProvider. However, we still // want to check if we want to offer the *reverse* refactoring here in this // single location. // // For example, say this is the "use expression body" feature. If the user says // they always prefer expression-bodies (with warning level), then we want the // analyzer to always be checking for that. However, we still want to offer the // refactoring to flip their code to use a block body here, just in case that // was something they wanted to do as a one off (i.e. before adding new // statements. // // TODO(cyrusn): Should we only do this for warn/info? Argument could be made // that we shouldn't even offer to refactor in the reverse direction if it will // just cause an error. That said, maybe this is just an intermediary step, and // we shouldn't really be blocking the user from making it. await ComputeRefactoringsAsync(context, optionValue.Value, analyzerActive: true).ConfigureAwait(false); return; } } private async Task ComputeRefactoringsAsync( CodeRefactoringContext context, TOptionKind option, bool analyzerActive) { var (document, span, cancellationToken) = context; var computationTask = analyzerActive ? ComputeOpposingRefactoringsWhenAnalyzerActiveAsync(document, span, option, cancellationToken) : ComputeAllRefactoringsWhenAnalyzerInactiveAsync(document, span, cancellationToken); var codeActions = await computationTask.ConfigureAwait(false); context.RegisterRefactorings(codeActions); } public class CodeRefactoringProvider : CodeRefactorings.CodeRefactoringProvider { public readonly TCodeStyleProvider _codeStyleProvider; protected CodeRefactoringProvider() => _codeStyleProvider = new TCodeStyleProvider(); public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) => _codeStyleProvider.ComputeRefactoringsAsync(context); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; namespace Microsoft.CodeAnalysis.CodeStyle { // This part contains all the logic for hooking up the CodeRefactoring 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 refactorings // is contained in AbstractCodeStyleProvider.cs internal abstract partial class AbstractCodeStyleProvider<TOptionKind, TCodeStyleProvider> { private async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var optionValue = optionSet.GetOption(_option); var severity = GetOptionSeverity(optionValue); switch (severity) { case ReportDiagnostic.Suppress: case ReportDiagnostic.Hidden: // if the severity is Hidden that's equivalent to 'refactoring only', so we want // to try to compute the refactoring here. // // If the severity is 'suppress', that means the user doesn't want the actual // analyzer to run here. However, we can still check to see if we could offer // the feature here as a refactoring. await ComputeRefactoringsAsync(context, optionValue.Value, analyzerActive: false).ConfigureAwait(false); return; case ReportDiagnostic.Error: case ReportDiagnostic.Warn: case ReportDiagnostic.Info: // User has this option set at a level where we want it checked by the // DiagnosticAnalyser and not the CodeRefactoringProvider. However, we still // want to check if we want to offer the *reverse* refactoring here in this // single location. // // For example, say this is the "use expression body" feature. If the user says // they always prefer expression-bodies (with warning level), then we want the // analyzer to always be checking for that. However, we still want to offer the // refactoring to flip their code to use a block body here, just in case that // was something they wanted to do as a one off (i.e. before adding new // statements. // // TODO(cyrusn): Should we only do this for warn/info? Argument could be made // that we shouldn't even offer to refactor in the reverse direction if it will // just cause an error. That said, maybe this is just an intermediary step, and // we shouldn't really be blocking the user from making it. await ComputeRefactoringsAsync(context, optionValue.Value, analyzerActive: true).ConfigureAwait(false); return; } } private async Task ComputeRefactoringsAsync( CodeRefactoringContext context, TOptionKind option, bool analyzerActive) { var (document, span, cancellationToken) = context; var computationTask = analyzerActive ? ComputeOpposingRefactoringsWhenAnalyzerActiveAsync(document, span, option, cancellationToken) : ComputeAllRefactoringsWhenAnalyzerInactiveAsync(document, span, cancellationToken); var codeActions = await computationTask.ConfigureAwait(false); context.RegisterRefactorings(codeActions); } public class CodeRefactoringProvider : CodeRefactorings.CodeRefactoringProvider { public readonly TCodeStyleProvider _codeStyleProvider; protected CodeRefactoringProvider() => _codeStyleProvider = new TCodeStyleProvider(); public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) => _codeStyleProvider.ComputeRefactoringsAsync(context); } } }
-1
dotnet/roslyn
55,482
Protect baseline readers from disposal while in use
Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
tmat
2021-08-06T22:22:08Z
2021-08-10T18:41:44Z
1ceccc6d26f17ba1452bd9b4107ee1e7a4a910e8
3a9bae8ce5ed75929a82d798ed4a98fc25b00001
Protect baseline readers from disposal while in use. Will help diagnose errors like [AB#1363929](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1363929)
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationNamespaceInfo { private static readonly ConditionalWeakTable<INamespaceSymbol, CodeGenerationNamespaceInfo> s_namespaceToInfoMap = new(); private readonly IList<ISymbol> _imports; private CodeGenerationNamespaceInfo(IList<ISymbol> imports) => _imports = imports; public static void Attach( INamespaceSymbol @namespace, IList<ISymbol> imports) { var info = new CodeGenerationNamespaceInfo(imports ?? SpecializedCollections.EmptyList<ISymbol>()); s_namespaceToInfoMap.Add(@namespace, info); } private static CodeGenerationNamespaceInfo GetInfo(INamespaceSymbol @namespace) { s_namespaceToInfoMap.TryGetValue(@namespace, out var info); return info; } public static IList<ISymbol> GetImports(INamespaceSymbol @namespace) => GetImports(GetInfo(@namespace)); private static IList<ISymbol> GetImports(CodeGenerationNamespaceInfo info) { return info == null ? SpecializedCollections.EmptyList<ISymbol>() : info._imports; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationNamespaceInfo { private static readonly ConditionalWeakTable<INamespaceSymbol, CodeGenerationNamespaceInfo> s_namespaceToInfoMap = new(); private readonly IList<ISymbol> _imports; private CodeGenerationNamespaceInfo(IList<ISymbol> imports) => _imports = imports; public static void Attach( INamespaceSymbol @namespace, IList<ISymbol> imports) { var info = new CodeGenerationNamespaceInfo(imports ?? SpecializedCollections.EmptyList<ISymbol>()); s_namespaceToInfoMap.Add(@namespace, info); } private static CodeGenerationNamespaceInfo GetInfo(INamespaceSymbol @namespace) { s_namespaceToInfoMap.TryGetValue(@namespace, out var info); return info; } public static IList<ISymbol> GetImports(INamespaceSymbol @namespace) => GetImports(GetInfo(@namespace)); private static IList<ISymbol> GetImports(CodeGenerationNamespaceInfo info) { return info == null ? SpecializedCollections.EmptyList<ISymbol>() : info._imports; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/LanguageServer/Protocol/Extensions/ProtocolConversions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using Logger = Microsoft.CodeAnalysis.Internal.Log.Logger; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer { internal static class ProtocolConversions { private const string CSharpMarkdownLanguageName = "csharp"; private const string VisualBasicMarkdownLanguageName = "vb"; private static readonly Regex s_markdownEscapeRegex = new(@"([\\`\*_\{\}\[\]\(\)#+\-\.!])", RegexOptions.Compiled); // NOTE: While the spec allows it, don't use Function and Method, as both VS and VS Code display them the same way // which can confuse users public static readonly Dictionary<string, LSP.CompletionItemKind> RoslynTagToCompletionItemKind = new Dictionary<string, LSP.CompletionItemKind>() { { WellKnownTags.Public, LSP.CompletionItemKind.Keyword }, { WellKnownTags.Protected, LSP.CompletionItemKind.Keyword }, { WellKnownTags.Private, LSP.CompletionItemKind.Keyword }, { WellKnownTags.Internal, LSP.CompletionItemKind.Keyword }, { WellKnownTags.File, LSP.CompletionItemKind.File }, { WellKnownTags.Project, LSP.CompletionItemKind.File }, { WellKnownTags.Folder, LSP.CompletionItemKind.Folder }, { WellKnownTags.Assembly, LSP.CompletionItemKind.File }, { WellKnownTags.Class, LSP.CompletionItemKind.Class }, { WellKnownTags.Constant, LSP.CompletionItemKind.Constant }, { WellKnownTags.Delegate, LSP.CompletionItemKind.Method }, { WellKnownTags.Enum, LSP.CompletionItemKind.Enum }, { WellKnownTags.EnumMember, LSP.CompletionItemKind.EnumMember }, { WellKnownTags.Event, LSP.CompletionItemKind.Event }, { WellKnownTags.ExtensionMethod, LSP.CompletionItemKind.Method }, { WellKnownTags.Field, LSP.CompletionItemKind.Field }, { WellKnownTags.Interface, LSP.CompletionItemKind.Interface }, { WellKnownTags.Intrinsic, LSP.CompletionItemKind.Text }, { WellKnownTags.Keyword, LSP.CompletionItemKind.Keyword }, { WellKnownTags.Label, LSP.CompletionItemKind.Text }, { WellKnownTags.Local, LSP.CompletionItemKind.Variable }, { WellKnownTags.Namespace, LSP.CompletionItemKind.Text }, { WellKnownTags.Method, LSP.CompletionItemKind.Method }, { WellKnownTags.Module, LSP.CompletionItemKind.Module }, { WellKnownTags.Operator, LSP.CompletionItemKind.Operator }, { WellKnownTags.Parameter, LSP.CompletionItemKind.Value }, { WellKnownTags.Property, LSP.CompletionItemKind.Property }, { WellKnownTags.RangeVariable, LSP.CompletionItemKind.Variable }, { WellKnownTags.Reference, LSP.CompletionItemKind.Reference }, { WellKnownTags.Structure, LSP.CompletionItemKind.Struct }, { WellKnownTags.TypeParameter, LSP.CompletionItemKind.TypeParameter }, { WellKnownTags.Snippet, LSP.CompletionItemKind.Snippet }, { WellKnownTags.Error, LSP.CompletionItemKind.Text }, { WellKnownTags.Warning, LSP.CompletionItemKind.Text }, { WellKnownTags.StatusInformation, LSP.CompletionItemKind.Text }, { WellKnownTags.AddReference, LSP.CompletionItemKind.Text }, { WellKnownTags.NuGet, LSP.CompletionItemKind.Text } }; // TO-DO: More LSP.CompletionTriggerKind mappings are required to properly map to Roslyn CompletionTriggerKinds. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1178726 public static async Task<Completion.CompletionTrigger> LSPToRoslynCompletionTriggerAsync( LSP.CompletionContext? context, Document document, int position, CancellationToken cancellationToken) { if (context is null) { // Some LSP clients don't support sending extra context, so all we can do is invoke return Completion.CompletionTrigger.Invoke; } else if (context.TriggerKind is LSP.CompletionTriggerKind.Invoked or LSP.CompletionTriggerKind.TriggerForIncompleteCompletions) { if (context is not LSP.VSCompletionContext vsCompletionContext) { return Completion.CompletionTrigger.Invoke; } switch (vsCompletionContext.InvokeKind) { case LSP.VSCompletionInvokeKind.Explicit: return Completion.CompletionTrigger.Invoke; case LSP.VSCompletionInvokeKind.Typing: var insertionChar = await GetInsertionCharacterAsync(document, position, cancellationToken).ConfigureAwait(false); return Completion.CompletionTrigger.CreateInsertionTrigger(insertionChar); case LSP.VSCompletionInvokeKind.Deletion: Contract.ThrowIfNull(context.TriggerCharacter); Contract.ThrowIfFalse(char.TryParse(context.TriggerCharacter, out var triggerChar)); return Completion.CompletionTrigger.CreateDeletionTrigger(triggerChar); default: // LSP added an InvokeKind that we need to support. Logger.Log(FunctionId.LSPCompletion_MissingLSPCompletionInvokeKind); return Completion.CompletionTrigger.Invoke; } } else if (context.TriggerKind is LSP.CompletionTriggerKind.TriggerCharacter) { Contract.ThrowIfNull(context.TriggerCharacter); Contract.ThrowIfFalse(char.TryParse(context.TriggerCharacter, out var triggerChar)); return Completion.CompletionTrigger.CreateInsertionTrigger(triggerChar); } else { // LSP added a TriggerKind that we need to support. Logger.Log(FunctionId.LSPCompletion_MissingLSPCompletionTriggerKind); return Completion.CompletionTrigger.Invoke; } // Local functions static async Task<char> GetInsertionCharacterAsync(Document document, int position, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use 'position - 1' here since we want to find the character that was just inserted. Contract.ThrowIfTrue(position < 1); var triggerCharacter = text[position - 1]; return triggerCharacter; } } public static Uri GetUriFromFilePath(string? filePath) { if (filePath is null) { throw new ArgumentNullException(nameof(filePath)); } return new Uri(filePath, UriKind.Absolute); } public static LSP.TextDocumentPositionParams PositionToTextDocumentPositionParams(int position, SourceText text, Document document) { return new LSP.TextDocumentPositionParams() { TextDocument = DocumentToTextDocumentIdentifier(document), Position = LinePositionToPosition(text.Lines.GetLinePosition(position)) }; } public static LSP.TextDocumentIdentifier DocumentToTextDocumentIdentifier(Document document) => new LSP.TextDocumentIdentifier { Uri = document.GetURI() }; public static LSP.VersionedTextDocumentIdentifier DocumentToVersionedTextDocumentIdentifier(Document document) => new LSP.VersionedTextDocumentIdentifier { Uri = document.GetURI() }; public static LinePosition PositionToLinePosition(LSP.Position position) => new LinePosition(position.Line, position.Character); public static LinePositionSpan RangeToLinePositionSpan(LSP.Range range) => new LinePositionSpan(PositionToLinePosition(range.Start), PositionToLinePosition(range.End)); public static TextSpan RangeToTextSpan(LSP.Range range, SourceText text) { var linePositionSpan = RangeToLinePositionSpan(range); return text.Lines.GetTextSpan(linePositionSpan); } public static LSP.TextEdit TextChangeToTextEdit(TextChange textChange, SourceText oldText) { Contract.ThrowIfNull(textChange.NewText); return new LSP.TextEdit { NewText = textChange.NewText, Range = TextSpanToRange(textChange.Span, oldText) }; } public static TextChange ContentChangeEventToTextChange(LSP.TextDocumentContentChangeEvent changeEvent, SourceText text) => new TextChange(RangeToTextSpan(changeEvent.Range, text), changeEvent.Text); public static LSP.Position LinePositionToPosition(LinePosition linePosition) => new LSP.Position { Line = linePosition.Line, Character = linePosition.Character }; public static LSP.Range LinePositionToRange(LinePositionSpan linePositionSpan) => new LSP.Range { Start = LinePositionToPosition(linePositionSpan.Start), End = LinePositionToPosition(linePositionSpan.End) }; public static LSP.Range TextSpanToRange(TextSpan textSpan, SourceText text) { var linePosSpan = text.Lines.GetLinePositionSpan(textSpan); return LinePositionToRange(linePosSpan); } public static Task<LSP.Location?> DocumentSpanToLocationAsync(DocumentSpan documentSpan, CancellationToken cancellationToken) => TextSpanToLocationAsync(documentSpan.Document, documentSpan.SourceSpan, isStale: false, cancellationToken); public static async Task<LSP.LocationWithText?> DocumentSpanToLocationWithTextAsync( DocumentSpan documentSpan, ClassifiedTextElement text, CancellationToken cancellationToken) { var location = await TextSpanToLocationAsync( documentSpan.Document, documentSpan.SourceSpan, isStale: false, cancellationToken).ConfigureAwait(false); return location == null ? null : new LSP.LocationWithText { Uri = location.Uri, Range = location.Range, Text = text }; } /// <summary> /// Compute all the <see cref="LSP.TextDocumentEdit"/> for the input list of changed documents. /// Additionally maps the locations of the changed documents if necessary. /// </summary> public static async Task<LSP.TextDocumentEdit[]> ChangedDocumentsToTextDocumentEditsAsync<T>(IEnumerable<DocumentId> changedDocuments, Func<DocumentId, T> getNewDocumentFunc, Func<DocumentId, T> getOldDocumentFunc, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) where T : TextDocument { using var _ = ArrayBuilder<(Uri Uri, LSP.TextEdit TextEdit)>.GetInstance(out var uriToTextEdits); foreach (var docId in changedDocuments) { var newDocument = getNewDocumentFunc(docId); var oldDocument = getOldDocumentFunc(docId); var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); ImmutableArray<TextChange> textChanges; // Normal documents have a unique service for calculating minimal text edits. If we used the standard 'GetTextChanges' // method instead, we would get a change that spans the entire document, which we ideally want to avoid. if (newDocument is Document newDoc && oldDocument is Document oldDoc) { Contract.ThrowIfNull(textDiffService); textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false); } else { var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); textChanges = newText.GetTextChanges(oldText).ToImmutableArray(); } // Map all the text changes' spans for this document. var mappedResults = await GetMappedSpanResultAsync(oldDocument, textChanges.Select(tc => tc.Span).ToImmutableArray(), cancellationToken).ConfigureAwait(false); if (mappedResults == null) { // There's no span mapping available, just create text edits from the original text changes. foreach (var textChange in textChanges) { uriToTextEdits.Add((oldDocument.GetURI(), TextChangeToTextEdit(textChange, oldText))); } } else { // We have mapping results, so create text edits from the mapped text change spans. for (var i = 0; i < textChanges.Length; i++) { var mappedSpan = mappedResults.Value[i]; var textChange = textChanges[i]; if (!mappedSpan.IsDefault) { uriToTextEdits.Add((GetUriFromFilePath(mappedSpan.FilePath), new LSP.TextEdit { Range = MappedSpanResultToRange(mappedSpan), NewText = textChange.NewText ?? string.Empty })); } } } } var documentEdits = uriToTextEdits.GroupBy(uriAndEdit => uriAndEdit.Uri, uriAndEdit => uriAndEdit.TextEdit, (uri, edits) => new TextDocumentEdit { TextDocument = new VersionedTextDocumentIdentifier { Uri = uri }, Edits = edits.ToArray(), }).ToArray(); return documentEdits; } public static async Task<LSP.Location?> TextSpanToLocationAsync( Document document, TextSpan textSpan, bool isStale, CancellationToken cancellationToken) { var result = await GetMappedSpanResultAsync(document, ImmutableArray.Create(textSpan), cancellationToken).ConfigureAwait(false); if (result == null) { return await ConvertTextSpanToLocation(document, textSpan, isStale, cancellationToken).ConfigureAwait(false); } var mappedSpan = result.Value.Single(); if (mappedSpan.IsDefault) { return await ConvertTextSpanToLocation(document, textSpan, isStale, cancellationToken).ConfigureAwait(false); } return new LSP.Location { Uri = GetUriFromFilePath(mappedSpan.FilePath), Range = MappedSpanResultToRange(mappedSpan) }; static async Task<LSP.Location> ConvertTextSpanToLocation( Document document, TextSpan span, bool isStale, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (isStale) { // in the case of a stale item, the span may be out of bounds of the document. Cap // us to the end of the document as that's where we're going to navigate the user // to. span = TextSpan.FromBounds( Math.Min(text.Length, span.Start), Math.Min(text.Length, span.End)); } return ConvertTextSpanWithTextToLocation(span, text, document.GetURI()); } static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri) { var location = new LSP.Location { Uri = documentUri, Range = TextSpanToRange(span, text), }; return location; } } public static LSP.SymbolKind NavigateToKindToSymbolKind(string kind) { if (Enum.TryParse<LSP.SymbolKind>(kind, out var symbolKind)) { return symbolKind; } // TODO - Define conversion from NavigateToItemKind to LSP Symbol kind switch (kind) { case NavigateToItemKind.EnumItem: return LSP.SymbolKind.EnumMember; case NavigateToItemKind.Structure: return LSP.SymbolKind.Struct; case NavigateToItemKind.Delegate: return LSP.SymbolKind.Function; default: return LSP.SymbolKind.Object; } } public static LSP.DocumentHighlightKind HighlightSpanKindToDocumentHighlightKind(HighlightSpanKind kind) { switch (kind) { case HighlightSpanKind.Reference: return LSP.DocumentHighlightKind.Read; case HighlightSpanKind.WrittenReference: return LSP.DocumentHighlightKind.Write; default: return LSP.DocumentHighlightKind.Text; } } public static Glyph SymbolKindToGlyph(LSP.SymbolKind kind) { switch (kind) { case LSP.SymbolKind.File: return Glyph.CSharpFile; case LSP.SymbolKind.Module: return Glyph.ModulePublic; case LSP.SymbolKind.Namespace: return Glyph.Namespace; case LSP.SymbolKind.Package: return Glyph.Assembly; case LSP.SymbolKind.Class: return Glyph.ClassPublic; case LSP.SymbolKind.Method: return Glyph.MethodPublic; case LSP.SymbolKind.Property: return Glyph.PropertyPublic; case LSP.SymbolKind.Field: return Glyph.FieldPublic; case LSP.SymbolKind.Constructor: return Glyph.MethodPublic; case LSP.SymbolKind.Enum: return Glyph.EnumPublic; case LSP.SymbolKind.Interface: return Glyph.InterfacePublic; case LSP.SymbolKind.Function: return Glyph.DelegatePublic; case LSP.SymbolKind.Variable: return Glyph.Local; case LSP.SymbolKind.Constant: case LSP.SymbolKind.Number: return Glyph.ConstantPublic; case LSP.SymbolKind.String: case LSP.SymbolKind.Boolean: case LSP.SymbolKind.Array: case LSP.SymbolKind.Object: case LSP.SymbolKind.Key: case LSP.SymbolKind.Null: return Glyph.Local; case LSP.SymbolKind.EnumMember: return Glyph.EnumMemberPublic; case LSP.SymbolKind.Struct: return Glyph.StructurePublic; case LSP.SymbolKind.Event: return Glyph.EventPublic; case LSP.SymbolKind.Operator: return Glyph.Operator; case LSP.SymbolKind.TypeParameter: return Glyph.TypeParameter; default: return Glyph.None; } } public static LSP.SymbolKind GlyphToSymbolKind(Glyph glyph) { // Glyph kinds have accessibility modifiers in their name, e.g. ClassPrivate. // Remove the accessibility modifier and try to convert to LSP symbol kind. var glyphString = glyph.ToString().Replace(nameof(Accessibility.Public), string.Empty) .Replace(nameof(Accessibility.Protected), string.Empty) .Replace(nameof(Accessibility.Private), string.Empty) .Replace(nameof(Accessibility.Internal), string.Empty); if (Enum.TryParse<LSP.SymbolKind>(glyphString, out var symbolKind)) { return symbolKind; } switch (glyph) { case Glyph.Assembly: case Glyph.BasicProject: case Glyph.CSharpProject: case Glyph.NuGet: return LSP.SymbolKind.Package; case Glyph.BasicFile: case Glyph.CSharpFile: return LSP.SymbolKind.File; case Glyph.DelegatePublic: case Glyph.DelegateProtected: case Glyph.DelegatePrivate: case Glyph.DelegateInternal: case Glyph.ExtensionMethodPublic: case Glyph.ExtensionMethodProtected: case Glyph.ExtensionMethodPrivate: case Glyph.ExtensionMethodInternal: return LSP.SymbolKind.Method; case Glyph.Local: case Glyph.Parameter: case Glyph.RangeVariable: case Glyph.Reference: return LSP.SymbolKind.Variable; case Glyph.StructurePublic: case Glyph.StructureProtected: case Glyph.StructurePrivate: case Glyph.StructureInternal: return LSP.SymbolKind.Struct; default: return LSP.SymbolKind.Object; } } public static Glyph CompletionItemKindToGlyph(LSP.CompletionItemKind kind) { switch (kind) { case LSP.CompletionItemKind.Text: return Glyph.None; case LSP.CompletionItemKind.Method: case LSP.CompletionItemKind.Constructor: case LSP.CompletionItemKind.Function: // We don't use Function, but map it just in case. It has the same icon as Method in VS and VS Code return Glyph.MethodPublic; case LSP.CompletionItemKind.Field: return Glyph.FieldPublic; case LSP.CompletionItemKind.Variable: case LSP.CompletionItemKind.Unit: case LSP.CompletionItemKind.Value: return Glyph.Local; case LSP.CompletionItemKind.Class: return Glyph.ClassPublic; case LSP.CompletionItemKind.Interface: return Glyph.InterfacePublic; case LSP.CompletionItemKind.Module: return Glyph.ModulePublic; case LSP.CompletionItemKind.Property: return Glyph.PropertyPublic; case LSP.CompletionItemKind.Enum: return Glyph.EnumPublic; case LSP.CompletionItemKind.Keyword: return Glyph.Keyword; case LSP.CompletionItemKind.Snippet: return Glyph.Snippet; case LSP.CompletionItemKind.Color: return Glyph.None; case LSP.CompletionItemKind.File: return Glyph.CSharpFile; case LSP.CompletionItemKind.Reference: return Glyph.Reference; case LSP.CompletionItemKind.Folder: return Glyph.OpenFolder; case LSP.CompletionItemKind.EnumMember: return Glyph.EnumMemberPublic; case LSP.CompletionItemKind.Constant: return Glyph.ConstantPublic; case LSP.CompletionItemKind.Struct: return Glyph.StructurePublic; case LSP.CompletionItemKind.Event: return Glyph.EventPublic; case LSP.CompletionItemKind.Operator: return Glyph.Operator; case LSP.CompletionItemKind.TypeParameter: return Glyph.TypeParameter; default: return Glyph.None; } } // The mappings here are roughly based off of SymbolUsageInfoExtensions.ToSymbolReferenceKinds. public static LSP.ReferenceKind[] SymbolUsageInfoToReferenceKinds(SymbolUsageInfo symbolUsageInfo) { using var _ = ArrayBuilder<LSP.ReferenceKind>.GetInstance(out var referenceKinds); if (symbolUsageInfo.ValueUsageInfoOpt.HasValue) { var usageInfo = symbolUsageInfo.ValueUsageInfoOpt.Value; if (usageInfo.IsReadFrom()) { referenceKinds.Add(LSP.ReferenceKind.Read); } if (usageInfo.IsWrittenTo()) { referenceKinds.Add(LSP.ReferenceKind.Write); } if (usageInfo.IsReference()) { referenceKinds.Add(LSP.ReferenceKind.Reference); } if (usageInfo.IsNameOnly()) { referenceKinds.Add(LSP.ReferenceKind.Name); } } if (symbolUsageInfo.TypeOrNamespaceUsageInfoOpt.HasValue) { var usageInfo = symbolUsageInfo.TypeOrNamespaceUsageInfoOpt.Value; if ((usageInfo & TypeOrNamespaceUsageInfo.Qualified) != 0) { referenceKinds.Add(LSP.ReferenceKind.Qualified); } if ((usageInfo & TypeOrNamespaceUsageInfo.TypeArgument) != 0) { referenceKinds.Add(LSP.ReferenceKind.TypeArgument); } if ((usageInfo & TypeOrNamespaceUsageInfo.TypeConstraint) != 0) { referenceKinds.Add(LSP.ReferenceKind.TypeConstraint); } if ((usageInfo & TypeOrNamespaceUsageInfo.Base) != 0) { referenceKinds.Add(LSP.ReferenceKind.BaseType); } // Preserving the same mapping logic that SymbolUsageInfoExtensions.ToSymbolReferenceKinds uses if ((usageInfo & TypeOrNamespaceUsageInfo.ObjectCreation) != 0) { referenceKinds.Add(LSP.ReferenceKind.Constructor); } if ((usageInfo & TypeOrNamespaceUsageInfo.Import) != 0) { referenceKinds.Add(LSP.ReferenceKind.Import); } // Preserving the same mapping logic that SymbolUsageInfoExtensions.ToSymbolReferenceKinds uses if ((usageInfo & TypeOrNamespaceUsageInfo.NamespaceDeclaration) != 0) { referenceKinds.Add(LSP.ReferenceKind.Declaration); } } return referenceKinds.ToArray(); } public static string ProjectIdToProjectContextId(ProjectId id) { return id.Id + "|" + id.DebugName; } public static ProjectId ProjectContextToProjectId(ProjectContext projectContext) { var delimiter = projectContext.Id.IndexOf('|'); return ProjectId.CreateFromSerialized( Guid.Parse(projectContext.Id.Substring(0, delimiter)), debugName: projectContext.Id.Substring(delimiter + 1)); } public static async Task<DocumentOptionSet> FormattingOptionsToDocumentOptionsAsync( LSP.FormattingOptions options, Document document, CancellationToken cancellationToken) { var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); // LSP doesn't currently support indent size as an option. However, except in special // circumstances, indent size is usually equivalent to tab size, so we'll just set it. var updatedOptions = documentOptions .WithChangedOption(Formatting.FormattingOptions.UseTabs, !options.InsertSpaces) .WithChangedOption(Formatting.FormattingOptions.TabSize, options.TabSize) .WithChangedOption(Formatting.FormattingOptions.IndentationSize, options.TabSize); return updatedOptions; } public static LSP.MarkupContent GetDocumentationMarkupContent(ImmutableArray<TaggedText> tags, Document document, bool featureSupportsMarkdown) => GetDocumentationMarkupContent(tags, document.Project.Language, featureSupportsMarkdown); public static LSP.MarkupContent GetDocumentationMarkupContent(ImmutableArray<TaggedText> tags, string language, bool featureSupportsMarkdown) { if (!featureSupportsMarkdown) { return new LSP.MarkupContent { Kind = LSP.MarkupKind.PlainText, Value = tags.GetFullText(), }; } var builder = new StringBuilder(); var isInCodeBlock = false; foreach (var taggedText in tags) { switch (taggedText.Tag) { case TextTags.CodeBlockStart: var codeBlockLanguageName = GetCodeBlockLanguageName(language); builder.Append($"```{codeBlockLanguageName}{Environment.NewLine}"); builder.Append(taggedText.Text); isInCodeBlock = true; break; case TextTags.CodeBlockEnd: builder.Append($"{Environment.NewLine}```{Environment.NewLine}"); builder.Append(taggedText.Text); isInCodeBlock = false; break; case TextTags.LineBreak: // A line ending with double space and a new line indicates to markdown // to render a single-spaced line break. builder.Append(" "); builder.Append(Environment.NewLine); break; default: var styledText = GetStyledText(taggedText, isInCodeBlock); builder.Append(styledText); break; } } return new LSP.MarkupContent { Kind = LSP.MarkupKind.Markdown, Value = builder.ToString(), }; static string GetCodeBlockLanguageName(string language) { return language switch { (LanguageNames.CSharp) => CSharpMarkdownLanguageName, (LanguageNames.VisualBasic) => VisualBasicMarkdownLanguageName, _ => throw new InvalidOperationException($"{language} is not supported"), }; } static string GetStyledText(TaggedText taggedText, bool isInCodeBlock) { var text = isInCodeBlock ? taggedText.Text : s_markdownEscapeRegex.Replace(taggedText.Text, @"\$1"); // For non-cref links, the URI is present in both the hint and target. if (!string.IsNullOrEmpty(taggedText.NavigationHint) && taggedText.NavigationHint == taggedText.NavigationTarget) return $"[{text}]({taggedText.NavigationHint})"; // Markdown ignores spaces at the start of lines outside of code blocks, // so to get indented lines we replace the spaces with these. if (!isInCodeBlock) text = text.Replace(" ", "&nbsp;"); return taggedText.Style switch { TaggedTextStyle.None => text, TaggedTextStyle.Strong => $"**{text}**", TaggedTextStyle.Emphasis => $"_{text}_", TaggedTextStyle.Underline => $"<u>{text}</u>", TaggedTextStyle.Code => $"`{text}`", _ => text, }; } } private static async Task<ImmutableArray<MappedSpanResult>?> GetMappedSpanResultAsync(TextDocument textDocument, ImmutableArray<TextSpan> textSpans, CancellationToken cancellationToken) { if (textDocument is not Document document) { return null; } var spanMappingService = document.Services.GetService<ISpanMappingService>(); if (spanMappingService == null) { return null; } var mappedSpanResult = await spanMappingService.MapSpansAsync(document, textSpans, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(textSpans.Length == mappedSpanResult.Length, $"The number of input spans {textSpans.Length} should match the number of mapped spans returned {mappedSpanResult.Length}"); return mappedSpanResult; } private static LSP.Range MappedSpanResultToRange(MappedSpanResult mappedSpanResult) { return new LSP.Range { Start = LinePositionToPosition(mappedSpanResult.LinePositionSpan.Start), End = LinePositionToPosition(mappedSpanResult.LinePositionSpan.End) }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using Logger = Microsoft.CodeAnalysis.Internal.Log.Logger; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer { internal static class ProtocolConversions { private const string CSharpMarkdownLanguageName = "csharp"; private const string VisualBasicMarkdownLanguageName = "vb"; private static readonly Regex s_markdownEscapeRegex = new(@"([\\`\*_\{\}\[\]\(\)#+\-\.!])", RegexOptions.Compiled); // NOTE: While the spec allows it, don't use Function and Method, as both VS and VS Code display them the same way // which can confuse users public static readonly Dictionary<string, LSP.CompletionItemKind> RoslynTagToCompletionItemKind = new Dictionary<string, LSP.CompletionItemKind>() { { WellKnownTags.Public, LSP.CompletionItemKind.Keyword }, { WellKnownTags.Protected, LSP.CompletionItemKind.Keyword }, { WellKnownTags.Private, LSP.CompletionItemKind.Keyword }, { WellKnownTags.Internal, LSP.CompletionItemKind.Keyword }, { WellKnownTags.File, LSP.CompletionItemKind.File }, { WellKnownTags.Project, LSP.CompletionItemKind.File }, { WellKnownTags.Folder, LSP.CompletionItemKind.Folder }, { WellKnownTags.Assembly, LSP.CompletionItemKind.File }, { WellKnownTags.Class, LSP.CompletionItemKind.Class }, { WellKnownTags.Constant, LSP.CompletionItemKind.Constant }, { WellKnownTags.Delegate, LSP.CompletionItemKind.Method }, { WellKnownTags.Enum, LSP.CompletionItemKind.Enum }, { WellKnownTags.EnumMember, LSP.CompletionItemKind.EnumMember }, { WellKnownTags.Event, LSP.CompletionItemKind.Event }, { WellKnownTags.ExtensionMethod, LSP.CompletionItemKind.Method }, { WellKnownTags.Field, LSP.CompletionItemKind.Field }, { WellKnownTags.Interface, LSP.CompletionItemKind.Interface }, { WellKnownTags.Intrinsic, LSP.CompletionItemKind.Text }, { WellKnownTags.Keyword, LSP.CompletionItemKind.Keyword }, { WellKnownTags.Label, LSP.CompletionItemKind.Text }, { WellKnownTags.Local, LSP.CompletionItemKind.Variable }, { WellKnownTags.Namespace, LSP.CompletionItemKind.Text }, { WellKnownTags.Method, LSP.CompletionItemKind.Method }, { WellKnownTags.Module, LSP.CompletionItemKind.Module }, { WellKnownTags.Operator, LSP.CompletionItemKind.Operator }, { WellKnownTags.Parameter, LSP.CompletionItemKind.Value }, { WellKnownTags.Property, LSP.CompletionItemKind.Property }, { WellKnownTags.RangeVariable, LSP.CompletionItemKind.Variable }, { WellKnownTags.Reference, LSP.CompletionItemKind.Reference }, { WellKnownTags.Structure, LSP.CompletionItemKind.Struct }, { WellKnownTags.TypeParameter, LSP.CompletionItemKind.TypeParameter }, { WellKnownTags.Snippet, LSP.CompletionItemKind.Snippet }, { WellKnownTags.Error, LSP.CompletionItemKind.Text }, { WellKnownTags.Warning, LSP.CompletionItemKind.Text }, { WellKnownTags.StatusInformation, LSP.CompletionItemKind.Text }, { WellKnownTags.AddReference, LSP.CompletionItemKind.Text }, { WellKnownTags.NuGet, LSP.CompletionItemKind.Text } }; // TO-DO: More LSP.CompletionTriggerKind mappings are required to properly map to Roslyn CompletionTriggerKinds. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1178726 public static async Task<Completion.CompletionTrigger> LSPToRoslynCompletionTriggerAsync( LSP.CompletionContext? context, Document document, int position, CancellationToken cancellationToken) { if (context is null) { // Some LSP clients don't support sending extra context, so all we can do is invoke return Completion.CompletionTrigger.Invoke; } else if (context.TriggerKind is LSP.CompletionTriggerKind.Invoked or LSP.CompletionTriggerKind.TriggerForIncompleteCompletions) { if (context is not LSP.VSCompletionContext vsCompletionContext) { return Completion.CompletionTrigger.Invoke; } switch (vsCompletionContext.InvokeKind) { case LSP.VSCompletionInvokeKind.Explicit: return Completion.CompletionTrigger.Invoke; case LSP.VSCompletionInvokeKind.Typing: var insertionChar = await GetInsertionCharacterAsync(document, position, cancellationToken).ConfigureAwait(false); return Completion.CompletionTrigger.CreateInsertionTrigger(insertionChar); case LSP.VSCompletionInvokeKind.Deletion: Contract.ThrowIfNull(context.TriggerCharacter); Contract.ThrowIfFalse(char.TryParse(context.TriggerCharacter, out var triggerChar)); return Completion.CompletionTrigger.CreateDeletionTrigger(triggerChar); default: // LSP added an InvokeKind that we need to support. Logger.Log(FunctionId.LSPCompletion_MissingLSPCompletionInvokeKind); return Completion.CompletionTrigger.Invoke; } } else if (context.TriggerKind is LSP.CompletionTriggerKind.TriggerCharacter) { Contract.ThrowIfNull(context.TriggerCharacter); Contract.ThrowIfFalse(char.TryParse(context.TriggerCharacter, out var triggerChar)); return Completion.CompletionTrigger.CreateInsertionTrigger(triggerChar); } else { // LSP added a TriggerKind that we need to support. Logger.Log(FunctionId.LSPCompletion_MissingLSPCompletionTriggerKind); return Completion.CompletionTrigger.Invoke; } // Local functions static async Task<char> GetInsertionCharacterAsync(Document document, int position, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use 'position - 1' here since we want to find the character that was just inserted. Contract.ThrowIfTrue(position < 1); var triggerCharacter = text[position - 1]; return triggerCharacter; } } public static Uri GetUriFromFilePath(string? filePath) { if (filePath is null) { throw new ArgumentNullException(nameof(filePath)); } return new Uri(filePath, UriKind.Absolute); } public static LSP.TextDocumentPositionParams PositionToTextDocumentPositionParams(int position, SourceText text, Document document) { return new LSP.TextDocumentPositionParams() { TextDocument = DocumentToTextDocumentIdentifier(document), Position = LinePositionToPosition(text.Lines.GetLinePosition(position)) }; } public static LSP.TextDocumentIdentifier DocumentToTextDocumentIdentifier(Document document) => new LSP.TextDocumentIdentifier { Uri = document.GetURI() }; public static LSP.VersionedTextDocumentIdentifier DocumentToVersionedTextDocumentIdentifier(Document document) => new LSP.VersionedTextDocumentIdentifier { Uri = document.GetURI() }; public static LinePosition PositionToLinePosition(LSP.Position position) => new LinePosition(position.Line, position.Character); public static LinePositionSpan RangeToLinePositionSpan(LSP.Range range) => new LinePositionSpan(PositionToLinePosition(range.Start), PositionToLinePosition(range.End)); public static TextSpan RangeToTextSpan(LSP.Range range, SourceText text) { var linePositionSpan = RangeToLinePositionSpan(range); return text.Lines.GetTextSpan(linePositionSpan); } public static LSP.TextEdit TextChangeToTextEdit(TextChange textChange, SourceText oldText) { Contract.ThrowIfNull(textChange.NewText); return new LSP.TextEdit { NewText = textChange.NewText, Range = TextSpanToRange(textChange.Span, oldText) }; } public static TextChange ContentChangeEventToTextChange(LSP.TextDocumentContentChangeEvent changeEvent, SourceText text) => new TextChange(RangeToTextSpan(changeEvent.Range, text), changeEvent.Text); public static LSP.Position LinePositionToPosition(LinePosition linePosition) => new LSP.Position { Line = linePosition.Line, Character = linePosition.Character }; public static LSP.Range LinePositionToRange(LinePositionSpan linePositionSpan) => new LSP.Range { Start = LinePositionToPosition(linePositionSpan.Start), End = LinePositionToPosition(linePositionSpan.End) }; public static LSP.Range TextSpanToRange(TextSpan textSpan, SourceText text) { var linePosSpan = text.Lines.GetLinePositionSpan(textSpan); return LinePositionToRange(linePosSpan); } public static Task<LSP.Location?> DocumentSpanToLocationAsync(DocumentSpan documentSpan, CancellationToken cancellationToken) => TextSpanToLocationAsync(documentSpan.Document, documentSpan.SourceSpan, isStale: false, cancellationToken); public static async Task<LSP.LocationWithText?> DocumentSpanToLocationWithTextAsync( DocumentSpan documentSpan, ClassifiedTextElement text, CancellationToken cancellationToken) { var location = await TextSpanToLocationAsync( documentSpan.Document, documentSpan.SourceSpan, isStale: false, cancellationToken).ConfigureAwait(false); return location == null ? null : new LSP.LocationWithText { Uri = location.Uri, Range = location.Range, Text = text }; } /// <summary> /// Compute all the <see cref="LSP.TextDocumentEdit"/> for the input list of changed documents. /// Additionally maps the locations of the changed documents if necessary. /// </summary> public static async Task<LSP.TextDocumentEdit[]> ChangedDocumentsToTextDocumentEditsAsync<T>(IEnumerable<DocumentId> changedDocuments, Func<DocumentId, T> getNewDocumentFunc, Func<DocumentId, T> getOldDocumentFunc, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) where T : TextDocument { using var _ = ArrayBuilder<(Uri Uri, LSP.TextEdit TextEdit)>.GetInstance(out var uriToTextEdits); foreach (var docId in changedDocuments) { var newDocument = getNewDocumentFunc(docId); var oldDocument = getOldDocumentFunc(docId); var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); ImmutableArray<TextChange> textChanges; // Normal documents have a unique service for calculating minimal text edits. If we used the standard 'GetTextChanges' // method instead, we would get a change that spans the entire document, which we ideally want to avoid. if (newDocument is Document newDoc && oldDocument is Document oldDoc) { Contract.ThrowIfNull(textDiffService); textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false); } else { var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); textChanges = newText.GetTextChanges(oldText).ToImmutableArray(); } // Map all the text changes' spans for this document. var mappedResults = await GetMappedSpanResultAsync(oldDocument, textChanges.Select(tc => tc.Span).ToImmutableArray(), cancellationToken).ConfigureAwait(false); if (mappedResults == null) { // There's no span mapping available, just create text edits from the original text changes. foreach (var textChange in textChanges) { uriToTextEdits.Add((oldDocument.GetURI(), TextChangeToTextEdit(textChange, oldText))); } } else { // We have mapping results, so create text edits from the mapped text change spans. for (var i = 0; i < textChanges.Length; i++) { var mappedSpan = mappedResults.Value[i]; var textChange = textChanges[i]; if (!mappedSpan.IsDefault) { uriToTextEdits.Add((GetUriFromFilePath(mappedSpan.FilePath), new LSP.TextEdit { Range = MappedSpanResultToRange(mappedSpan), NewText = textChange.NewText ?? string.Empty })); } } } } var documentEdits = uriToTextEdits.GroupBy(uriAndEdit => uriAndEdit.Uri, uriAndEdit => uriAndEdit.TextEdit, (uri, edits) => new TextDocumentEdit { TextDocument = new VersionedTextDocumentIdentifier { Uri = uri }, Edits = edits.ToArray(), }).ToArray(); return documentEdits; } public static async Task<LSP.Location?> TextSpanToLocationAsync( Document document, TextSpan textSpan, bool isStale, CancellationToken cancellationToken) { var result = await GetMappedSpanResultAsync(document, ImmutableArray.Create(textSpan), cancellationToken).ConfigureAwait(false); if (result == null) { return await ConvertTextSpanToLocation(document, textSpan, isStale, cancellationToken).ConfigureAwait(false); } var mappedSpan = result.Value.Single(); if (mappedSpan.IsDefault) { return await ConvertTextSpanToLocation(document, textSpan, isStale, cancellationToken).ConfigureAwait(false); } return new LSP.Location { Uri = GetUriFromFilePath(mappedSpan.FilePath), Range = MappedSpanResultToRange(mappedSpan) }; static async Task<LSP.Location> ConvertTextSpanToLocation( Document document, TextSpan span, bool isStale, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (isStale) { // in the case of a stale item, the span may be out of bounds of the document. Cap // us to the end of the document as that's where we're going to navigate the user // to. span = TextSpan.FromBounds( Math.Min(text.Length, span.Start), Math.Min(text.Length, span.End)); } return ConvertTextSpanWithTextToLocation(span, text, document.GetURI()); } static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri) { var location = new LSP.Location { Uri = documentUri, Range = TextSpanToRange(span, text), }; return location; } } public static LSP.CodeDescription? HelpLinkToCodeDescription(string? helpLink) { if (Uri.TryCreate(helpLink, UriKind.RelativeOrAbsolute, out var uri)) { return new LSP.CodeDescription { Href = uri, }; } return null; } public static LSP.SymbolKind NavigateToKindToSymbolKind(string kind) { if (Enum.TryParse<LSP.SymbolKind>(kind, out var symbolKind)) { return symbolKind; } // TODO - Define conversion from NavigateToItemKind to LSP Symbol kind switch (kind) { case NavigateToItemKind.EnumItem: return LSP.SymbolKind.EnumMember; case NavigateToItemKind.Structure: return LSP.SymbolKind.Struct; case NavigateToItemKind.Delegate: return LSP.SymbolKind.Function; default: return LSP.SymbolKind.Object; } } public static LSP.DocumentHighlightKind HighlightSpanKindToDocumentHighlightKind(HighlightSpanKind kind) { switch (kind) { case HighlightSpanKind.Reference: return LSP.DocumentHighlightKind.Read; case HighlightSpanKind.WrittenReference: return LSP.DocumentHighlightKind.Write; default: return LSP.DocumentHighlightKind.Text; } } public static Glyph SymbolKindToGlyph(LSP.SymbolKind kind) { switch (kind) { case LSP.SymbolKind.File: return Glyph.CSharpFile; case LSP.SymbolKind.Module: return Glyph.ModulePublic; case LSP.SymbolKind.Namespace: return Glyph.Namespace; case LSP.SymbolKind.Package: return Glyph.Assembly; case LSP.SymbolKind.Class: return Glyph.ClassPublic; case LSP.SymbolKind.Method: return Glyph.MethodPublic; case LSP.SymbolKind.Property: return Glyph.PropertyPublic; case LSP.SymbolKind.Field: return Glyph.FieldPublic; case LSP.SymbolKind.Constructor: return Glyph.MethodPublic; case LSP.SymbolKind.Enum: return Glyph.EnumPublic; case LSP.SymbolKind.Interface: return Glyph.InterfacePublic; case LSP.SymbolKind.Function: return Glyph.DelegatePublic; case LSP.SymbolKind.Variable: return Glyph.Local; case LSP.SymbolKind.Constant: case LSP.SymbolKind.Number: return Glyph.ConstantPublic; case LSP.SymbolKind.String: case LSP.SymbolKind.Boolean: case LSP.SymbolKind.Array: case LSP.SymbolKind.Object: case LSP.SymbolKind.Key: case LSP.SymbolKind.Null: return Glyph.Local; case LSP.SymbolKind.EnumMember: return Glyph.EnumMemberPublic; case LSP.SymbolKind.Struct: return Glyph.StructurePublic; case LSP.SymbolKind.Event: return Glyph.EventPublic; case LSP.SymbolKind.Operator: return Glyph.Operator; case LSP.SymbolKind.TypeParameter: return Glyph.TypeParameter; default: return Glyph.None; } } public static LSP.SymbolKind GlyphToSymbolKind(Glyph glyph) { // Glyph kinds have accessibility modifiers in their name, e.g. ClassPrivate. // Remove the accessibility modifier and try to convert to LSP symbol kind. var glyphString = glyph.ToString().Replace(nameof(Accessibility.Public), string.Empty) .Replace(nameof(Accessibility.Protected), string.Empty) .Replace(nameof(Accessibility.Private), string.Empty) .Replace(nameof(Accessibility.Internal), string.Empty); if (Enum.TryParse<LSP.SymbolKind>(glyphString, out var symbolKind)) { return symbolKind; } switch (glyph) { case Glyph.Assembly: case Glyph.BasicProject: case Glyph.CSharpProject: case Glyph.NuGet: return LSP.SymbolKind.Package; case Glyph.BasicFile: case Glyph.CSharpFile: return LSP.SymbolKind.File; case Glyph.DelegatePublic: case Glyph.DelegateProtected: case Glyph.DelegatePrivate: case Glyph.DelegateInternal: case Glyph.ExtensionMethodPublic: case Glyph.ExtensionMethodProtected: case Glyph.ExtensionMethodPrivate: case Glyph.ExtensionMethodInternal: return LSP.SymbolKind.Method; case Glyph.Local: case Glyph.Parameter: case Glyph.RangeVariable: case Glyph.Reference: return LSP.SymbolKind.Variable; case Glyph.StructurePublic: case Glyph.StructureProtected: case Glyph.StructurePrivate: case Glyph.StructureInternal: return LSP.SymbolKind.Struct; default: return LSP.SymbolKind.Object; } } public static Glyph CompletionItemKindToGlyph(LSP.CompletionItemKind kind) { switch (kind) { case LSP.CompletionItemKind.Text: return Glyph.None; case LSP.CompletionItemKind.Method: case LSP.CompletionItemKind.Constructor: case LSP.CompletionItemKind.Function: // We don't use Function, but map it just in case. It has the same icon as Method in VS and VS Code return Glyph.MethodPublic; case LSP.CompletionItemKind.Field: return Glyph.FieldPublic; case LSP.CompletionItemKind.Variable: case LSP.CompletionItemKind.Unit: case LSP.CompletionItemKind.Value: return Glyph.Local; case LSP.CompletionItemKind.Class: return Glyph.ClassPublic; case LSP.CompletionItemKind.Interface: return Glyph.InterfacePublic; case LSP.CompletionItemKind.Module: return Glyph.ModulePublic; case LSP.CompletionItemKind.Property: return Glyph.PropertyPublic; case LSP.CompletionItemKind.Enum: return Glyph.EnumPublic; case LSP.CompletionItemKind.Keyword: return Glyph.Keyword; case LSP.CompletionItemKind.Snippet: return Glyph.Snippet; case LSP.CompletionItemKind.Color: return Glyph.None; case LSP.CompletionItemKind.File: return Glyph.CSharpFile; case LSP.CompletionItemKind.Reference: return Glyph.Reference; case LSP.CompletionItemKind.Folder: return Glyph.OpenFolder; case LSP.CompletionItemKind.EnumMember: return Glyph.EnumMemberPublic; case LSP.CompletionItemKind.Constant: return Glyph.ConstantPublic; case LSP.CompletionItemKind.Struct: return Glyph.StructurePublic; case LSP.CompletionItemKind.Event: return Glyph.EventPublic; case LSP.CompletionItemKind.Operator: return Glyph.Operator; case LSP.CompletionItemKind.TypeParameter: return Glyph.TypeParameter; default: return Glyph.None; } } // The mappings here are roughly based off of SymbolUsageInfoExtensions.ToSymbolReferenceKinds. public static LSP.ReferenceKind[] SymbolUsageInfoToReferenceKinds(SymbolUsageInfo symbolUsageInfo) { using var _ = ArrayBuilder<LSP.ReferenceKind>.GetInstance(out var referenceKinds); if (symbolUsageInfo.ValueUsageInfoOpt.HasValue) { var usageInfo = symbolUsageInfo.ValueUsageInfoOpt.Value; if (usageInfo.IsReadFrom()) { referenceKinds.Add(LSP.ReferenceKind.Read); } if (usageInfo.IsWrittenTo()) { referenceKinds.Add(LSP.ReferenceKind.Write); } if (usageInfo.IsReference()) { referenceKinds.Add(LSP.ReferenceKind.Reference); } if (usageInfo.IsNameOnly()) { referenceKinds.Add(LSP.ReferenceKind.Name); } } if (symbolUsageInfo.TypeOrNamespaceUsageInfoOpt.HasValue) { var usageInfo = symbolUsageInfo.TypeOrNamespaceUsageInfoOpt.Value; if ((usageInfo & TypeOrNamespaceUsageInfo.Qualified) != 0) { referenceKinds.Add(LSP.ReferenceKind.Qualified); } if ((usageInfo & TypeOrNamespaceUsageInfo.TypeArgument) != 0) { referenceKinds.Add(LSP.ReferenceKind.TypeArgument); } if ((usageInfo & TypeOrNamespaceUsageInfo.TypeConstraint) != 0) { referenceKinds.Add(LSP.ReferenceKind.TypeConstraint); } if ((usageInfo & TypeOrNamespaceUsageInfo.Base) != 0) { referenceKinds.Add(LSP.ReferenceKind.BaseType); } // Preserving the same mapping logic that SymbolUsageInfoExtensions.ToSymbolReferenceKinds uses if ((usageInfo & TypeOrNamespaceUsageInfo.ObjectCreation) != 0) { referenceKinds.Add(LSP.ReferenceKind.Constructor); } if ((usageInfo & TypeOrNamespaceUsageInfo.Import) != 0) { referenceKinds.Add(LSP.ReferenceKind.Import); } // Preserving the same mapping logic that SymbolUsageInfoExtensions.ToSymbolReferenceKinds uses if ((usageInfo & TypeOrNamespaceUsageInfo.NamespaceDeclaration) != 0) { referenceKinds.Add(LSP.ReferenceKind.Declaration); } } return referenceKinds.ToArray(); } public static string ProjectIdToProjectContextId(ProjectId id) { return id.Id + "|" + id.DebugName; } public static ProjectId ProjectContextToProjectId(ProjectContext projectContext) { var delimiter = projectContext.Id.IndexOf('|'); return ProjectId.CreateFromSerialized( Guid.Parse(projectContext.Id.Substring(0, delimiter)), debugName: projectContext.Id.Substring(delimiter + 1)); } public static async Task<DocumentOptionSet> FormattingOptionsToDocumentOptionsAsync( LSP.FormattingOptions options, Document document, CancellationToken cancellationToken) { var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); // LSP doesn't currently support indent size as an option. However, except in special // circumstances, indent size is usually equivalent to tab size, so we'll just set it. var updatedOptions = documentOptions .WithChangedOption(Formatting.FormattingOptions.UseTabs, !options.InsertSpaces) .WithChangedOption(Formatting.FormattingOptions.TabSize, options.TabSize) .WithChangedOption(Formatting.FormattingOptions.IndentationSize, options.TabSize); return updatedOptions; } public static LSP.MarkupContent GetDocumentationMarkupContent(ImmutableArray<TaggedText> tags, Document document, bool featureSupportsMarkdown) => GetDocumentationMarkupContent(tags, document.Project.Language, featureSupportsMarkdown); public static LSP.MarkupContent GetDocumentationMarkupContent(ImmutableArray<TaggedText> tags, string language, bool featureSupportsMarkdown) { if (!featureSupportsMarkdown) { return new LSP.MarkupContent { Kind = LSP.MarkupKind.PlainText, Value = tags.GetFullText(), }; } var builder = new StringBuilder(); var isInCodeBlock = false; foreach (var taggedText in tags) { switch (taggedText.Tag) { case TextTags.CodeBlockStart: var codeBlockLanguageName = GetCodeBlockLanguageName(language); builder.Append($"```{codeBlockLanguageName}{Environment.NewLine}"); builder.Append(taggedText.Text); isInCodeBlock = true; break; case TextTags.CodeBlockEnd: builder.Append($"{Environment.NewLine}```{Environment.NewLine}"); builder.Append(taggedText.Text); isInCodeBlock = false; break; case TextTags.LineBreak: // A line ending with double space and a new line indicates to markdown // to render a single-spaced line break. builder.Append(" "); builder.Append(Environment.NewLine); break; default: var styledText = GetStyledText(taggedText, isInCodeBlock); builder.Append(styledText); break; } } return new LSP.MarkupContent { Kind = LSP.MarkupKind.Markdown, Value = builder.ToString(), }; static string GetCodeBlockLanguageName(string language) { return language switch { (LanguageNames.CSharp) => CSharpMarkdownLanguageName, (LanguageNames.VisualBasic) => VisualBasicMarkdownLanguageName, _ => throw new InvalidOperationException($"{language} is not supported"), }; } static string GetStyledText(TaggedText taggedText, bool isInCodeBlock) { var text = isInCodeBlock ? taggedText.Text : s_markdownEscapeRegex.Replace(taggedText.Text, @"\$1"); // For non-cref links, the URI is present in both the hint and target. if (!string.IsNullOrEmpty(taggedText.NavigationHint) && taggedText.NavigationHint == taggedText.NavigationTarget) return $"[{text}]({taggedText.NavigationHint})"; // Markdown ignores spaces at the start of lines outside of code blocks, // so to get indented lines we replace the spaces with these. if (!isInCodeBlock) text = text.Replace(" ", "&nbsp;"); return taggedText.Style switch { TaggedTextStyle.None => text, TaggedTextStyle.Strong => $"**{text}**", TaggedTextStyle.Emphasis => $"_{text}_", TaggedTextStyle.Underline => $"<u>{text}</u>", TaggedTextStyle.Code => $"`{text}`", _ => text, }; } } private static async Task<ImmutableArray<MappedSpanResult>?> GetMappedSpanResultAsync(TextDocument textDocument, ImmutableArray<TextSpan> textSpans, CancellationToken cancellationToken) { if (textDocument is not Document document) { return null; } var spanMappingService = document.Services.GetService<ISpanMappingService>(); if (spanMappingService == null) { return null; } var mappedSpanResult = await spanMappingService.MapSpansAsync(document, textSpans, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(textSpans.Length == mappedSpanResult.Length, $"The number of input spans {textSpans.Length} should match the number of mapped spans returned {mappedSpanResult.Length}"); return mappedSpanResult; } private static LSP.Range MappedSpanResultToRange(MappedSpanResult mappedSpanResult) { return new LSP.Range { Start = LinePositionToPosition(mappedSpanResult.LinePositionSpan.Start), End = LinePositionToPosition(mappedSpanResult.LinePositionSpan.End) }; } } }
1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : IRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : DiagnosticReport { /// <summary> /// Special value we use to designate workspace diagnostics vs document diagnostics. Document diagnostics /// should always <see cref="DiagnosticReport.Supersedes"/> a workspace diagnostic as the former are 'live' /// while the latter are cached and may be stale. /// </summary> protected const int WorkspaceDiagnosticIdentifier = 1; protected const int DocumentDiagnosticIdentifier = 2; protected readonly IDiagnosticService DiagnosticService; /// <summary> /// Lock to protect <see cref="_documentIdToLastResultId"/> and <see cref="_nextDocumentResultId"/>. /// </summary> private readonly object _gate = new(); /// <summary> /// Mapping of a document to the last result id we reported for it. /// </summary> private readonly Dictionary<(Workspace workspace, DocumentId documentId), string> _documentIdToLastResultId = new(); /// <summary> /// The next available id to label results with. Note that results are tagged on a per-document bases. That /// way we can update diagnostics with the client with per-doc granularity. /// </summary> private long _nextDocumentResultId; public abstract string Method { get; } public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; protected AbstractPullDiagnosticHandler( IDiagnosticService diagnosticService) { DiagnosticService = diagnosticService; DiagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; } public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(TDiagnosticsParams diagnosticsParams); /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. Used so we can avoid resending data for unchanged files. Also /// used so we can report which documents were removed and can have all their diagnostics cleared. /// </summary> protected abstract DiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed in the desired order to process them in. /// </summary> protected abstract ImmutableArray<Document> GetOrderedDocuments(RequestContext context); /// <summary> /// Creates the <see cref="DiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. Subclasses can fill in data specific to their needs as appropriate. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); /// <summary> /// Produce the diagnostics for the specified document. /// </summary> protected abstract Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(RequestContext context, Document document, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken); /// <summary> /// Generate the right diagnostic tags for a particular diagnostic. /// </summary> protected abstract DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData); private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateArgs) { if (updateArgs.DocumentId == null) return; // Ensure we do not clear the cached results while the handler is reading (and possibly then writing) // to the cached results. lock (_gate) { // Whenever we hear about changes to a document, drop the data we've stored for it. We'll recompute it as // necessary on the next request. _documentIdToLastResultId.Remove((updateArgs.Workspace, updateArgs.DocumentId)); } } public async Task<TReport[]?> HandleRequestAsync( TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { context.TraceInformation($"{this.GetType()} started getting diagnostics"); // The progress object we will stream reports to. using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. We can use this to determine both // what to skip, and what files we have to tell the client have been removed. var previousResults = GetPreviousResults(diagnosticsParams) ?? Array.Empty<DiagnosticParams>(); context.TraceInformation($"previousResults.Length={previousResults.Length}"); // First, let the client know if any workspace documents have gone away. That way it can remove those for // the user from squiggles or error-list. HandleRemovedDocuments(context, previousResults, progress); // Create a mapping from documents to the previous results the client says it has for them. That way as we // process documents we know if we should tell the client it should stay the same, or we can tell it what // the updated diagnostics are. var documentToPreviousDiagnosticParams = GetDocumentToPreviousDiagnosticParams(context, previousResults); // Next process each file in priority order. Determine if diagnostics are changed or unchanged since the // last time we notified the client. Report back either to the client so they can update accordingly. var orderedDocuments = GetOrderedDocuments(context); context.TraceInformation($"Processing {orderedDocuments.Length} documents"); foreach (var document in orderedDocuments) { context.TraceInformation($"Processing: {document.FilePath}"); if (!IncludeDocument(document, context.ClientName)) { context.TraceInformation($"Ignoring document '{document.FilePath}' because of razor/client-name mismatch"); continue; } if (HaveDiagnosticsChanged(documentToPreviousDiagnosticParams, document, out var newResultId)) { context.TraceInformation($"Diagnostics were changed for document: {document.FilePath}"); progress.Report(await ComputeAndReportCurrentDiagnosticsAsync(context, document, newResultId, cancellationToken).ConfigureAwait(false)); } else { context.TraceInformation($"Diagnostics were unchanged for document: {document.FilePath}"); // Nothing changed between the last request and this one. Report a (null-diagnostics, // same-result-id) response to the client as that means they should just preserve the current // diagnostics they have for this file. var previousParams = documentToPreviousDiagnosticParams[document]; progress.Report(CreateReport(previousParams.TextDocument, diagnostics: null, previousParams.PreviousResultId)); } } // If we had a progress object, then we will have been reporting to that. Otherwise, take what we've been // collecting and return that. context.TraceInformation($"{this.GetType()} finished getting diagnostics"); return progress.GetValues(); } private static bool IncludeDocument(Document document, string? clientName) { // Documents either belong to Razor or not. We can determine this by checking if the doc has a span-mapping // service or not. If we're not in razor, we do not include razor docs. If we are in razor, we only // include razor docs. var isRazorDoc = document.IsRazorDocument(); var wantsRazorDoc = clientName != null; return wantsRazorDoc == isRazorDoc; } private static Dictionary<Document, DiagnosticParams> GetDocumentToPreviousDiagnosticParams( RequestContext context, DiagnosticParams[] previousResults) { Contract.ThrowIfNull(context.Solution); var result = new Dictionary<Document, DiagnosticParams>(); foreach (var diagnosticParams in previousResults) { if (diagnosticParams.TextDocument != null) { var document = context.Solution.GetDocument(diagnosticParams.TextDocument); if (document != null) result[document] = diagnosticParams; } } return result; } private async Task<TReport> ComputeAndReportCurrentDiagnosticsAsync( RequestContext context, Document document, string resultId, CancellationToken cancellationToken) { // Being asked about this document for the first time. Or being asked again and we have different // diagnostics. Compute and report the current diagnostics info for this document. // Razor has a separate option for determining if they should be in push or pull mode. var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; var workspace = document.Project.Solution.Workspace; var isPull = workspace.IsPullDiagnostics(diagnosticMode); context.TraceInformation($"Getting '{(isPull ? "pull" : "push")}' diagnostics with mode '{diagnosticMode}'"); using var _ = ArrayBuilder<VSDiagnostic>.GetInstance(out var result); if (isPull) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await GetDiagnosticsAsync(context, document, diagnosticMode, cancellationToken).ConfigureAwait(false); context.TraceInformation($"Got {diagnostics.Length} diagnostics"); foreach (var diagnostic in diagnostics) result.Add(ConvertDiagnostic(document, text, diagnostic)); } return CreateReport(ProtocolConversions.DocumentToTextDocumentIdentifier(document), result.ToArray(), resultId); } private void HandleRemovedDocuments(RequestContext context, DiagnosticParams[] previousResults, BufferedProgress<TReport> progress) { Contract.ThrowIfNull(context.Solution); foreach (var previousResult in previousResults) { var textDocument = previousResult.TextDocument; if (textDocument != null) { var document = context.Solution.GetDocument(textDocument); if (document == null) { context.TraceInformation($"Clearing diagnostics for removed document: {textDocument.Uri}"); // Client is asking server about a document that no longer exists (i.e. was removed/deleted from // the workspace). Report a (null-diagnostics, null-result-id) response to the client as that // means they should just consider the file deleted and should remove all diagnostics // information they've cached for it. progress.Report(CreateReport(textDocument, diagnostics: null, resultId: null)); } } } } /// <summary> /// Returns true if diagnostics have changed since the last request and if so, /// calculates a new resultId to use for subsequent computation and caches it. /// </summary> /// <param name="documentToPreviousDiagnosticParams">the resultIds the client sent us.</param> /// <param name="document">the document we are currently calculating results for.</param> /// <param name="newResultId">the resultId to report new diagnostics with if changed.</param> private bool HaveDiagnosticsChanged( Dictionary<Document, DiagnosticParams> documentToPreviousDiagnosticParams, Document document, [NotNullWhen(true)] out string? newResultId) { // Read and write the cached resultId to _documentIdToLastResultId in a single transaction // to prevent in-between updates to _documentIdToLastResultId triggered by OnDiagnosticsUpdated. lock (_gate) { var workspace = document.Project.Solution.Workspace; if (documentToPreviousDiagnosticParams.TryGetValue(document, out var previousParams) && _documentIdToLastResultId.TryGetValue((workspace, document.Id), out var lastReportedResultId) && lastReportedResultId == previousParams.PreviousResultId) { // Our cached resultId for the document matches the resultId the client passed to us. // This means the diagnostics have not changed and we do not need to re-compute. newResultId = null; return false; } // Keep track of the diagnostics we reported here so that we can short-circuit producing diagnostics for // the same diagnostic set in the future. Use a custom result-id per type (doc diagnostics or workspace // diagnostics) so that clients of one don't errantly call into the other. For example, a client // getting document diagnostics should not ask for workspace diagnostics with the result-ids it got for // doc-diagnostics. The two systems are different and cannot share results, or do things like report // what changed between each other. // // Note that we can safely update the map before computation as any cancellation or exception // during computation means that the client will never recieve this resultId and so cannot ask us for it. newResultId = $"{GetType().Name}:{_nextDocumentResultId++}"; _documentIdToLastResultId[(document.Project.Solution.Workspace, document.Id)] = newResultId; return true; } } private VSDiagnostic ConvertDiagnostic(Document document, SourceText text, DiagnosticData diagnosticData) { Contract.ThrowIfNull(diagnosticData.Message, $"Got a document diagnostic that did not have a {nameof(diagnosticData.Message)}"); Contract.ThrowIfNull(diagnosticData.DataLocation, $"Got a document diagnostic that did not have a {nameof(diagnosticData.DataLocation)}"); var project = document.Project; // We currently do not map diagnostics spans as // 1. Razor handles span mapping for razor files on their side. // 2. LSP does not allow us to report document pull diagnostics for a different file path. // 3. The VS LSP client does not support document pull diagnostics for files outside our content type. // 4. This matches classic behavior where we only squiggle the original location anyway. var useMappedSpan = false; return new VSDiagnostic { Source = GetType().Name, Code = diagnosticData.Id, Message = diagnosticData.Message, Severity = ConvertDiagnosticSeverity(diagnosticData.Severity), Range = ProtocolConversions.LinePositionToRange(DiagnosticData.GetLinePositionSpan(diagnosticData.DataLocation, text, useMappedSpan)), Tags = ConvertTags(diagnosticData), DiagnosticType = diagnosticData.Category, Projects = new[] { new ProjectAndContext { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }; } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(DiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. DiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Info => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, DiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\VisualStudio\Xaml\Impl\Implementation\LanguageServer\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> protected static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData, bool potentialDuplicate) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); if (diagnosticData.Severity == DiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (potentialDuplicate) result.Add(VSDiagnosticTags.PotentialDuplicate); result.Add(diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Build) ? VSDiagnosticTags.BuildError : VSDiagnosticTags.IntellisenseError); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary)) result.Add(DiagnosticTag.Unnecessary); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.EditAndContinue)) result.Add(VSDiagnosticTags.EditAndContinueError); return result.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : IRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : DiagnosticReport { /// <summary> /// Special value we use to designate workspace diagnostics vs document diagnostics. Document diagnostics /// should always <see cref="DiagnosticReport.Supersedes"/> a workspace diagnostic as the former are 'live' /// while the latter are cached and may be stale. /// </summary> protected const int WorkspaceDiagnosticIdentifier = 1; protected const int DocumentDiagnosticIdentifier = 2; protected readonly IDiagnosticService DiagnosticService; /// <summary> /// Lock to protect <see cref="_documentIdToLastResultId"/> and <see cref="_nextDocumentResultId"/>. /// </summary> private readonly object _gate = new(); /// <summary> /// Mapping of a document to the last result id we reported for it. /// </summary> private readonly Dictionary<(Workspace workspace, DocumentId documentId), string> _documentIdToLastResultId = new(); /// <summary> /// The next available id to label results with. Note that results are tagged on a per-document bases. That /// way we can update diagnostics with the client with per-doc granularity. /// </summary> private long _nextDocumentResultId; public abstract string Method { get; } public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; protected AbstractPullDiagnosticHandler( IDiagnosticService diagnosticService) { DiagnosticService = diagnosticService; DiagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; } public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(TDiagnosticsParams diagnosticsParams); /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. Used so we can avoid resending data for unchanged files. Also /// used so we can report which documents were removed and can have all their diagnostics cleared. /// </summary> protected abstract DiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed in the desired order to process them in. /// </summary> protected abstract ImmutableArray<Document> GetOrderedDocuments(RequestContext context); /// <summary> /// Creates the <see cref="DiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. Subclasses can fill in data specific to their needs as appropriate. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); /// <summary> /// Produce the diagnostics for the specified document. /// </summary> protected abstract Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(RequestContext context, Document document, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken); /// <summary> /// Generate the right diagnostic tags for a particular diagnostic. /// </summary> protected abstract DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData); private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateArgs) { if (updateArgs.DocumentId == null) return; // Ensure we do not clear the cached results while the handler is reading (and possibly then writing) // to the cached results. lock (_gate) { // Whenever we hear about changes to a document, drop the data we've stored for it. We'll recompute it as // necessary on the next request. _documentIdToLastResultId.Remove((updateArgs.Workspace, updateArgs.DocumentId)); } } public async Task<TReport[]?> HandleRequestAsync( TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { context.TraceInformation($"{this.GetType()} started getting diagnostics"); // The progress object we will stream reports to. using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. We can use this to determine both // what to skip, and what files we have to tell the client have been removed. var previousResults = GetPreviousResults(diagnosticsParams) ?? Array.Empty<DiagnosticParams>(); context.TraceInformation($"previousResults.Length={previousResults.Length}"); // First, let the client know if any workspace documents have gone away. That way it can remove those for // the user from squiggles or error-list. HandleRemovedDocuments(context, previousResults, progress); // Create a mapping from documents to the previous results the client says it has for them. That way as we // process documents we know if we should tell the client it should stay the same, or we can tell it what // the updated diagnostics are. var documentToPreviousDiagnosticParams = GetDocumentToPreviousDiagnosticParams(context, previousResults); // Next process each file in priority order. Determine if diagnostics are changed or unchanged since the // last time we notified the client. Report back either to the client so they can update accordingly. var orderedDocuments = GetOrderedDocuments(context); context.TraceInformation($"Processing {orderedDocuments.Length} documents"); foreach (var document in orderedDocuments) { context.TraceInformation($"Processing: {document.FilePath}"); if (!IncludeDocument(document, context.ClientName)) { context.TraceInformation($"Ignoring document '{document.FilePath}' because of razor/client-name mismatch"); continue; } if (HaveDiagnosticsChanged(documentToPreviousDiagnosticParams, document, out var newResultId)) { context.TraceInformation($"Diagnostics were changed for document: {document.FilePath}"); progress.Report(await ComputeAndReportCurrentDiagnosticsAsync(context, document, newResultId, cancellationToken).ConfigureAwait(false)); } else { context.TraceInformation($"Diagnostics were unchanged for document: {document.FilePath}"); // Nothing changed between the last request and this one. Report a (null-diagnostics, // same-result-id) response to the client as that means they should just preserve the current // diagnostics they have for this file. var previousParams = documentToPreviousDiagnosticParams[document]; progress.Report(CreateReport(previousParams.TextDocument, diagnostics: null, previousParams.PreviousResultId)); } } // If we had a progress object, then we will have been reporting to that. Otherwise, take what we've been // collecting and return that. context.TraceInformation($"{this.GetType()} finished getting diagnostics"); return progress.GetValues(); } private static bool IncludeDocument(Document document, string? clientName) { // Documents either belong to Razor or not. We can determine this by checking if the doc has a span-mapping // service or not. If we're not in razor, we do not include razor docs. If we are in razor, we only // include razor docs. var isRazorDoc = document.IsRazorDocument(); var wantsRazorDoc = clientName != null; return wantsRazorDoc == isRazorDoc; } private static Dictionary<Document, DiagnosticParams> GetDocumentToPreviousDiagnosticParams( RequestContext context, DiagnosticParams[] previousResults) { Contract.ThrowIfNull(context.Solution); var result = new Dictionary<Document, DiagnosticParams>(); foreach (var diagnosticParams in previousResults) { if (diagnosticParams.TextDocument != null) { var document = context.Solution.GetDocument(diagnosticParams.TextDocument); if (document != null) result[document] = diagnosticParams; } } return result; } private async Task<TReport> ComputeAndReportCurrentDiagnosticsAsync( RequestContext context, Document document, string resultId, CancellationToken cancellationToken) { // Being asked about this document for the first time. Or being asked again and we have different // diagnostics. Compute and report the current diagnostics info for this document. // Razor has a separate option for determining if they should be in push or pull mode. var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; var workspace = document.Project.Solution.Workspace; var isPull = workspace.IsPullDiagnostics(diagnosticMode); context.TraceInformation($"Getting '{(isPull ? "pull" : "push")}' diagnostics with mode '{diagnosticMode}'"); using var _ = ArrayBuilder<VSDiagnostic>.GetInstance(out var result); if (isPull) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await GetDiagnosticsAsync(context, document, diagnosticMode, cancellationToken).ConfigureAwait(false); context.TraceInformation($"Got {diagnostics.Length} diagnostics"); foreach (var diagnostic in diagnostics) result.Add(ConvertDiagnostic(document, text, diagnostic)); } return CreateReport(ProtocolConversions.DocumentToTextDocumentIdentifier(document), result.ToArray(), resultId); } private void HandleRemovedDocuments(RequestContext context, DiagnosticParams[] previousResults, BufferedProgress<TReport> progress) { Contract.ThrowIfNull(context.Solution); foreach (var previousResult in previousResults) { var textDocument = previousResult.TextDocument; if (textDocument != null) { var document = context.Solution.GetDocument(textDocument); if (document == null) { context.TraceInformation($"Clearing diagnostics for removed document: {textDocument.Uri}"); // Client is asking server about a document that no longer exists (i.e. was removed/deleted from // the workspace). Report a (null-diagnostics, null-result-id) response to the client as that // means they should just consider the file deleted and should remove all diagnostics // information they've cached for it. progress.Report(CreateReport(textDocument, diagnostics: null, resultId: null)); } } } } /// <summary> /// Returns true if diagnostics have changed since the last request and if so, /// calculates a new resultId to use for subsequent computation and caches it. /// </summary> /// <param name="documentToPreviousDiagnosticParams">the resultIds the client sent us.</param> /// <param name="document">the document we are currently calculating results for.</param> /// <param name="newResultId">the resultId to report new diagnostics with if changed.</param> private bool HaveDiagnosticsChanged( Dictionary<Document, DiagnosticParams> documentToPreviousDiagnosticParams, Document document, [NotNullWhen(true)] out string? newResultId) { // Read and write the cached resultId to _documentIdToLastResultId in a single transaction // to prevent in-between updates to _documentIdToLastResultId triggered by OnDiagnosticsUpdated. lock (_gate) { var workspace = document.Project.Solution.Workspace; if (documentToPreviousDiagnosticParams.TryGetValue(document, out var previousParams) && _documentIdToLastResultId.TryGetValue((workspace, document.Id), out var lastReportedResultId) && lastReportedResultId == previousParams.PreviousResultId) { // Our cached resultId for the document matches the resultId the client passed to us. // This means the diagnostics have not changed and we do not need to re-compute. newResultId = null; return false; } // Keep track of the diagnostics we reported here so that we can short-circuit producing diagnostics for // the same diagnostic set in the future. Use a custom result-id per type (doc diagnostics or workspace // diagnostics) so that clients of one don't errantly call into the other. For example, a client // getting document diagnostics should not ask for workspace diagnostics with the result-ids it got for // doc-diagnostics. The two systems are different and cannot share results, or do things like report // what changed between each other. // // Note that we can safely update the map before computation as any cancellation or exception // during computation means that the client will never recieve this resultId and so cannot ask us for it. newResultId = $"{GetType().Name}:{_nextDocumentResultId++}"; _documentIdToLastResultId[(document.Project.Solution.Workspace, document.Id)] = newResultId; return true; } } private VSDiagnostic ConvertDiagnostic(Document document, SourceText text, DiagnosticData diagnosticData) { Contract.ThrowIfNull(diagnosticData.Message, $"Got a document diagnostic that did not have a {nameof(diagnosticData.Message)}"); Contract.ThrowIfNull(diagnosticData.DataLocation, $"Got a document diagnostic that did not have a {nameof(diagnosticData.DataLocation)}"); var project = document.Project; // We currently do not map diagnostics spans as // 1. Razor handles span mapping for razor files on their side. // 2. LSP does not allow us to report document pull diagnostics for a different file path. // 3. The VS LSP client does not support document pull diagnostics for files outside our content type. // 4. This matches classic behavior where we only squiggle the original location anyway. var useMappedSpan = false; return new VSDiagnostic { Source = GetType().Name, Code = diagnosticData.Id, CodeDescription = ProtocolConversions.HelpLinkToCodeDescription(diagnosticData.HelpLink), Message = diagnosticData.Message, Severity = ConvertDiagnosticSeverity(diagnosticData.Severity), Range = ProtocolConversions.LinePositionToRange(DiagnosticData.GetLinePositionSpan(diagnosticData.DataLocation, text, useMappedSpan)), Tags = ConvertTags(diagnosticData), DiagnosticType = diagnosticData.Category, Projects = new[] { new ProjectAndContext { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }; } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(DiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. DiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Info => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, DiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\VisualStudio\Xaml\Impl\Implementation\LanguageServer\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> protected static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData, bool potentialDuplicate) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); if (diagnosticData.Severity == DiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (potentialDuplicate) result.Add(VSDiagnosticTags.PotentialDuplicate); result.Add(diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Build) ? VSDiagnosticTags.BuildError : VSDiagnosticTags.IntellisenseError); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary)) result.Add(DiagnosticTag.Unnecessary); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.EditAndContinue)) result.Add(VSDiagnosticTags.EditAndContinueError); return result.ToArray(); } } }
1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Test; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Diagnostics { public class PullDiagnosticTests : AbstractLanguageServerProtocolTests { #region Document Diagnostics [Fact] public async Task TestNoDocumentDiagnosticsForClosedFilesWithFSAOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesWithFSAOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesWithFSAOffIfInPushMode() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, pullDiagnostics: false); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesIfDefaultAndFeatureFlagOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, DiagnosticMode.Default); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); // Ensure we get no diagnostics when feature flag is off. var testExperimentationService = (TestExperimentationService)testLspServer.TestWorkspace.Services.GetRequiredService<IExperimentationService>(); testExperimentationService.SetExperimentOption(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag, false); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesIfDefaultAndFeatureFlagOn() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, DiagnosticMode.Default); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var testExperimentationService = (TestExperimentationService)testLspServer.TestWorkspace.Services.GetRequiredService<IExperimentationService>(); testExperimentationService.SetExperimentOption(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag, true); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } [Fact] public async Task TestDocumentDiagnosticsForRemovedDocument() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var workspace = testLspServer.TestWorkspace; // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); // Get the diagnostics for the solution containing the doc. var solution = document.Project.Solution; await OpenDocumentAsync(testLspServer, document); await WaitForDiagnosticsAsync(workspace); var results = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(document.GetURI()), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); // Now remove the doc. workspace.OnDocumentRemoved(workspace.Documents.Single().Id); await CloseDocumentAsync(testLspServer, document); // And get diagnostic again, using the same doc-id as before. await WaitForDiagnosticsAsync(workspace); results = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, new DocumentDiagnosticsParams { PreviousResultId = results.Single().ResultId, TextDocument = ProtocolConversions.DocumentToTextDocumentIdentifier(document) }, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Null(results.Single().Diagnostics); Assert.Null(results.Single().ResultId); } [Fact] public async Task TestNoChangeIfDocumentDiagnosticsCalledTwice() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var resultId = results.Single().ResultId; results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI(), previousResultId: resultId); Assert.Null(results.Single().Diagnostics); Assert.Equal(resultId, results.Single().ResultId); } [Fact] public async Task TestDocumentDiagnosticsRemovedAfterErrorIsFixed() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); await InsertTextAsync(testLspServer, document, buffer.CurrentSnapshot.Length, "}"); results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results[0].Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsRemainAfterErrorIsNotFixed() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); buffer.Insert(0, " "); await InsertTextAsync(testLspServer, document, position: 0, text: " "); results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI(), previousResultId: results[0].ResultId); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results[0].Diagnostics.Single().Range.Start); } [Fact] public async Task TestDocumentDiagnosticsAreNotMapped() { var markup = @"#line 1 ""test.txt"" class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); Assert.Equal(1, results.Single().Diagnostics.Single().Range.Start.Line); } private static async Task InsertTextAsync( TestLspServer testLspServer, Document document, int position, string text) { var sourceText = await document.GetTextAsync(); var lineInfo = sourceText.Lines.GetLinePositionSpan(new TextSpan(position, 0)); await testLspServer.InsertTextAsync(document.GetURI(), (lineInfo.Start.Line, lineInfo.Start.Character, text)); } private static Task OpenDocumentAsync(TestLspServer testLspServer, Document document) => testLspServer.OpenDocumentAsync(document.GetURI()); private static Task CloseDocumentAsync(TestLspServer testLspServer, Document document) => testLspServer.CloseDocumentAsync(document.GetURI()); [Fact] public async Task TestStreamingDocumentDiagnostics() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var progress = BufferedProgress.Create<DiagnosticReport>(null); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI(), progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()!.Single().Diagnostics.Single().Code); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesUsesActiveContext() { var documentText = @"#if ONE class A { #endif class B {"; var workspaceXml = @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""C:\C.cs"">{documentText}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1"">{documentText}</Document> </Project> </Workspace>"; using var testLspServer = CreateTestWorkspaceFromXml(workspaceXml, BackgroundAnalysisScope.OpenFilesAndProjects); var csproj1Document = testLspServer.GetCurrentSolution().Projects.Where(p => p.Name == "CSProj1").Single().Documents.First(); var csproj2Document = testLspServer.GetCurrentSolution().Projects.Where(p => p.Name == "CSProj2").Single().Documents.First(); // Open either of the documents via LSP, we're tracking the URI and text. await OpenDocumentAsync(testLspServer, csproj1Document); // This opens all documents in the workspace and ensures buffers are created. testLspServer.TestWorkspace.GetTestDocument(csproj1Document.Id).GetTextBuffer(); // Set CSProj2 as the active context and get diagnostics. testLspServer.TestWorkspace.SetDocumentContext(csproj2Document.Id); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, csproj2Document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var vsDiagnostic = (LSP.VSDiagnostic)results.Single().Diagnostics.Single(); Assert.Equal("CSProj2", vsDiagnostic.Projects.Single().ProjectName); // Set CSProj1 as the active context and get diagnostics. testLspServer.TestWorkspace.SetDocumentContext(csproj1Document.Id); results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, csproj1Document.GetURI()); Assert.Equal(2, results.Single().Diagnostics!.Length); Assert.All(results.Single().Diagnostics, d => Assert.Equal("CS1513", d.Code)); Assert.All(results.Single().Diagnostics, d => Assert.Equal("CSProj1", ((VSDiagnostic)d).Projects.Single().ProjectName)); } #endregion #region Workspace Diagnostics [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOff() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.OpenFilesAndProjects); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Empty(results); } [Fact] public async Task TestWorkspaceDiagnosticsForClosedFilesWithFSAOn() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOnAndInPushMode() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution, pullDiagnostics: false); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Empty(results[0].Diagnostics); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestWorkspaceDiagnosticsForRemovedDocument() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); testLspServer.TestWorkspace.OnDocumentRemoved(testLspServer.TestWorkspace.Documents.First().Id); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); // First doc should show up as removed. Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[0].ResultId); // Second doc should show up as unchanged. Assert.Null(results2[1].Diagnostics); Assert.Equal(results[1].ResultId, results2[1].ResultId); } private static DiagnosticParams[] CreateDiagnosticParamsFromPreviousReports(WorkspaceDiagnosticReport[] results) { return results.Select(r => new DiagnosticParams { TextDocument = r.TextDocument, PreviousResultId = r.ResultId }).ToArray(); } [Fact] public async Task TestNoChangeIfWorkspaceDiagnosticsCalledTwice() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.Equal(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemovedAfterErrorIsFixed() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var buffer = testLspServer.TestWorkspace.Documents.First().GetTextBuffer(); buffer.Insert(buffer.CurrentSnapshot.Length, "}"); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Empty(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.NotEqual(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemainAfterErrorIsNotFixed() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); Assert.Empty(results[1].Diagnostics); var buffer = testLspServer.TestWorkspace.Documents.First().GetTextBuffer(); buffer.Insert(0, " "); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.First(); var text = await document.GetTextAsync(); // Hacky, but we need to close the document manually since editing the text-buffer will open it in the // test-workspace. testLspServer.TestWorkspace.OnDocumentClosed( document.Id, TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create()))); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal("CS1513", results2[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results2[0].Diagnostics.Single().Range.Start); Assert.Empty(results2[1].Diagnostics); Assert.NotEqual(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestStreamingWorkspaceDiagnostics() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); var progress = BufferedProgress.Create<DiagnosticReport>(null); results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()![0].Diagnostics![0].Code); } [Fact] public async Task TestWorkspaceDiagnosticsAreNotMapped() { var markup1 = @"#line 1 ""test.txt"" class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal(new Uri("C:/test1.cs"), results[0].TextDocument!.Uri); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(1, results[0].Diagnostics.Single().Range.Start.Line); Assert.Empty(results[1].Diagnostics); } #endregion private static async Task<DiagnosticReport[]> RunGetDocumentPullDiagnosticsAsync( TestLspServer testLspServer, Uri uri, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { await WaitForDiagnosticsAsync(testLspServer.TestWorkspace); var result = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(uri, previousResultId, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task<WorkspaceDiagnosticReport[]> RunGetWorkspacePullDiagnosticsAsync( TestLspServer testLspServer, DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { await WaitForDiagnosticsAsync(testLspServer.TestWorkspace); var result = await testLspServer.ExecuteRequestAsync<WorkspaceDocumentDiagnosticsParams, WorkspaceDiagnosticReport[]>( MSLSPMethods.WorkspacePullDiagnosticName, CreateWorkspaceDiagnosticParams(previousResults, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task WaitForDiagnosticsAsync(TestWorkspace workspace) { var listenerProvider = workspace.GetService<IAsynchronousOperationListenerProvider>(); await listenerProvider.GetWaiter(FeatureAttribute.Workspace).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).ExpeditedWaitAsync(); } private static DocumentDiagnosticsParams CreateDocumentDiagnosticParams( Uri uri, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { return new DocumentDiagnosticsParams { TextDocument = new LSP.TextDocumentIdentifier { Uri = uri }, PreviousResultId = previousResultId, PartialResultToken = progress, }; } private static WorkspaceDocumentDiagnosticsParams CreateWorkspaceDiagnosticParams( DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { return new WorkspaceDocumentDiagnosticsParams { PreviousResults = previousResults, PartialResultToken = progress, }; } private TestLspServer CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) => CreateTestWorkspaceWithDiagnostics(markup, scope, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); private TestLspServer CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, DiagnosticMode mode) { var testLspServer = CreateTestLspServer(markup, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, mode); return testLspServer; } private TestLspServer CreateTestWorkspaceFromXml(string xmlMarkup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var testLspServer = CreateXmlTestLspServer(xmlMarkup, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); return testLspServer; } private TestLspServer CreateTestWorkspaceWithDiagnostics(string[] markups, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var testLspServer = CreateTestLspServer(markups, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); return testLspServer; } private static void InitializeDiagnostics(BackgroundAnalysisScope scope, TestWorkspace workspace, DiagnosticMode diagnosticMode) { workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions( workspace.Options .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, scope) .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, scope) .WithChangedOption(InternalDiagnosticsOptions.NormalDiagnosticMode, diagnosticMode))); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var registrationService = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); var diagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue<IDiagnosticService>(); diagnosticService.Register(new TestHostDiagnosticUpdateSource(workspace)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Test; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Diagnostics { public class PullDiagnosticTests : AbstractLanguageServerProtocolTests { #region Document Diagnostics [Fact] public async Task TestNoDocumentDiagnosticsForClosedFilesWithFSAOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesWithFSAOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); Assert.NotNull(results.Single().Diagnostics.Single().CodeDescription!.Href); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesWithFSAOffIfInPushMode() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, pullDiagnostics: false); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesIfDefaultAndFeatureFlagOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, DiagnosticMode.Default); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); // Ensure we get no diagnostics when feature flag is off. var testExperimentationService = (TestExperimentationService)testLspServer.TestWorkspace.Services.GetRequiredService<IExperimentationService>(); testExperimentationService.SetExperimentOption(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag, false); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesIfDefaultAndFeatureFlagOn() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, DiagnosticMode.Default); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var testExperimentationService = (TestExperimentationService)testLspServer.TestWorkspace.Services.GetRequiredService<IExperimentationService>(); testExperimentationService.SetExperimentOption(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag, true); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } [Fact] public async Task TestDocumentDiagnosticsForRemovedDocument() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var workspace = testLspServer.TestWorkspace; // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); // Get the diagnostics for the solution containing the doc. var solution = document.Project.Solution; await OpenDocumentAsync(testLspServer, document); await WaitForDiagnosticsAsync(workspace); var results = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(document.GetURI()), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); // Now remove the doc. workspace.OnDocumentRemoved(workspace.Documents.Single().Id); await CloseDocumentAsync(testLspServer, document); // And get diagnostic again, using the same doc-id as before. await WaitForDiagnosticsAsync(workspace); results = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, new DocumentDiagnosticsParams { PreviousResultId = results.Single().ResultId, TextDocument = ProtocolConversions.DocumentToTextDocumentIdentifier(document) }, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Null(results.Single().Diagnostics); Assert.Null(results.Single().ResultId); } [Fact] public async Task TestNoChangeIfDocumentDiagnosticsCalledTwice() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var resultId = results.Single().ResultId; results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI(), previousResultId: resultId); Assert.Null(results.Single().Diagnostics); Assert.Equal(resultId, results.Single().ResultId); } [Fact] public async Task TestDocumentDiagnosticsRemovedAfterErrorIsFixed() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); await InsertTextAsync(testLspServer, document, buffer.CurrentSnapshot.Length, "}"); results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results[0].Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsRemainAfterErrorIsNotFixed() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); buffer.Insert(0, " "); await InsertTextAsync(testLspServer, document, position: 0, text: " "); results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI(), previousResultId: results[0].ResultId); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results[0].Diagnostics.Single().Range.Start); } [Fact] public async Task TestDocumentDiagnosticsAreNotMapped() { var markup = @"#line 1 ""test.txt"" class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); Assert.Equal(1, results.Single().Diagnostics.Single().Range.Start.Line); } private static async Task InsertTextAsync( TestLspServer testLspServer, Document document, int position, string text) { var sourceText = await document.GetTextAsync(); var lineInfo = sourceText.Lines.GetLinePositionSpan(new TextSpan(position, 0)); await testLspServer.InsertTextAsync(document.GetURI(), (lineInfo.Start.Line, lineInfo.Start.Character, text)); } private static Task OpenDocumentAsync(TestLspServer testLspServer, Document document) => testLspServer.OpenDocumentAsync(document.GetURI()); private static Task CloseDocumentAsync(TestLspServer testLspServer, Document document) => testLspServer.CloseDocumentAsync(document.GetURI()); [Fact] public async Task TestStreamingDocumentDiagnostics() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var progress = BufferedProgress.Create<DiagnosticReport>(null); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI(), progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()!.Single().Diagnostics.Single().Code); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesUsesActiveContext() { var documentText = @"#if ONE class A { #endif class B {"; var workspaceXml = @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""C:\C.cs"">{documentText}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1"">{documentText}</Document> </Project> </Workspace>"; using var testLspServer = CreateTestWorkspaceFromXml(workspaceXml, BackgroundAnalysisScope.OpenFilesAndProjects); var csproj1Document = testLspServer.GetCurrentSolution().Projects.Where(p => p.Name == "CSProj1").Single().Documents.First(); var csproj2Document = testLspServer.GetCurrentSolution().Projects.Where(p => p.Name == "CSProj2").Single().Documents.First(); // Open either of the documents via LSP, we're tracking the URI and text. await OpenDocumentAsync(testLspServer, csproj1Document); // This opens all documents in the workspace and ensures buffers are created. testLspServer.TestWorkspace.GetTestDocument(csproj1Document.Id).GetTextBuffer(); // Set CSProj2 as the active context and get diagnostics. testLspServer.TestWorkspace.SetDocumentContext(csproj2Document.Id); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, csproj2Document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var vsDiagnostic = (LSP.VSDiagnostic)results.Single().Diagnostics.Single(); Assert.Equal("CSProj2", vsDiagnostic.Projects.Single().ProjectName); // Set CSProj1 as the active context and get diagnostics. testLspServer.TestWorkspace.SetDocumentContext(csproj1Document.Id); results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, csproj1Document.GetURI()); Assert.Equal(2, results.Single().Diagnostics!.Length); Assert.All(results.Single().Diagnostics, d => Assert.Equal("CS1513", d.Code)); Assert.All(results.Single().Diagnostics, d => Assert.Equal("CSProj1", ((VSDiagnostic)d).Projects.Single().ProjectName)); } #endregion #region Workspace Diagnostics [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOff() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.OpenFilesAndProjects); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Empty(results); } [Fact] public async Task TestWorkspaceDiagnosticsForClosedFilesWithFSAOn() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOnAndInPushMode() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution, pullDiagnostics: false); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Empty(results[0].Diagnostics); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestWorkspaceDiagnosticsForRemovedDocument() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); testLspServer.TestWorkspace.OnDocumentRemoved(testLspServer.TestWorkspace.Documents.First().Id); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); // First doc should show up as removed. Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[0].ResultId); // Second doc should show up as unchanged. Assert.Null(results2[1].Diagnostics); Assert.Equal(results[1].ResultId, results2[1].ResultId); } private static DiagnosticParams[] CreateDiagnosticParamsFromPreviousReports(WorkspaceDiagnosticReport[] results) { return results.Select(r => new DiagnosticParams { TextDocument = r.TextDocument, PreviousResultId = r.ResultId }).ToArray(); } [Fact] public async Task TestNoChangeIfWorkspaceDiagnosticsCalledTwice() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.Equal(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemovedAfterErrorIsFixed() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var buffer = testLspServer.TestWorkspace.Documents.First().GetTextBuffer(); buffer.Insert(buffer.CurrentSnapshot.Length, "}"); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Empty(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.NotEqual(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemainAfterErrorIsNotFixed() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); Assert.Empty(results[1].Diagnostics); var buffer = testLspServer.TestWorkspace.Documents.First().GetTextBuffer(); buffer.Insert(0, " "); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.First(); var text = await document.GetTextAsync(); // Hacky, but we need to close the document manually since editing the text-buffer will open it in the // test-workspace. testLspServer.TestWorkspace.OnDocumentClosed( document.Id, TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create()))); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal("CS1513", results2[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results2[0].Diagnostics.Single().Range.Start); Assert.Empty(results2[1].Diagnostics); Assert.NotEqual(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestStreamingWorkspaceDiagnostics() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); var progress = BufferedProgress.Create<DiagnosticReport>(null); results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()![0].Diagnostics![0].Code); } [Fact] public async Task TestWorkspaceDiagnosticsAreNotMapped() { var markup1 = @"#line 1 ""test.txt"" class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal(new Uri("C:/test1.cs"), results[0].TextDocument!.Uri); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(1, results[0].Diagnostics.Single().Range.Start.Line); Assert.Empty(results[1].Diagnostics); } #endregion private static async Task<DiagnosticReport[]> RunGetDocumentPullDiagnosticsAsync( TestLspServer testLspServer, Uri uri, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { await WaitForDiagnosticsAsync(testLspServer.TestWorkspace); var result = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(uri, previousResultId, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task<WorkspaceDiagnosticReport[]> RunGetWorkspacePullDiagnosticsAsync( TestLspServer testLspServer, DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { await WaitForDiagnosticsAsync(testLspServer.TestWorkspace); var result = await testLspServer.ExecuteRequestAsync<WorkspaceDocumentDiagnosticsParams, WorkspaceDiagnosticReport[]>( MSLSPMethods.WorkspacePullDiagnosticName, CreateWorkspaceDiagnosticParams(previousResults, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task WaitForDiagnosticsAsync(TestWorkspace workspace) { var listenerProvider = workspace.GetService<IAsynchronousOperationListenerProvider>(); await listenerProvider.GetWaiter(FeatureAttribute.Workspace).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).ExpeditedWaitAsync(); } private static DocumentDiagnosticsParams CreateDocumentDiagnosticParams( Uri uri, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { return new DocumentDiagnosticsParams { TextDocument = new LSP.TextDocumentIdentifier { Uri = uri }, PreviousResultId = previousResultId, PartialResultToken = progress, }; } private static WorkspaceDocumentDiagnosticsParams CreateWorkspaceDiagnosticParams( DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { return new WorkspaceDocumentDiagnosticsParams { PreviousResults = previousResults, PartialResultToken = progress, }; } private TestLspServer CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) => CreateTestWorkspaceWithDiagnostics(markup, scope, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); private TestLspServer CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, DiagnosticMode mode) { var testLspServer = CreateTestLspServer(markup, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, mode); return testLspServer; } private TestLspServer CreateTestWorkspaceFromXml(string xmlMarkup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var testLspServer = CreateXmlTestLspServer(xmlMarkup, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); return testLspServer; } private TestLspServer CreateTestWorkspaceWithDiagnostics(string[] markups, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var testLspServer = CreateTestLspServer(markups, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); return testLspServer; } private static void InitializeDiagnostics(BackgroundAnalysisScope scope, TestWorkspace workspace, DiagnosticMode diagnosticMode) { workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions( workspace.Options .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, scope) .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, scope) .WithChangedOption(InternalDiagnosticsOptions.NormalDiagnosticMode, diagnosticMode))); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var registrationService = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); var diagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue<IDiagnosticService>(); diagnosticService.Register(new TestHostDiagnosticUpdateSource(workspace)); } } }
1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : AbstractStatelessRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : DiagnosticReport { private readonly IXamlPullDiagnosticService _xamlDiagnosticService; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. /// </summary> protected abstract DiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed. /// </summary> protected abstract ImmutableArray<Document> GetDocuments(RequestContext context); /// <summary> /// Creates the <see cref="DiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); protected AbstractPullDiagnosticHandler(IXamlPullDiagnosticService xamlDiagnosticService) { _xamlDiagnosticService = xamlDiagnosticService; } public override async Task<TReport[]?> HandleRequestAsync(TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. var previousResults = GetPreviousResults(diagnosticsParams); var documentToPreviousResultId = new Dictionary<Document, string?>(); if (previousResults != null) { // Go through the previousResults and check if we need to remove diagnostic information for any documents foreach (var previousResult in previousResults) { if (previousResult.TextDocument != null) { var document = context.Solution.GetDocument(previousResult.TextDocument, context.ClientName); if (document == null) { // We can no longer get this document, return null for both diagnostics and resultId progress.Report(CreateReport(previousResult.TextDocument, diagnostics: null, resultId: null)); } else { // Cache the document to previousResultId mapping so we can easily retrieve the resultId later. documentToPreviousResultId[document] = previousResult.PreviousResultId; } } } } // Go through the documents that we need to process and call XamlPullDiagnosticService to get the diagnostic report foreach (var document in GetDocuments(context)) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var documentId = ProtocolConversions.DocumentToTextDocumentIdentifier(document); // If we can get a previousId of the document, use it, // otherwise use null as the previousId to pass into the XamlPullDiagnosticService var previousResultId = documentToPreviousResultId.TryGetValue(document, out var id) ? id : null; // Call XamlPullDiagnosticService to get the diagnostic report for this document. // We will compute what to report inside XamlPullDiagnosticService, for example, whether we should keep using the previousId or use a new resultId, // and the handler here just return the result get from XamlPullDiagnosticService. var diagnosticReport = await _xamlDiagnosticService.GetDiagnosticReportAsync(document, previousResultId, cancellationToken).ConfigureAwait(false); progress.Report(CreateReport( documentId, ConvertToVSDiagnostics(diagnosticReport.Diagnostics, document, text), diagnosticReport.ResultId)); } return progress.GetValues(); } /// <summary> /// Convert XamlDiagnostics to VSDiagnostics /// </summary> private static VSDiagnostic[]? ConvertToVSDiagnostics(ImmutableArray<XamlDiagnostic>? xamlDiagnostics, Document document, SourceText text) { if (xamlDiagnostics == null) { return null; } var project = document.Project; return xamlDiagnostics.Value.Select(d => new VSDiagnostic() { Code = d.Code, Message = d.Message ?? string.Empty, ExpandedMessage = d.ExtendedMessage, Severity = ConvertDiagnosticSeverity(d.Severity), Range = ProtocolConversions.TextSpanToRange(new TextSpan(d.Offset, d.Length), text), Tags = ConvertTags(d), Source = d.Tool, CodeDescription = GetCodeDescription(d.HelpLink), Projects = new[] { new ProjectAndContext { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }).ToArray(); } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(XamlDiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. XamlDiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, XamlDiagnosticSeverity.HintedSuggestion => LSP.DiagnosticSeverity.Hint, XamlDiagnosticSeverity.Message => LSP.DiagnosticSeverity.Information, XamlDiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, XamlDiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\Features\LanguageServer\Protocol\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> private static DiagnosticTag[] ConvertTags(XamlDiagnostic diagnostic) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); result.Add(VSDiagnosticTags.IntellisenseError); if (diagnostic.Severity == XamlDiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else if (diagnostic.Severity == XamlDiagnosticSeverity.HintedSuggestion) { result.Add(VSDiagnosticTags.HiddenInErrorList); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (diagnostic.CustomTags?.Contains(WellKnownDiagnosticTags.Unnecessary) == true) result.Add(DiagnosticTag.Unnecessary); return result.ToArray(); } private static CodeDescription? GetCodeDescription(string? helpLink) { if (Uri.TryCreate(helpLink, UriKind.RelativeOrAbsolute, out var uri)) { return new CodeDescription { Href = uri, }; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : AbstractStatelessRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : DiagnosticReport { private readonly IXamlPullDiagnosticService _xamlDiagnosticService; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. /// </summary> protected abstract DiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed. /// </summary> protected abstract ImmutableArray<Document> GetDocuments(RequestContext context); /// <summary> /// Creates the <see cref="DiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); protected AbstractPullDiagnosticHandler(IXamlPullDiagnosticService xamlDiagnosticService) { _xamlDiagnosticService = xamlDiagnosticService; } public override async Task<TReport[]?> HandleRequestAsync(TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. var previousResults = GetPreviousResults(diagnosticsParams); var documentToPreviousResultId = new Dictionary<Document, string?>(); if (previousResults != null) { // Go through the previousResults and check if we need to remove diagnostic information for any documents foreach (var previousResult in previousResults) { if (previousResult.TextDocument != null) { var document = context.Solution.GetDocument(previousResult.TextDocument, context.ClientName); if (document == null) { // We can no longer get this document, return null for both diagnostics and resultId progress.Report(CreateReport(previousResult.TextDocument, diagnostics: null, resultId: null)); } else { // Cache the document to previousResultId mapping so we can easily retrieve the resultId later. documentToPreviousResultId[document] = previousResult.PreviousResultId; } } } } // Go through the documents that we need to process and call XamlPullDiagnosticService to get the diagnostic report foreach (var document in GetDocuments(context)) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var documentId = ProtocolConversions.DocumentToTextDocumentIdentifier(document); // If we can get a previousId of the document, use it, // otherwise use null as the previousId to pass into the XamlPullDiagnosticService var previousResultId = documentToPreviousResultId.TryGetValue(document, out var id) ? id : null; // Call XamlPullDiagnosticService to get the diagnostic report for this document. // We will compute what to report inside XamlPullDiagnosticService, for example, whether we should keep using the previousId or use a new resultId, // and the handler here just return the result get from XamlPullDiagnosticService. var diagnosticReport = await _xamlDiagnosticService.GetDiagnosticReportAsync(document, previousResultId, cancellationToken).ConfigureAwait(false); progress.Report(CreateReport( documentId, ConvertToVSDiagnostics(diagnosticReport.Diagnostics, document, text), diagnosticReport.ResultId)); } return progress.GetValues(); } /// <summary> /// Convert XamlDiagnostics to VSDiagnostics /// </summary> private static VSDiagnostic[]? ConvertToVSDiagnostics(ImmutableArray<XamlDiagnostic>? xamlDiagnostics, Document document, SourceText text) { if (xamlDiagnostics == null) { return null; } var project = document.Project; return xamlDiagnostics.Value.Select(d => new VSDiagnostic() { Code = d.Code, Message = d.Message ?? string.Empty, ExpandedMessage = d.ExtendedMessage, Severity = ConvertDiagnosticSeverity(d.Severity), Range = ProtocolConversions.TextSpanToRange(new TextSpan(d.Offset, d.Length), text), Tags = ConvertTags(d), Source = d.Tool, CodeDescription = ProtocolConversions.HelpLinkToCodeDescription(d.HelpLink), Projects = new[] { new ProjectAndContext { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }).ToArray(); } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(XamlDiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. XamlDiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, XamlDiagnosticSeverity.HintedSuggestion => LSP.DiagnosticSeverity.Hint, XamlDiagnosticSeverity.Message => LSP.DiagnosticSeverity.Information, XamlDiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, XamlDiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\Features\LanguageServer\Protocol\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> private static DiagnosticTag[] ConvertTags(XamlDiagnostic diagnostic) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); result.Add(VSDiagnosticTags.IntellisenseError); if (diagnostic.Severity == XamlDiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else if (diagnostic.Severity == XamlDiagnosticSeverity.HintedSuggestion) { result.Add(VSDiagnosticTags.HiddenInErrorList); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (diagnostic.CustomTags?.Contains(WellKnownDiagnosticTags.Unnecessary) == true) result.Add(DiagnosticTag.Unnecessary); return result.ToArray(); } } }
1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Workspaces/CoreTest/UtilityTest/SpecializedTasksTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; using Xunit; #pragma warning disable IDE0039 // Use local function namespace Microsoft.CodeAnalysis.UnitTests { [SuppressMessage("Usage", "VSTHRD104:Offer async methods", Justification = "This class tests specific behavior of tasks.")] public class SpecializedTasksTests { private record StateType; private record IntermediateType; private record ResultType; [Fact] public void WhenAll_Null() { #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) Assert.Throws<ArgumentNullException>(() => SpecializedTasks.WhenAll<int>(null!)); #pragma warning restore CA2012 // Use ValueTasks correctly } [Fact] public void WhenAll_Empty() { var whenAll = SpecializedTasks.WhenAll(SpecializedCollections.EmptyEnumerable<ValueTask<int>>()); Debug.Assert(whenAll.IsCompleted); Assert.True(whenAll.IsCompletedSuccessfully); Assert.Same(Array.Empty<int>(), whenAll.Result); } [Fact] public void WhenAll_AllCompletedSuccessfully() { var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(0), new ValueTask<int>(1) }); Debug.Assert(whenAll.IsCompleted); Assert.True(whenAll.IsCompletedSuccessfully); Assert.Equal(new[] { 0, 1 }, whenAll.Result); } [Fact] public void WhenAll_CompletedButCanceled() { var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(Task.FromCanceled<int>(new CancellationToken(true))) }); Assert.True(whenAll.IsCompleted); Assert.False(whenAll.IsCompletedSuccessfully); Assert.ThrowsAsync<OperationCanceledException>(async () => await whenAll); } [Fact] public void WhenAll_NotYetCompleted() { var completionSource = new TaskCompletionSource<int>(); var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(completionSource.Task) }); Assert.False(whenAll.IsCompleted); completionSource.SetResult(0); Assert.True(whenAll.IsCompleted); Debug.Assert(whenAll.IsCompleted); Assert.Equal(new[] { 0 }, whenAll.Result); } [Fact] public void Transform_ArgumentValidation() { Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) Assert.Throws<ArgumentNullException>("func", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(null!, transform, arg, cancellationToken)); Assert.Throws<ArgumentNullException>("transform", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync<StateType, IntermediateType, ResultType>(func, null!, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly } [Fact] public void Transform_SyncCompletedFunction_CompletedTransform() { Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCompletedSuccessfully); Assert.NotNull(task.Result); } [Fact] public void Transform_SyncCompletedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCompletedFunction_CompletedTransform() { var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); Assert.NotNull(await task); } [Fact] public async Task Transform_AsyncCompletedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(cancellationToken)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); cts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_NotRequested_IgnoresTransform() { using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); // ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the // cancellation token applied when the intermediate task was cancelled. Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_NotRequested_IgnoresTransform() { using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = new CancellationToken(canceled: false); var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); unexpectedCts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.True(task.IsCanceled); // ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the // cancellation token applied when the intermediate task was cancelled. Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_MismatchToken_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_MismatchToken_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); unexpectedCts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.True(task.IsCanceled); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncDirectFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsFaulted); var exception = Assert.Throws<InvalidOperationException>(() => task.Result); Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); throw fault; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask()); Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncDirectFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); throw fault; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(() => task.AsTask()); Assert.True(task.IsCanceled); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCompletedFunction_FaultedTransform() { var fault = ExceptionUtilities.Unreachable; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault; var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); } [Fact] public async Task Transform_AsyncCompletedFunction_FaultedTransform() { var fault = ExceptionUtilities.Unreachable; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault; var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask()); Assert.Same(fault, exception); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; using Xunit; #pragma warning disable IDE0039 // Use local function namespace Microsoft.CodeAnalysis.UnitTests { [SuppressMessage("Usage", "VSTHRD104:Offer async methods", Justification = "This class tests specific behavior of tasks.")] public class SpecializedTasksTests { private record StateType; private record IntermediateType; private record ResultType; [Fact] public void WhenAll_Null() { #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) Assert.Throws<ArgumentNullException>(() => SpecializedTasks.WhenAll<int>(null!)); #pragma warning restore CA2012 // Use ValueTasks correctly } [Fact] public void WhenAll_Empty() { var whenAll = SpecializedTasks.WhenAll(SpecializedCollections.EmptyEnumerable<ValueTask<int>>()); Debug.Assert(whenAll.IsCompleted); Assert.True(whenAll.IsCompletedSuccessfully); Assert.Same(Array.Empty<int>(), whenAll.Result); } [Fact] public void WhenAll_AllCompletedSuccessfully() { var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(0), new ValueTask<int>(1) }); Debug.Assert(whenAll.IsCompleted); Assert.True(whenAll.IsCompletedSuccessfully); Assert.Equal(new[] { 0, 1 }, whenAll.Result); } [Fact] public void WhenAll_CompletedButCanceled() { var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(Task.FromCanceled<int>(new CancellationToken(true))) }); Assert.True(whenAll.IsCompleted); Assert.False(whenAll.IsCompletedSuccessfully); Assert.ThrowsAsync<OperationCanceledException>(async () => await whenAll); } [Fact] public void WhenAll_NotYetCompleted() { var completionSource = new TaskCompletionSource<int>(); var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(completionSource.Task) }); Assert.False(whenAll.IsCompleted); completionSource.SetResult(0); Assert.True(whenAll.IsCompleted); Debug.Assert(whenAll.IsCompleted); Assert.Equal(new[] { 0 }, whenAll.Result); } [Fact] public void Transform_ArgumentValidation() { Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) Assert.Throws<ArgumentNullException>("func", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(null!, transform, arg, cancellationToken)); Assert.Throws<ArgumentNullException>("transform", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync<StateType, IntermediateType, ResultType>(func, null!, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly } [Fact] public void Transform_SyncCompletedFunction_CompletedTransform() { Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCompletedSuccessfully); Assert.NotNull(task.Result); } [Fact] public void Transform_SyncCompletedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCompletedFunction_CompletedTransform() { var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); Assert.NotNull(await task); } [Fact] public async Task Transform_AsyncCompletedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(cancellationToken)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); cts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_NotRequested_IgnoresTransform() { using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); // ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the // cancellation token applied when the intermediate task was cancelled. Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_NotRequested_IgnoresTransform() { using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = new CancellationToken(canceled: false); var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); unexpectedCts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.True(task.IsCanceled); // ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the // cancellation token applied when the intermediate task was cancelled. Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_MismatchToken_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_MismatchToken_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); unexpectedCts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.True(task.IsCanceled); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncDirectFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsFaulted); var exception = Assert.Throws<InvalidOperationException>(() => task.Result); Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); throw fault; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask()); Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncDirectFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); throw fault; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(() => task.AsTask()); Assert.True(task.IsCanceled); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCompletedFunction_FaultedTransform() { var fault = ExceptionUtilities.Unreachable; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault; var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); } [Fact] public async Task Transform_AsyncCompletedFunction_FaultedTransform() { var fault = ExceptionUtilities.Unreachable; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault; var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask()); Assert.Same(fault, exception); } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ValuesSources/WeakValueSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// A <see cref="ValueSource{T}"/> that keeps a weak reference to a value. /// </summary> internal sealed class WeakValueSource<T> : ValueSource<Optional<T>> where T : class { private readonly WeakReference<T> _weakValue; public WeakValueSource(T value) => _weakValue = new WeakReference<T>(value); public override bool TryGetValue(out Optional<T> value) { if (_weakValue.TryGetTarget(out var target)) { value = target; return true; } value = default; return false; } public override Optional<T> GetValue(CancellationToken cancellationToken) { if (_weakValue.TryGetTarget(out var target)) { return target; } return default; } public override Task<Optional<T>> GetValueAsync(CancellationToken cancellationToken) => Task.FromResult(GetValue(cancellationToken)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// A <see cref="ValueSource{T}"/> that keeps a weak reference to a value. /// </summary> internal sealed class WeakValueSource<T> : ValueSource<Optional<T>> where T : class { private readonly WeakReference<T> _weakValue; public WeakValueSource(T value) => _weakValue = new WeakReference<T>(value); public override bool TryGetValue(out Optional<T> value) { if (_weakValue.TryGetTarget(out var target)) { value = target; return true; } value = default; return false; } public override Optional<T> GetValue(CancellationToken cancellationToken) { if (_weakValue.TryGetTarget(out var target)) { return target; } return default; } public override Task<Optional<T>> GetValueAsync(CancellationToken cancellationToken) => Task.FromResult(GetValue(cancellationToken)); } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Workspaces/Core/Portable/Rename/ConflictEngine/RelatedLocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { /// <summary> /// Gives information about an identifier span that was affected by Rename (Reference or Non reference) /// </summary> [DataContract] internal readonly struct RelatedLocation : IEquatable<RelatedLocation> { /// <summary> /// The Span of the original identifier if it was in source, otherwise the span to check for implicit /// references. /// </summary> [DataMember(Order = 0)] public readonly TextSpan ConflictCheckSpan; [DataMember(Order = 1)] public readonly DocumentId DocumentId; [DataMember(Order = 2)] public readonly RelatedLocationType Type; [DataMember(Order = 3)] public readonly bool IsReference; /// <summary> /// If there was a conflict at ConflictCheckSpan during rename, then the next phase in rename uses /// ComplexifiedTargetSpan span to be expanded to resolve the conflict. /// </summary> [DataMember(Order = 4)] public readonly TextSpan ComplexifiedTargetSpan; public RelatedLocation(TextSpan conflictCheckSpan, DocumentId documentId, RelatedLocationType type, bool isReference = false, TextSpan complexifiedTargetSpan = default) { ConflictCheckSpan = conflictCheckSpan; Type = type; IsReference = isReference; DocumentId = documentId; ComplexifiedTargetSpan = complexifiedTargetSpan; } public RelatedLocation WithType(RelatedLocationType type) => new(ConflictCheckSpan, DocumentId, type, IsReference, ComplexifiedTargetSpan); public override bool Equals(object obj) => obj is RelatedLocation location && Equals(location); public bool Equals(RelatedLocation other) { return ConflictCheckSpan.Equals(other.ConflictCheckSpan) && Type == other.Type && IsReference == other.IsReference && EqualityComparer<DocumentId>.Default.Equals(DocumentId, other.DocumentId) && ComplexifiedTargetSpan.Equals(other.ComplexifiedTargetSpan); } public override int GetHashCode() { var hashCode = 928418920; hashCode = hashCode * -1521134295 + ConflictCheckSpan.GetHashCode(); hashCode = hashCode * -1521134295 + Type.GetHashCode(); hashCode = hashCode * -1521134295 + IsReference.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<DocumentId>.Default.GetHashCode(DocumentId); hashCode = hashCode * -1521134295 + ComplexifiedTargetSpan.GetHashCode(); return hashCode; } public static bool operator ==(RelatedLocation left, RelatedLocation right) => left.Equals(right); public static bool operator !=(RelatedLocation left, RelatedLocation right) => !(left == right); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { /// <summary> /// Gives information about an identifier span that was affected by Rename (Reference or Non reference) /// </summary> [DataContract] internal readonly struct RelatedLocation : IEquatable<RelatedLocation> { /// <summary> /// The Span of the original identifier if it was in source, otherwise the span to check for implicit /// references. /// </summary> [DataMember(Order = 0)] public readonly TextSpan ConflictCheckSpan; [DataMember(Order = 1)] public readonly DocumentId DocumentId; [DataMember(Order = 2)] public readonly RelatedLocationType Type; [DataMember(Order = 3)] public readonly bool IsReference; /// <summary> /// If there was a conflict at ConflictCheckSpan during rename, then the next phase in rename uses /// ComplexifiedTargetSpan span to be expanded to resolve the conflict. /// </summary> [DataMember(Order = 4)] public readonly TextSpan ComplexifiedTargetSpan; public RelatedLocation(TextSpan conflictCheckSpan, DocumentId documentId, RelatedLocationType type, bool isReference = false, TextSpan complexifiedTargetSpan = default) { ConflictCheckSpan = conflictCheckSpan; Type = type; IsReference = isReference; DocumentId = documentId; ComplexifiedTargetSpan = complexifiedTargetSpan; } public RelatedLocation WithType(RelatedLocationType type) => new(ConflictCheckSpan, DocumentId, type, IsReference, ComplexifiedTargetSpan); public override bool Equals(object obj) => obj is RelatedLocation location && Equals(location); public bool Equals(RelatedLocation other) { return ConflictCheckSpan.Equals(other.ConflictCheckSpan) && Type == other.Type && IsReference == other.IsReference && EqualityComparer<DocumentId>.Default.Equals(DocumentId, other.DocumentId) && ComplexifiedTargetSpan.Equals(other.ComplexifiedTargetSpan); } public override int GetHashCode() { var hashCode = 928418920; hashCode = hashCode * -1521134295 + ConflictCheckSpan.GetHashCode(); hashCode = hashCode * -1521134295 + Type.GetHashCode(); hashCode = hashCode * -1521134295 + IsReference.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<DocumentId>.Default.GetHashCode(DocumentId); hashCode = hashCode * -1521134295 + ComplexifiedTargetSpan.GetHashCode(); return hashCode; } public static bool operator ==(RelatedLocation left, RelatedLocation right) => left.Equals(right); public static bool operator !=(RelatedLocation left, RelatedLocation right) => !(left == right); } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/EditorFeatures/TestUtilities/StubVsEditorAdaptersFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using IServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(IVsEditorAdaptersFactoryService))] [PartNotDiscoverable] internal class StubVsEditorAdaptersFactoryService : IVsEditorAdaptersFactoryService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StubVsEditorAdaptersFactoryService() { } public IVsCodeWindow CreateVsCodeWindowAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapter(IServiceProvider serviceProvider, IContentType contentType) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapterForSecondaryBuffer(IServiceProvider serviceProvider, ITextBuffer secondaryBuffer) => throw new NotImplementedException(); public IVsTextBufferCoordinator CreateVsTextBufferCoordinatorAdapter() => throw new NotImplementedException(); public IVsTextView CreateVsTextViewAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextView CreateVsTextViewAdapter(IServiceProvider serviceProvider, ITextViewRoleSet roles) => throw new NotImplementedException(); public IVsTextBuffer GetBufferAdapter(ITextBuffer textBuffer) => throw new NotImplementedException(); public ITextBuffer GetDataBuffer(IVsTextBuffer bufferAdapter) => throw new NotImplementedException(); public ITextBuffer GetDocumentBuffer(IVsTextBuffer bufferAdapter) => throw new NotImplementedException(); public IVsTextView GetViewAdapter(ITextView textView) => throw new NotImplementedException(); public IWpfTextView GetWpfTextView(IVsTextView viewAdapter) => throw new NotImplementedException(); public IWpfTextViewHost GetWpfTextViewHost(IVsTextView viewAdapter) => throw new NotImplementedException(); public void SetDataBuffer(IVsTextBuffer bufferAdapter, ITextBuffer dataBuffer) => 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using IServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(IVsEditorAdaptersFactoryService))] [PartNotDiscoverable] internal class StubVsEditorAdaptersFactoryService : IVsEditorAdaptersFactoryService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StubVsEditorAdaptersFactoryService() { } public IVsCodeWindow CreateVsCodeWindowAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapter(IServiceProvider serviceProvider, IContentType contentType) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapterForSecondaryBuffer(IServiceProvider serviceProvider, ITextBuffer secondaryBuffer) => throw new NotImplementedException(); public IVsTextBufferCoordinator CreateVsTextBufferCoordinatorAdapter() => throw new NotImplementedException(); public IVsTextView CreateVsTextViewAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextView CreateVsTextViewAdapter(IServiceProvider serviceProvider, ITextViewRoleSet roles) => throw new NotImplementedException(); public IVsTextBuffer GetBufferAdapter(ITextBuffer textBuffer) => throw new NotImplementedException(); public ITextBuffer GetDataBuffer(IVsTextBuffer bufferAdapter) => throw new NotImplementedException(); public ITextBuffer GetDocumentBuffer(IVsTextBuffer bufferAdapter) => throw new NotImplementedException(); public IVsTextView GetViewAdapter(ITextView textView) => throw new NotImplementedException(); public IWpfTextView GetWpfTextView(IVsTextView viewAdapter) => throw new NotImplementedException(); public IWpfTextViewHost GetWpfTextViewHost(IVsTextView viewAdapter) => throw new NotImplementedException(); public void SetDataBuffer(IVsTextBuffer bufferAdapter, ITextBuffer dataBuffer) => throw new NotImplementedException(); } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/VisualStudio/Core/Def/Implementation/Utilities/VsEnumDebugName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.VisualStudio; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal class VsEnumDebugName : IVsEnumDebugName { private readonly IList<IVsDebugName> _values; private int _currentIndex; public VsEnumDebugName(IList<IVsDebugName> values) { _values = values; _currentIndex = 0; } public int Clone(out IVsEnumDebugName ppEnum) { ppEnum = new VsEnumDebugName(_values); return VSConstants.S_OK; } public int GetCount(out uint pceltCount) { pceltCount = (uint)_values.Count; return VSConstants.S_OK; } public int Next(uint celt, IVsDebugName[] rgelt, uint[] pceltFetched) { var i = 0; for (; i < celt && _currentIndex < _values.Count; i++, _currentIndex++) { rgelt[i] = _values[_currentIndex]; } if (pceltFetched != null && pceltFetched.Length > 0) { pceltFetched[0] = (uint)i; } return i < celt ? VSConstants.S_FALSE : VSConstants.S_OK; } public int Reset() { _currentIndex = 0; return VSConstants.S_OK; } public int Skip(uint celt) { _currentIndex += (int)celt; return _currentIndex < _values.Count ? VSConstants.S_OK : VSConstants.S_FALSE; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.VisualStudio; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal class VsEnumDebugName : IVsEnumDebugName { private readonly IList<IVsDebugName> _values; private int _currentIndex; public VsEnumDebugName(IList<IVsDebugName> values) { _values = values; _currentIndex = 0; } public int Clone(out IVsEnumDebugName ppEnum) { ppEnum = new VsEnumDebugName(_values); return VSConstants.S_OK; } public int GetCount(out uint pceltCount) { pceltCount = (uint)_values.Count; return VSConstants.S_OK; } public int Next(uint celt, IVsDebugName[] rgelt, uint[] pceltFetched) { var i = 0; for (; i < celt && _currentIndex < _values.Count; i++, _currentIndex++) { rgelt[i] = _values[_currentIndex]; } if (pceltFetched != null && pceltFetched.Length > 0) { pceltFetched[0] = (uint)i; } return i < celt ? VSConstants.S_FALSE : VSConstants.S_OK; } public int Reset() { _currentIndex = 0; return VSConstants.S_OK; } public int Skip(uint celt) { _currentIndex += (int)celt; return _currentIndex < _values.Count ? VSConstants.S_OK : VSConstants.S_FALSE; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Compilers/CSharp/Portable/BoundTree/ConversionGroup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A group is a common instance referenced by all BoundConversion instances /// generated from a single Conversion. The group is used by NullableWalker to /// determine which BoundConversion nodes should be considered as a unit. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class ConversionGroup { internal ConversionGroup(Conversion conversion, TypeWithAnnotations explicitType = default) { Conversion = conversion; ExplicitType = explicitType; } /// <summary> /// True if the conversion is an explicit conversion. /// </summary> internal bool IsExplicitConversion => ExplicitType.HasType; /// <summary> /// The conversion (from Conversions.ClassifyConversionFromExpression for /// instance) from which all BoundConversions in the group were created. /// </summary> internal readonly Conversion Conversion; /// <summary> /// The target type of the conversion specified explicitly in source, /// or null if not an explicit conversion. /// </summary> internal readonly TypeWithAnnotations ExplicitType; #if DEBUG private static int _nextId; private readonly int _id = _nextId++; internal string GetDebuggerDisplay() { var str = $"#{_id} {Conversion}"; if (ExplicitType.HasType) { str += $" ({ExplicitType})"; } return str; } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A group is a common instance referenced by all BoundConversion instances /// generated from a single Conversion. The group is used by NullableWalker to /// determine which BoundConversion nodes should be considered as a unit. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class ConversionGroup { internal ConversionGroup(Conversion conversion, TypeWithAnnotations explicitType = default) { Conversion = conversion; ExplicitType = explicitType; } /// <summary> /// True if the conversion is an explicit conversion. /// </summary> internal bool IsExplicitConversion => ExplicitType.HasType; /// <summary> /// The conversion (from Conversions.ClassifyConversionFromExpression for /// instance) from which all BoundConversions in the group were created. /// </summary> internal readonly Conversion Conversion; /// <summary> /// The target type of the conversion specified explicitly in source, /// or null if not an explicit conversion. /// </summary> internal readonly TypeWithAnnotations ExplicitType; #if DEBUG private static int _nextId; private readonly int _id = _nextId++; internal string GetDebuggerDisplay() { var str = $"#{_id} {Conversion}"; if (ExplicitType.HasType) { str += $" ({ExplicitType})"; } return str; } #endif } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingInvocationReasonsWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingInvocationReasonsWrapper { public static readonly UnitTestingInvocationReasonsWrapper SemanticChanged = new(InvocationReasons.SemanticChanged); public static readonly UnitTestingInvocationReasonsWrapper Reanalyze = new(InvocationReasons.Reanalyze); public static readonly UnitTestingInvocationReasonsWrapper ProjectConfigurationChanged = new(InvocationReasons.ProjectConfigurationChanged); public static readonly UnitTestingInvocationReasonsWrapper SyntaxChanged = new(InvocationReasons.SyntaxChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentAdded = new(PredefinedInvocationReasons.DocumentAdded); public static readonly UnitTestingInvocationReasonsWrapper PredefinedReanalyze = new(PredefinedInvocationReasons.Reanalyze); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSemanticChanged = new(PredefinedInvocationReasons.SemanticChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSyntaxChanged = new(PredefinedInvocationReasons.SyntaxChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedProjectConfigurationChanged = new(PredefinedInvocationReasons.ProjectConfigurationChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentOpened = new(PredefinedInvocationReasons.DocumentOpened); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentRemoved = new(PredefinedInvocationReasons.DocumentRemoved); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentClosed = new(PredefinedInvocationReasons.DocumentClosed); public static readonly UnitTestingInvocationReasonsWrapper PredefinedHighPriority = new(PredefinedInvocationReasons.HighPriority); public static readonly UnitTestingInvocationReasonsWrapper PredefinedProjectParseOptionsChanged = new(PredefinedInvocationReasons.ProjectParseOptionsChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSolutionRemoved = new(PredefinedInvocationReasons.SolutionRemoved); internal InvocationReasons UnderlyingObject { get; } internal UnitTestingInvocationReasonsWrapper(InvocationReasons underlyingObject) => UnderlyingObject = underlyingObject; public UnitTestingInvocationReasonsWrapper(string reason) : this(new InvocationReasons(reason)) { } public UnitTestingInvocationReasonsWrapper With(UnitTestingInvocationReasonsWrapper reason) => new(reason.UnderlyingObject.With(UnderlyingObject)); public bool IsReanalyze() => UnderlyingObject.Contains(PredefinedInvocationReasons.Reanalyze); public bool HasSemanticChanged() => UnderlyingObject.Contains(PredefinedInvocationReasons.SemanticChanged); public bool HasProjectConfigurationChanged() => UnderlyingObject.Contains(PredefinedInvocationReasons.ProjectConfigurationChanged); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingInvocationReasonsWrapper { public static readonly UnitTestingInvocationReasonsWrapper SemanticChanged = new(InvocationReasons.SemanticChanged); public static readonly UnitTestingInvocationReasonsWrapper Reanalyze = new(InvocationReasons.Reanalyze); public static readonly UnitTestingInvocationReasonsWrapper ProjectConfigurationChanged = new(InvocationReasons.ProjectConfigurationChanged); public static readonly UnitTestingInvocationReasonsWrapper SyntaxChanged = new(InvocationReasons.SyntaxChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentAdded = new(PredefinedInvocationReasons.DocumentAdded); public static readonly UnitTestingInvocationReasonsWrapper PredefinedReanalyze = new(PredefinedInvocationReasons.Reanalyze); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSemanticChanged = new(PredefinedInvocationReasons.SemanticChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSyntaxChanged = new(PredefinedInvocationReasons.SyntaxChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedProjectConfigurationChanged = new(PredefinedInvocationReasons.ProjectConfigurationChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentOpened = new(PredefinedInvocationReasons.DocumentOpened); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentRemoved = new(PredefinedInvocationReasons.DocumentRemoved); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentClosed = new(PredefinedInvocationReasons.DocumentClosed); public static readonly UnitTestingInvocationReasonsWrapper PredefinedHighPriority = new(PredefinedInvocationReasons.HighPriority); public static readonly UnitTestingInvocationReasonsWrapper PredefinedProjectParseOptionsChanged = new(PredefinedInvocationReasons.ProjectParseOptionsChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSolutionRemoved = new(PredefinedInvocationReasons.SolutionRemoved); internal InvocationReasons UnderlyingObject { get; } internal UnitTestingInvocationReasonsWrapper(InvocationReasons underlyingObject) => UnderlyingObject = underlyingObject; public UnitTestingInvocationReasonsWrapper(string reason) : this(new InvocationReasons(reason)) { } public UnitTestingInvocationReasonsWrapper With(UnitTestingInvocationReasonsWrapper reason) => new(reason.UnderlyingObject.With(UnderlyingObject)); public bool IsReanalyze() => UnderlyingObject.Contains(PredefinedInvocationReasons.Reanalyze); public bool HasSemanticChanged() => UnderlyingObject.Contains(PredefinedInvocationReasons.SemanticChanged); public bool HasProjectConfigurationChanged() => UnderlyingObject.Contains(PredefinedInvocationReasons.ProjectConfigurationChanged); } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/GotoKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class GotoKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public GotoKeywordRecommender() : base(SyntaxKind.GotoKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class GotoKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public GotoKeywordRecommender() : base(SyntaxKind.GotoKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/Core/Portable/Common/GlyphTags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tags; namespace Microsoft.CodeAnalysis { internal static class GlyphTags { public static ImmutableArray<string> GetTags(Glyph glyph) => glyph switch { Glyph.Assembly => WellKnownTagArrays.Assembly, Glyph.BasicFile => WellKnownTagArrays.VisualBasicFile, Glyph.BasicProject => WellKnownTagArrays.VisualBasicProject, Glyph.ClassPublic => WellKnownTagArrays.ClassPublic, Glyph.ClassProtected => WellKnownTagArrays.ClassProtected, Glyph.ClassPrivate => WellKnownTagArrays.ClassPrivate, Glyph.ClassInternal => WellKnownTagArrays.ClassInternal, Glyph.CSharpFile => WellKnownTagArrays.CSharpFile, Glyph.CSharpProject => WellKnownTagArrays.CSharpProject, Glyph.ConstantPublic => WellKnownTagArrays.ConstantPublic, Glyph.ConstantProtected => WellKnownTagArrays.ConstantProtected, Glyph.ConstantPrivate => WellKnownTagArrays.ConstantPrivate, Glyph.ConstantInternal => WellKnownTagArrays.ConstantInternal, Glyph.DelegatePublic => WellKnownTagArrays.DelegatePublic, Glyph.DelegateProtected => WellKnownTagArrays.DelegateProtected, Glyph.DelegatePrivate => WellKnownTagArrays.DelegatePrivate, Glyph.DelegateInternal => WellKnownTagArrays.DelegateInternal, Glyph.EnumPublic => WellKnownTagArrays.EnumPublic, Glyph.EnumProtected => WellKnownTagArrays.EnumProtected, Glyph.EnumPrivate => WellKnownTagArrays.EnumPrivate, Glyph.EnumInternal => WellKnownTagArrays.EnumInternal, Glyph.EnumMemberPublic => WellKnownTagArrays.EnumMemberPublic, Glyph.EnumMemberProtected => WellKnownTagArrays.EnumMemberProtected, Glyph.EnumMemberPrivate => WellKnownTagArrays.EnumMemberPrivate, Glyph.EnumMemberInternal => WellKnownTagArrays.EnumMemberInternal, Glyph.Error => WellKnownTagArrays.Error, Glyph.EventPublic => WellKnownTagArrays.EventPublic, Glyph.EventProtected => WellKnownTagArrays.EventProtected, Glyph.EventPrivate => WellKnownTagArrays.EventPrivate, Glyph.EventInternal => WellKnownTagArrays.EventInternal, Glyph.ExtensionMethodPublic => WellKnownTagArrays.ExtensionMethodPublic, Glyph.ExtensionMethodProtected => WellKnownTagArrays.ExtensionMethodProtected, Glyph.ExtensionMethodPrivate => WellKnownTagArrays.ExtensionMethodPrivate, Glyph.ExtensionMethodInternal => WellKnownTagArrays.ExtensionMethodInternal, Glyph.FieldPublic => WellKnownTagArrays.FieldPublic, Glyph.FieldProtected => WellKnownTagArrays.FieldProtected, Glyph.FieldPrivate => WellKnownTagArrays.FieldPrivate, Glyph.FieldInternal => WellKnownTagArrays.FieldInternal, Glyph.InterfacePublic => WellKnownTagArrays.InterfacePublic, Glyph.InterfaceProtected => WellKnownTagArrays.InterfaceProtected, Glyph.InterfacePrivate => WellKnownTagArrays.InterfacePrivate, Glyph.InterfaceInternal => WellKnownTagArrays.InterfaceInternal, Glyph.Intrinsic => WellKnownTagArrays.Intrinsic, Glyph.Keyword => WellKnownTagArrays.Keyword, Glyph.Label => WellKnownTagArrays.Label, Glyph.Local => WellKnownTagArrays.Local, Glyph.Namespace => WellKnownTagArrays.Namespace, Glyph.MethodPublic => WellKnownTagArrays.MethodPublic, Glyph.MethodProtected => WellKnownTagArrays.MethodProtected, Glyph.MethodPrivate => WellKnownTagArrays.MethodPrivate, Glyph.MethodInternal => WellKnownTagArrays.MethodInternal, Glyph.ModulePublic => WellKnownTagArrays.ModulePublic, Glyph.ModuleProtected => WellKnownTagArrays.ModuleProtected, Glyph.ModulePrivate => WellKnownTagArrays.ModulePrivate, Glyph.ModuleInternal => WellKnownTagArrays.ModuleInternal, Glyph.OpenFolder => WellKnownTagArrays.Folder, Glyph.Operator => WellKnownTagArrays.Operator, Glyph.Parameter => WellKnownTagArrays.Parameter, Glyph.PropertyPublic => WellKnownTagArrays.PropertyPublic, Glyph.PropertyProtected => WellKnownTagArrays.PropertyProtected, Glyph.PropertyPrivate => WellKnownTagArrays.PropertyPrivate, Glyph.PropertyInternal => WellKnownTagArrays.PropertyInternal, Glyph.RangeVariable => WellKnownTagArrays.RangeVariable, Glyph.Reference => WellKnownTagArrays.Reference, Glyph.StructurePublic => WellKnownTagArrays.StructurePublic, Glyph.StructureProtected => WellKnownTagArrays.StructureProtected, Glyph.StructurePrivate => WellKnownTagArrays.StructurePrivate, Glyph.StructureInternal => WellKnownTagArrays.StructureInternal, Glyph.TypeParameter => WellKnownTagArrays.TypeParameter, Glyph.Snippet => WellKnownTagArrays.Snippet, Glyph.CompletionWarning => WellKnownTagArrays.Warning, Glyph.StatusInformation => WellKnownTagArrays.StatusInformation, _ => ImmutableArray<string>.Empty, }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis { internal static class GlyphTags { public static ImmutableArray<string> GetTags(Glyph glyph) => glyph switch { Glyph.Assembly => WellKnownTagArrays.Assembly, Glyph.BasicFile => WellKnownTagArrays.VisualBasicFile, Glyph.BasicProject => WellKnownTagArrays.VisualBasicProject, Glyph.ClassPublic => WellKnownTagArrays.ClassPublic, Glyph.ClassProtected => WellKnownTagArrays.ClassProtected, Glyph.ClassPrivate => WellKnownTagArrays.ClassPrivate, Glyph.ClassInternal => WellKnownTagArrays.ClassInternal, Glyph.CSharpFile => WellKnownTagArrays.CSharpFile, Glyph.CSharpProject => WellKnownTagArrays.CSharpProject, Glyph.ConstantPublic => WellKnownTagArrays.ConstantPublic, Glyph.ConstantProtected => WellKnownTagArrays.ConstantProtected, Glyph.ConstantPrivate => WellKnownTagArrays.ConstantPrivate, Glyph.ConstantInternal => WellKnownTagArrays.ConstantInternal, Glyph.DelegatePublic => WellKnownTagArrays.DelegatePublic, Glyph.DelegateProtected => WellKnownTagArrays.DelegateProtected, Glyph.DelegatePrivate => WellKnownTagArrays.DelegatePrivate, Glyph.DelegateInternal => WellKnownTagArrays.DelegateInternal, Glyph.EnumPublic => WellKnownTagArrays.EnumPublic, Glyph.EnumProtected => WellKnownTagArrays.EnumProtected, Glyph.EnumPrivate => WellKnownTagArrays.EnumPrivate, Glyph.EnumInternal => WellKnownTagArrays.EnumInternal, Glyph.EnumMemberPublic => WellKnownTagArrays.EnumMemberPublic, Glyph.EnumMemberProtected => WellKnownTagArrays.EnumMemberProtected, Glyph.EnumMemberPrivate => WellKnownTagArrays.EnumMemberPrivate, Glyph.EnumMemberInternal => WellKnownTagArrays.EnumMemberInternal, Glyph.Error => WellKnownTagArrays.Error, Glyph.EventPublic => WellKnownTagArrays.EventPublic, Glyph.EventProtected => WellKnownTagArrays.EventProtected, Glyph.EventPrivate => WellKnownTagArrays.EventPrivate, Glyph.EventInternal => WellKnownTagArrays.EventInternal, Glyph.ExtensionMethodPublic => WellKnownTagArrays.ExtensionMethodPublic, Glyph.ExtensionMethodProtected => WellKnownTagArrays.ExtensionMethodProtected, Glyph.ExtensionMethodPrivate => WellKnownTagArrays.ExtensionMethodPrivate, Glyph.ExtensionMethodInternal => WellKnownTagArrays.ExtensionMethodInternal, Glyph.FieldPublic => WellKnownTagArrays.FieldPublic, Glyph.FieldProtected => WellKnownTagArrays.FieldProtected, Glyph.FieldPrivate => WellKnownTagArrays.FieldPrivate, Glyph.FieldInternal => WellKnownTagArrays.FieldInternal, Glyph.InterfacePublic => WellKnownTagArrays.InterfacePublic, Glyph.InterfaceProtected => WellKnownTagArrays.InterfaceProtected, Glyph.InterfacePrivate => WellKnownTagArrays.InterfacePrivate, Glyph.InterfaceInternal => WellKnownTagArrays.InterfaceInternal, Glyph.Intrinsic => WellKnownTagArrays.Intrinsic, Glyph.Keyword => WellKnownTagArrays.Keyword, Glyph.Label => WellKnownTagArrays.Label, Glyph.Local => WellKnownTagArrays.Local, Glyph.Namespace => WellKnownTagArrays.Namespace, Glyph.MethodPublic => WellKnownTagArrays.MethodPublic, Glyph.MethodProtected => WellKnownTagArrays.MethodProtected, Glyph.MethodPrivate => WellKnownTagArrays.MethodPrivate, Glyph.MethodInternal => WellKnownTagArrays.MethodInternal, Glyph.ModulePublic => WellKnownTagArrays.ModulePublic, Glyph.ModuleProtected => WellKnownTagArrays.ModuleProtected, Glyph.ModulePrivate => WellKnownTagArrays.ModulePrivate, Glyph.ModuleInternal => WellKnownTagArrays.ModuleInternal, Glyph.OpenFolder => WellKnownTagArrays.Folder, Glyph.Operator => WellKnownTagArrays.Operator, Glyph.Parameter => WellKnownTagArrays.Parameter, Glyph.PropertyPublic => WellKnownTagArrays.PropertyPublic, Glyph.PropertyProtected => WellKnownTagArrays.PropertyProtected, Glyph.PropertyPrivate => WellKnownTagArrays.PropertyPrivate, Glyph.PropertyInternal => WellKnownTagArrays.PropertyInternal, Glyph.RangeVariable => WellKnownTagArrays.RangeVariable, Glyph.Reference => WellKnownTagArrays.Reference, Glyph.StructurePublic => WellKnownTagArrays.StructurePublic, Glyph.StructureProtected => WellKnownTagArrays.StructureProtected, Glyph.StructurePrivate => WellKnownTagArrays.StructurePrivate, Glyph.StructureInternal => WellKnownTagArrays.StructureInternal, Glyph.TypeParameter => WellKnownTagArrays.TypeParameter, Glyph.Snippet => WellKnownTagArrays.Snippet, Glyph.CompletionWarning => WellKnownTagArrays.Warning, Glyph.StatusInformation => WellKnownTagArrays.StatusInformation, _ => ImmutableArray<string>.Empty, }; } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Analyzers/Core/Analyzers/MatchFolderAndNamespace/AbstractMatchFolderAndNamespaceDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace { internal abstract class AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<TSyntaxKind, TNamespaceSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TNamespaceSyntax : SyntaxNode { private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Namespace_does_not_match_folder_structure), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInsideMessage = new( nameof(AnalyzersResources.Namespace_0_does_not_match_folder_structure_expected_1), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat .FullyQualifiedFormat .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted); protected AbstractMatchFolderAndNamespaceDiagnosticAnalyzer() : base(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId, EnforceOnBuildValues.MatchFolderAndNamespace, CodeStyleOptions2.PreferNamespaceAndFolderMatchStructure, s_localizableTitle, s_localizableInsideMessage) { } protected abstract ISyntaxFacts GetSyntaxFacts(); protected abstract ImmutableArray<TSyntaxKind> GetSyntaxKindsToAnalyze(); protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNamespaceNode, GetSyntaxKindsToAnalyze()); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context) { // It's ok to not have a rootnamespace property, but if it's there we want to use it correctly context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.RootNamespaceOption, out var rootNamespace); // Project directory is a must to correctly get the relative path and construct a namespace if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.ProjectDirOption, out var projectDir) || string.IsNullOrEmpty(projectDir)) { return; } var namespaceDecl = (TNamespaceSyntax)context.Node; var symbol = context.SemanticModel.GetDeclaredSymbol(namespaceDecl); RoslynDebug.AssertNotNull(symbol); var currentNamespace = symbol.ToDisplayString(s_namespaceDisplayFormat); if (IsFileAndNamespaceMismatch(namespaceDecl, rootNamespace, projectDir, currentNamespace, out var targetNamespace) && IsFixSupported(context.SemanticModel, namespaceDecl, context.CancellationToken)) { var nameSyntax = GetSyntaxFacts().GetNameOfNamespaceDeclaration(namespaceDecl); RoslynDebug.AssertNotNull(nameSyntax); context.ReportDiagnostic(Diagnostic.Create( Descriptor, nameSyntax.GetLocation(), additionalLocations: null, properties: ImmutableDictionary<string, string?>.Empty.Add(MatchFolderAndNamespaceConstants.TargetNamespace, targetNamespace), messageArgs: new[] { currentNamespace, targetNamespace })); } } private bool IsFixSupported(SemanticModel semanticModel, TNamespaceSyntax namespaceDeclaration, CancellationToken cancellationToken) { var root = namespaceDeclaration.SyntaxTree.GetRoot(cancellationToken); // It should not be nested in other namespaces if (namespaceDeclaration.Ancestors().OfType<TNamespaceSyntax>().Any()) { return false; } // It should not contain a namespace var containsNamespace = namespaceDeclaration .DescendantNodes(n => n is TNamespaceSyntax) .OfType<TNamespaceSyntax>().Any(); if (containsNamespace) { return false; } // The current namespace should be valid var isCurrentNamespaceInvalid = GetSyntaxFacts() .GetNameOfNamespaceDeclaration(namespaceDeclaration) ?.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ?? false; if (isCurrentNamespaceInvalid) { return false; } // It should not contain partial classes with more than one instance in the semantic model. The // fixer does not support this scenario. var containsPartialType = ContainsPartialTypeWithMultipleDeclarations(namespaceDeclaration, semanticModel); if (containsPartialType) { return false; } return true; } private bool IsFileAndNamespaceMismatch( TNamespaceSyntax namespaceDeclaration, string? rootNamespace, string projectDir, string currentNamespace, [NotNullWhen(returnValue: true)] out string? targetNamespace) { if (!PathUtilities.IsChildPath(projectDir, namespaceDeclaration.SyntaxTree.FilePath)) { // The file does not exist within the project directory targetNamespace = null; return false; } var relativeDirectoryPath = PathUtilities.GetRelativePath( projectDir, PathUtilities.GetDirectoryName(namespaceDeclaration.SyntaxTree.FilePath)!); var folders = relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var expectedNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(folders, GetSyntaxFacts(), rootNamespace); if (RoslynString.IsNullOrWhiteSpace(expectedNamespace) || expectedNamespace.Equals(currentNamespace, StringComparison.OrdinalIgnoreCase)) { // The namespace currently matches the folder structure or is invalid, in which case we don't want // to provide a diagnostic. targetNamespace = null; return false; } targetNamespace = expectedNamespace; return true; } /// <summary> /// Returns true if the namespace declaration contains one or more partial types with multiple declarations. /// </summary> protected bool ContainsPartialTypeWithMultipleDeclarations(TNamespaceSyntax namespaceDeclaration, SemanticModel semanticModel) { var syntaxFacts = GetSyntaxFacts(); var typeDeclarations = syntaxFacts.GetMembersOfNamespaceDeclaration(namespaceDeclaration) .Where(member => syntaxFacts.IsTypeDeclaration(member)); foreach (var typeDecl in typeDeclarations) { var symbol = semanticModel.GetDeclaredSymbol(typeDecl); // Simplify the check by assuming no multiple partial declarations in one document if (symbol is ITypeSymbol typeSymbol && typeSymbol.DeclaringSyntaxReferences.Length > 1) { return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace { internal abstract class AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<TSyntaxKind, TNamespaceSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TNamespaceSyntax : SyntaxNode { private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Namespace_does_not_match_folder_structure), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInsideMessage = new( nameof(AnalyzersResources.Namespace_0_does_not_match_folder_structure_expected_1), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat .FullyQualifiedFormat .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted); protected AbstractMatchFolderAndNamespaceDiagnosticAnalyzer() : base(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId, EnforceOnBuildValues.MatchFolderAndNamespace, CodeStyleOptions2.PreferNamespaceAndFolderMatchStructure, s_localizableTitle, s_localizableInsideMessage) { } protected abstract ISyntaxFacts GetSyntaxFacts(); protected abstract ImmutableArray<TSyntaxKind> GetSyntaxKindsToAnalyze(); protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNamespaceNode, GetSyntaxKindsToAnalyze()); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context) { // It's ok to not have a rootnamespace property, but if it's there we want to use it correctly context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.RootNamespaceOption, out var rootNamespace); // Project directory is a must to correctly get the relative path and construct a namespace if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.ProjectDirOption, out var projectDir) || string.IsNullOrEmpty(projectDir)) { return; } var namespaceDecl = (TNamespaceSyntax)context.Node; var symbol = context.SemanticModel.GetDeclaredSymbol(namespaceDecl); RoslynDebug.AssertNotNull(symbol); var currentNamespace = symbol.ToDisplayString(s_namespaceDisplayFormat); if (IsFileAndNamespaceMismatch(namespaceDecl, rootNamespace, projectDir, currentNamespace, out var targetNamespace) && IsFixSupported(context.SemanticModel, namespaceDecl, context.CancellationToken)) { var nameSyntax = GetSyntaxFacts().GetNameOfNamespaceDeclaration(namespaceDecl); RoslynDebug.AssertNotNull(nameSyntax); context.ReportDiagnostic(Diagnostic.Create( Descriptor, nameSyntax.GetLocation(), additionalLocations: null, properties: ImmutableDictionary<string, string?>.Empty.Add(MatchFolderAndNamespaceConstants.TargetNamespace, targetNamespace), messageArgs: new[] { currentNamespace, targetNamespace })); } } private bool IsFixSupported(SemanticModel semanticModel, TNamespaceSyntax namespaceDeclaration, CancellationToken cancellationToken) { var root = namespaceDeclaration.SyntaxTree.GetRoot(cancellationToken); // It should not be nested in other namespaces if (namespaceDeclaration.Ancestors().OfType<TNamespaceSyntax>().Any()) { return false; } // It should not contain a namespace var containsNamespace = namespaceDeclaration .DescendantNodes(n => n is TNamespaceSyntax) .OfType<TNamespaceSyntax>().Any(); if (containsNamespace) { return false; } // The current namespace should be valid var isCurrentNamespaceInvalid = GetSyntaxFacts() .GetNameOfNamespaceDeclaration(namespaceDeclaration) ?.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ?? false; if (isCurrentNamespaceInvalid) { return false; } // It should not contain partial classes with more than one instance in the semantic model. The // fixer does not support this scenario. var containsPartialType = ContainsPartialTypeWithMultipleDeclarations(namespaceDeclaration, semanticModel); if (containsPartialType) { return false; } return true; } private bool IsFileAndNamespaceMismatch( TNamespaceSyntax namespaceDeclaration, string? rootNamespace, string projectDir, string currentNamespace, [NotNullWhen(returnValue: true)] out string? targetNamespace) { if (!PathUtilities.IsChildPath(projectDir, namespaceDeclaration.SyntaxTree.FilePath)) { // The file does not exist within the project directory targetNamespace = null; return false; } var relativeDirectoryPath = PathUtilities.GetRelativePath( projectDir, PathUtilities.GetDirectoryName(namespaceDeclaration.SyntaxTree.FilePath)!); var folders = relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var expectedNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(folders, GetSyntaxFacts(), rootNamespace); if (RoslynString.IsNullOrWhiteSpace(expectedNamespace) || expectedNamespace.Equals(currentNamespace, StringComparison.OrdinalIgnoreCase)) { // The namespace currently matches the folder structure or is invalid, in which case we don't want // to provide a diagnostic. targetNamespace = null; return false; } targetNamespace = expectedNamespace; return true; } /// <summary> /// Returns true if the namespace declaration contains one or more partial types with multiple declarations. /// </summary> protected bool ContainsPartialTypeWithMultipleDeclarations(TNamespaceSyntax namespaceDeclaration, SemanticModel semanticModel) { var syntaxFacts = GetSyntaxFacts(); var typeDeclarations = syntaxFacts.GetMembersOfNamespaceDeclaration(namespaceDeclaration) .Where(member => syntaxFacts.IsTypeDeclaration(member)); foreach (var typeDecl in typeDeclarations) { var symbol = semanticModel.GetDeclaredSymbol(typeDecl); // Simplify the check by assuming no multiple partial declarations in one document if (symbol is ITypeSymbol typeSymbol && typeSymbol.DeclaringSyntaxReferences.Length > 1) { return true; } } return false; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentRenameName)] internal class RenameHandler : AbstractStatelessRequestHandler<LSP.RenameParams, WorkspaceEdit?> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameHandler() { } public override string Method => LSP.Methods.TextDocumentRenameName; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override TextDocumentIdentifier? GetTextDocumentIdentifier(RenameParams request) => request.TextDocument; public override async Task<WorkspaceEdit?> HandleRequestAsync(RenameParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document != null) { var oldSolution = document.Project.Solution; var renameService = document.Project.LanguageServices.GetRequiredService<IEditorInlineRenameService>(); var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var renameInfo = await renameService.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false); if (!renameInfo.CanRename) { return null; } var renameLocationSet = await renameInfo.FindRenameLocationsAsync(oldSolution.Workspace.Options, cancellationToken).ConfigureAwait(false); var renameReplacementInfo = await renameLocationSet.GetReplacementsAsync(request.NewName, oldSolution.Workspace.Options, cancellationToken).ConfigureAwait(false); var renamedSolution = renameReplacementInfo.NewSolution; var solutionChanges = renamedSolution.GetChanges(oldSolution); // Linked files can correspond to multiple roslyn documents each with changes. Merge the changes in the linked files so that all linked documents have the same text. // Then we can just take the text changes from the first document to avoid returning duplicate edits. renamedSolution = await renamedSolution.WithMergedLinkedFileChangesAsync(oldSolution, solutionChanges, cancellationToken: cancellationToken).ConfigureAwait(false); solutionChanges = renamedSolution.GetChanges(oldSolution); var changedDocuments = solutionChanges .GetProjectChanges() .SelectMany(p => p.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true)) .GroupBy(docId => renamedSolution.GetRequiredDocument(docId).FilePath, StringComparer.OrdinalIgnoreCase).Select(group => group.First()); var textDiffService = renamedSolution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>(); var documentEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync(changedDocuments, renamedSolution.GetRequiredDocument, oldSolution.GetRequiredDocument, textDiffService, cancellationToken).ConfigureAwait(false); return new WorkspaceEdit { DocumentChanges = documentEdits }; } 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentRenameName)] internal class RenameHandler : AbstractStatelessRequestHandler<LSP.RenameParams, WorkspaceEdit?> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameHandler() { } public override string Method => LSP.Methods.TextDocumentRenameName; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override TextDocumentIdentifier? GetTextDocumentIdentifier(RenameParams request) => request.TextDocument; public override async Task<WorkspaceEdit?> HandleRequestAsync(RenameParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document != null) { var oldSolution = document.Project.Solution; var renameService = document.Project.LanguageServices.GetRequiredService<IEditorInlineRenameService>(); var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var renameInfo = await renameService.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false); if (!renameInfo.CanRename) { return null; } var renameLocationSet = await renameInfo.FindRenameLocationsAsync(oldSolution.Workspace.Options, cancellationToken).ConfigureAwait(false); var renameReplacementInfo = await renameLocationSet.GetReplacementsAsync(request.NewName, oldSolution.Workspace.Options, cancellationToken).ConfigureAwait(false); var renamedSolution = renameReplacementInfo.NewSolution; var solutionChanges = renamedSolution.GetChanges(oldSolution); // Linked files can correspond to multiple roslyn documents each with changes. Merge the changes in the linked files so that all linked documents have the same text. // Then we can just take the text changes from the first document to avoid returning duplicate edits. renamedSolution = await renamedSolution.WithMergedLinkedFileChangesAsync(oldSolution, solutionChanges, cancellationToken: cancellationToken).ConfigureAwait(false); solutionChanges = renamedSolution.GetChanges(oldSolution); var changedDocuments = solutionChanges .GetProjectChanges() .SelectMany(p => p.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true)) .GroupBy(docId => renamedSolution.GetRequiredDocument(docId).FilePath, StringComparer.OrdinalIgnoreCase).Select(group => group.First()); var textDiffService = renamedSolution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>(); var documentEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync(changedDocuments, renamedSolution.GetRequiredDocument, oldSolution.GetRequiredDocument, textDiffService, cancellationToken).ConfigureAwait(false); return new WorkspaceEdit { DocumentChanges = documentEdits }; } return null; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/Core/Portable/Diagnostics/DefaultDiagnosticAnalyzerService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [Shared] [ExportIncrementalAnalyzerProvider(WellKnownSolutionCrawlerAnalyzers.Diagnostic, workspaceKinds: null)] internal partial class DefaultDiagnosticAnalyzerService : IIncrementalAnalyzerProvider, IDiagnosticUpdateSource { private readonly DiagnosticAnalyzerInfoCache _analyzerInfoCache; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDiagnosticAnalyzerService( IDiagnosticUpdateSourceRegistrationService registrationService) { _analyzerInfoCache = new DiagnosticAnalyzerInfoCache(); registrationService.Register(this); } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { if (!workspace.Options.GetOption(ServiceComponentOnOffOptions.DiagnosticProvider)) { return null; } return new DefaultDiagnosticIncrementalAnalyzer(this, workspace); } public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } // this only support push model, pull model will be provided by DiagnosticService by caching everything this one pushed public bool SupportGetDiagnostics => false; public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { // pull model not supported return new ValueTask<ImmutableArray<DiagnosticData>>(ImmutableArray<DiagnosticData>.Empty); } internal void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs state) => DiagnosticsUpdated?.Invoke(this, state); private class DefaultDiagnosticIncrementalAnalyzer : IIncrementalAnalyzer2 { private readonly DefaultDiagnosticAnalyzerService _service; private readonly Workspace _workspace; private readonly InProcOrRemoteHostAnalyzerRunner _diagnosticAnalyzerRunner; public DefaultDiagnosticIncrementalAnalyzer(DefaultDiagnosticAnalyzerService service, Workspace workspace) { _service = service; _workspace = workspace; _diagnosticAnalyzerRunner = new InProcOrRemoteHostAnalyzerRunner(service._analyzerInfoCache); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { if (e.Option == InternalRuntimeDiagnosticOptions.Syntax || e.Option == InternalRuntimeDiagnosticOptions.Semantic || e.Option == InternalRuntimeDiagnosticOptions.ScriptSemantic) { return true; } return false; } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeSyntaxOrNonSourceDocumentAsync(document, cancellationToken); public Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeSyntaxOrNonSourceDocumentAsync(textDocument, cancellationToken); private async Task AnalyzeSyntaxOrNonSourceDocumentAsync(TextDocument textDocument, CancellationToken cancellationToken) { Debug.Assert(textDocument.Project.Solution.Workspace == _workspace); // right now, there is no way to observe diagnostics for closed file. if (!_workspace.IsDocumentOpen(textDocument.Id) || !_workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.Syntax)) { return; } await AnalyzeForKindAsync(textDocument, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false); } public async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) { Debug.Assert(document.Project.Solution.Workspace == _workspace); if (!IsSemanticAnalysisOn()) { return; } await AnalyzeForKindAsync(document, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false); bool IsSemanticAnalysisOn() { // right now, there is no way to observe diagnostics for closed file. if (!_workspace.IsDocumentOpen(document.Id)) { return false; } if (_workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.Semantic)) { return true; } return _workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.ScriptSemantic) && document.SourceCodeKind == SourceCodeKind.Script; } } private async Task AnalyzeForKindAsync(TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { var diagnosticData = await GetDiagnosticsAsync(document, kind, cancellationToken).ConfigureAwait(false); _service.RaiseDiagnosticsUpdated( DiagnosticsUpdatedArgs.DiagnosticsCreated(new DefaultUpdateArgsId(_workspace.Kind, kind, document.Id), _workspace, document.Project.Solution, document.Project.Id, document.Id, diagnosticData)); } /// <summary> /// Get diagnostics for the given document. /// /// This is a simple API to get all diagnostics for the given document. /// /// The intended audience for this API is for ones that pefer simplicity over performance such as document that belong to misc project. /// this doesn't cache nor use cache for anything. it will re-caculate new diagnostics every time for the given document. /// it will not persist any data on disk nor use OOP to calculate the data. /// /// This should never be used when performance is a big concern. for such context, use much complex API from IDiagnosticAnalyzerService /// that provide all kinds of knobs/cache/persistency/OOP to get better perf over simplicity. /// </summary> private async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync( TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { var loadDiagnostic = await document.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false); if (loadDiagnostic != null) { return ImmutableArray.Create(DiagnosticData.Create(loadDiagnostic, document)); } var project = document.Project; var analyzers = GetAnalyzers(project.Solution.State.Analyzers, project); if (analyzers.IsEmpty) { return ImmutableArray<DiagnosticData>.Empty; } var compilationWithAnalyzers = await AnalyzerHelper.CreateCompilationWithAnalyzersAsync( project, analyzers, includeSuppressedDiagnostics: false, cancellationToken).ConfigureAwait(false); var analysisScope = new DocumentAnalysisScope(document, span: null, analyzers, kind); var executor = new DocumentAnalysisExecutor(analysisScope, compilationWithAnalyzers, _diagnosticAnalyzerRunner, logPerformanceInfo: true); var builder = ArrayBuilder<DiagnosticData>.GetInstance(); foreach (var analyzer in analyzers) { builder.AddRange(await executor.ComputeDiagnosticsAsync(analyzer, cancellationToken).ConfigureAwait(false)); } return builder.ToImmutableAndFree(); } private static ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(HostDiagnosticAnalyzers hostAnalyzers, Project project) { // C# or VB document that supports compiler var compilerAnalyzer = hostAnalyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer != null) { return ImmutableArray.Create(compilerAnalyzer); } // document that doesn't support compiler diagnostics such as FSharp or TypeScript return hostAnalyzers.CreateDiagnosticAnalyzersPerReference(project).Values.SelectMany(v => v).ToImmutableArrayOrEmpty(); } public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { // a file is removed from a solution // // here syntax and semantic indicates type of errors not where it is originated from. // Option.Semantic or Option.ScriptSemantic indicates what kind of document we will produce semantic errors from. // Option.Semantic == true means we will generate semantic errors for all document type // Option.ScriptSemantic == true means we will generate semantic errors only for script document type // both of them at the end generates semantic errors RaiseEmptyDiagnosticUpdated(AnalysisKind.Syntax, documentId); RaiseEmptyDiagnosticUpdated(AnalysisKind.Semantic, documentId); return Task.CompletedTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { // no closed file diagnostic and file is not opened, remove any existing diagnostics return RemoveDocumentAsync(document.Id, cancellationToken); } public Task NonSourceDocumentResetAsync(TextDocument textDocument, CancellationToken cancellationToken) { // no closed file diagnostic and file is not opened, remove any existing diagnostics return RemoveDocumentAsync(textDocument.Id, cancellationToken); } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => DocumentResetAsync(document, cancellationToken); public Task NonSourceDocumentCloseAsync(TextDocument textDocument, CancellationToken cancellationToken) => NonSourceDocumentResetAsync(textDocument, cancellationToken); private void RaiseEmptyDiagnosticUpdated(AnalysisKind kind, DocumentId documentId) { _service.RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs.DiagnosticsRemoved( new DefaultUpdateArgsId(_workspace.Kind, kind, documentId), _workspace, null, documentId.ProjectId, documentId)); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task NonSourceDocumentOpenAsync(TextDocument textDocument, CancellationToken cancellationToken) => Task.CompletedTask; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) => Task.CompletedTask; private class DefaultUpdateArgsId : BuildToolId.Base<int, DocumentId>, ISupportLiveUpdate { private readonly string _workspaceKind; public DefaultUpdateArgsId(string workspaceKind, AnalysisKind kind, DocumentId documentId) : base((int)kind, documentId) => _workspaceKind = workspaceKind; public override string BuildTool => PredefinedBuildTools.Live; public override bool Equals(object obj) { if (obj is not DefaultUpdateArgsId other) { return false; } return _workspaceKind == other._workspaceKind && base.Equals(obj); } public override int GetHashCode() => Hash.Combine(_workspaceKind.GetHashCode(), base.GetHashCode()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [Shared] [ExportIncrementalAnalyzerProvider(WellKnownSolutionCrawlerAnalyzers.Diagnostic, workspaceKinds: null)] internal partial class DefaultDiagnosticAnalyzerService : IIncrementalAnalyzerProvider, IDiagnosticUpdateSource { private readonly DiagnosticAnalyzerInfoCache _analyzerInfoCache; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDiagnosticAnalyzerService( IDiagnosticUpdateSourceRegistrationService registrationService) { _analyzerInfoCache = new DiagnosticAnalyzerInfoCache(); registrationService.Register(this); } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { if (!workspace.Options.GetOption(ServiceComponentOnOffOptions.DiagnosticProvider)) { return null; } return new DefaultDiagnosticIncrementalAnalyzer(this, workspace); } public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } // this only support push model, pull model will be provided by DiagnosticService by caching everything this one pushed public bool SupportGetDiagnostics => false; public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { // pull model not supported return new ValueTask<ImmutableArray<DiagnosticData>>(ImmutableArray<DiagnosticData>.Empty); } internal void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs state) => DiagnosticsUpdated?.Invoke(this, state); private class DefaultDiagnosticIncrementalAnalyzer : IIncrementalAnalyzer2 { private readonly DefaultDiagnosticAnalyzerService _service; private readonly Workspace _workspace; private readonly InProcOrRemoteHostAnalyzerRunner _diagnosticAnalyzerRunner; public DefaultDiagnosticIncrementalAnalyzer(DefaultDiagnosticAnalyzerService service, Workspace workspace) { _service = service; _workspace = workspace; _diagnosticAnalyzerRunner = new InProcOrRemoteHostAnalyzerRunner(service._analyzerInfoCache); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { if (e.Option == InternalRuntimeDiagnosticOptions.Syntax || e.Option == InternalRuntimeDiagnosticOptions.Semantic || e.Option == InternalRuntimeDiagnosticOptions.ScriptSemantic) { return true; } return false; } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeSyntaxOrNonSourceDocumentAsync(document, cancellationToken); public Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeSyntaxOrNonSourceDocumentAsync(textDocument, cancellationToken); private async Task AnalyzeSyntaxOrNonSourceDocumentAsync(TextDocument textDocument, CancellationToken cancellationToken) { Debug.Assert(textDocument.Project.Solution.Workspace == _workspace); // right now, there is no way to observe diagnostics for closed file. if (!_workspace.IsDocumentOpen(textDocument.Id) || !_workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.Syntax)) { return; } await AnalyzeForKindAsync(textDocument, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false); } public async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) { Debug.Assert(document.Project.Solution.Workspace == _workspace); if (!IsSemanticAnalysisOn()) { return; } await AnalyzeForKindAsync(document, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false); bool IsSemanticAnalysisOn() { // right now, there is no way to observe diagnostics for closed file. if (!_workspace.IsDocumentOpen(document.Id)) { return false; } if (_workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.Semantic)) { return true; } return _workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.ScriptSemantic) && document.SourceCodeKind == SourceCodeKind.Script; } } private async Task AnalyzeForKindAsync(TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { var diagnosticData = await GetDiagnosticsAsync(document, kind, cancellationToken).ConfigureAwait(false); _service.RaiseDiagnosticsUpdated( DiagnosticsUpdatedArgs.DiagnosticsCreated(new DefaultUpdateArgsId(_workspace.Kind, kind, document.Id), _workspace, document.Project.Solution, document.Project.Id, document.Id, diagnosticData)); } /// <summary> /// Get diagnostics for the given document. /// /// This is a simple API to get all diagnostics for the given document. /// /// The intended audience for this API is for ones that pefer simplicity over performance such as document that belong to misc project. /// this doesn't cache nor use cache for anything. it will re-caculate new diagnostics every time for the given document. /// it will not persist any data on disk nor use OOP to calculate the data. /// /// This should never be used when performance is a big concern. for such context, use much complex API from IDiagnosticAnalyzerService /// that provide all kinds of knobs/cache/persistency/OOP to get better perf over simplicity. /// </summary> private async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync( TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { var loadDiagnostic = await document.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false); if (loadDiagnostic != null) { return ImmutableArray.Create(DiagnosticData.Create(loadDiagnostic, document)); } var project = document.Project; var analyzers = GetAnalyzers(project.Solution.State.Analyzers, project); if (analyzers.IsEmpty) { return ImmutableArray<DiagnosticData>.Empty; } var compilationWithAnalyzers = await AnalyzerHelper.CreateCompilationWithAnalyzersAsync( project, analyzers, includeSuppressedDiagnostics: false, cancellationToken).ConfigureAwait(false); var analysisScope = new DocumentAnalysisScope(document, span: null, analyzers, kind); var executor = new DocumentAnalysisExecutor(analysisScope, compilationWithAnalyzers, _diagnosticAnalyzerRunner, logPerformanceInfo: true); var builder = ArrayBuilder<DiagnosticData>.GetInstance(); foreach (var analyzer in analyzers) { builder.AddRange(await executor.ComputeDiagnosticsAsync(analyzer, cancellationToken).ConfigureAwait(false)); } return builder.ToImmutableAndFree(); } private static ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(HostDiagnosticAnalyzers hostAnalyzers, Project project) { // C# or VB document that supports compiler var compilerAnalyzer = hostAnalyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer != null) { return ImmutableArray.Create(compilerAnalyzer); } // document that doesn't support compiler diagnostics such as FSharp or TypeScript return hostAnalyzers.CreateDiagnosticAnalyzersPerReference(project).Values.SelectMany(v => v).ToImmutableArrayOrEmpty(); } public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { // a file is removed from a solution // // here syntax and semantic indicates type of errors not where it is originated from. // Option.Semantic or Option.ScriptSemantic indicates what kind of document we will produce semantic errors from. // Option.Semantic == true means we will generate semantic errors for all document type // Option.ScriptSemantic == true means we will generate semantic errors only for script document type // both of them at the end generates semantic errors RaiseEmptyDiagnosticUpdated(AnalysisKind.Syntax, documentId); RaiseEmptyDiagnosticUpdated(AnalysisKind.Semantic, documentId); return Task.CompletedTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { // no closed file diagnostic and file is not opened, remove any existing diagnostics return RemoveDocumentAsync(document.Id, cancellationToken); } public Task NonSourceDocumentResetAsync(TextDocument textDocument, CancellationToken cancellationToken) { // no closed file diagnostic and file is not opened, remove any existing diagnostics return RemoveDocumentAsync(textDocument.Id, cancellationToken); } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => DocumentResetAsync(document, cancellationToken); public Task NonSourceDocumentCloseAsync(TextDocument textDocument, CancellationToken cancellationToken) => NonSourceDocumentResetAsync(textDocument, cancellationToken); private void RaiseEmptyDiagnosticUpdated(AnalysisKind kind, DocumentId documentId) { _service.RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs.DiagnosticsRemoved( new DefaultUpdateArgsId(_workspace.Kind, kind, documentId), _workspace, null, documentId.ProjectId, documentId)); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task NonSourceDocumentOpenAsync(TextDocument textDocument, CancellationToken cancellationToken) => Task.CompletedTask; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) => Task.CompletedTask; private class DefaultUpdateArgsId : BuildToolId.Base<int, DocumentId>, ISupportLiveUpdate { private readonly string _workspaceKind; public DefaultUpdateArgsId(string workspaceKind, AnalysisKind kind, DocumentId documentId) : base((int)kind, documentId) => _workspaceKind = workspaceKind; public override string BuildTool => PredefinedBuildTools.Live; public override bool Equals(object obj) { if (obj is not DefaultUpdateArgsId other) { return false; } return _workspaceKind == other._workspaceKind && base.Equals(obj); } public override int GetHashCode() => Hash.Combine(_workspaceKind.GetHashCode(), base.GetHashCode()); } } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/VisualStudio/CSharp/Test/Interactive/Commands/ResetInteractiveTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable extern alias InteractiveHost; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Roslyn.Test.Utilities; using Xunit; using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive.Commands { [UseExportProvider] public class ResetInteractiveTests { private string WorkspaceXmlStr => @"<Workspace> <Project Language=""Visual Basic"" AssemblyName=""ResetInteractiveVisualBasicSubproject"" CommonReferences=""true""> <Document FilePath=""VisualBasicDocument""></Document> </Project> <Project Language=""C#"" AssemblyName=""ResetInteractiveTestsAssembly"" CommonReferences=""true""> <ProjectReference>ResetInteractiveVisualBasicSubproject</ProjectReference> <Document FilePath=""ResetInteractiveTestsDocument""> namespace ResetInteractiveTestsDocument { class TestClass { } }</Document> </Project> </Workspace>"; [WpfFact] [Trait(Traits.Feature, Traits.Features.Interactive)] public async Task TestResetREPLWithProjectContext() { using var workspace = TestWorkspace.Create(WorkspaceXmlStr, composition: EditorTestCompositions.InteractiveWindow); var project = workspace.CurrentSolution.Projects.FirstOrDefault(p => p.AssemblyName == "ResetInteractiveTestsAssembly"); var document = project.Documents.FirstOrDefault(d => d.FilePath == "ResetInteractiveTestsDocument"); var replReferenceCommands = GetProjectReferences(workspace, project).Select(r => CreateReplReferenceCommand(r)); Assert.True(replReferenceCommands.Any(rc => rc.EndsWith(@"ResetInteractiveTestsAssembly.dll"""))); Assert.True(replReferenceCommands.Any(rc => rc.EndsWith(@"ResetInteractiveVisualBasicSubproject.dll"""))); var expectedReferences = replReferenceCommands.ToList(); var expectedUsings = new List<string> { @"using ""System"";", @"using ""ResetInteractiveTestsDocument"";" }; await AssertResetInteractiveAsync(workspace, project, buildSucceeds: true, expectedReferences: expectedReferences, expectedUsings: expectedUsings); // Test that no submissions are executed if the build fails. await AssertResetInteractiveAsync(workspace, project, buildSucceeds: false, expectedReferences: new List<string>()); } private async Task AssertResetInteractiveAsync( TestWorkspace workspace, Project project, bool buildSucceeds, List<string> expectedReferences = null, List<string> expectedUsings = null) { expectedReferences ??= new List<string>(); expectedUsings ??= new List<string>(); var testHost = new InteractiveWindowTestHost(workspace.ExportProvider.GetExportedValue<IInteractiveWindowFactoryService>()); var executedSubmissionCalls = new List<string>(); void executeSubmission(object _, string code) => executedSubmissionCalls.Add(code); testHost.Evaluator.OnExecute += executeSubmission; var uiThreadOperationExecutor = workspace.GetService<IUIThreadOperationExecutor>(); var editorOptionsFactoryService = workspace.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactoryService.GetOptions(testHost.Window.CurrentLanguageBuffer); var newLineCharacter = editorOptions.GetNewLineCharacter(); var resetInteractive = new TestResetInteractive( uiThreadOperationExecutor, editorOptionsFactoryService, CreateReplReferenceCommand, CreateImport, buildSucceeds: buildSucceeds) { References = ImmutableArray.CreateRange(GetProjectReferences(workspace, project)), ReferenceSearchPaths = ImmutableArray.Create("rsp1", "rsp2"), SourceSearchPaths = ImmutableArray.Create("ssp1", "ssp2"), ProjectNamespaces = ImmutableArray.Create("System", "ResetInteractiveTestsDocument", "VisualBasicResetInteractiveTestsDocument"), NamespacesToImport = ImmutableArray.Create("System", "ResetInteractiveTestsDocument"), ProjectDirectory = "pj", Platform = InteractiveHostPlatform.Desktop64, }; await resetInteractive.ExecuteAsync(testHost.Window, "Interactive C#"); // Validate that the project was rebuilt. Assert.Equal(1, resetInteractive.BuildProjectCount); Assert.Equal(0, resetInteractive.CancelBuildProjectCount); if (buildSucceeds) { Assert.Equal(InteractiveHostPlatform.Desktop64, testHost.Evaluator.ResetOptions.Platform); } else { Assert.Null(testHost.Evaluator.ResetOptions); } var expectedSubmissions = new List<string>(); if (expectedReferences.Any()) { expectedSubmissions.AddRange(expectedReferences.Select(r => r + newLineCharacter)); } if (expectedUsings.Any()) { expectedSubmissions.Add(string.Join(newLineCharacter, expectedUsings) + newLineCharacter); } AssertEx.Equal(expectedSubmissions, executedSubmissionCalls); testHost.Evaluator.OnExecute -= executeSubmission; } /// <summary> /// Simulates getting all project references. /// </summary> /// <param name="workspace">Workspace with the solution.</param> /// <param name="project">A project that should be built.</param> /// <returns>A list of paths that should be referenced.</returns> private IEnumerable<string> GetProjectReferences(TestWorkspace workspace, Project project) { var metadataReferences = project.MetadataReferences.Select(r => r.Display); var projectReferences = project.ProjectReferences.SelectMany(p => GetProjectReferences( workspace, workspace.CurrentSolution.GetProject(p.ProjectId))); var outputReference = new string[] { project.OutputFilePath }; return metadataReferences.Union(projectReferences).Concat(outputReference); } private string CreateReplReferenceCommand(string referenceName) { return $@"#r ""{referenceName}"""; } private string CreateImport(string importName) { return $@"using ""{importName}"";"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable extern alias InteractiveHost; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Roslyn.Test.Utilities; using Xunit; using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive.Commands { [UseExportProvider] public class ResetInteractiveTests { private string WorkspaceXmlStr => @"<Workspace> <Project Language=""Visual Basic"" AssemblyName=""ResetInteractiveVisualBasicSubproject"" CommonReferences=""true""> <Document FilePath=""VisualBasicDocument""></Document> </Project> <Project Language=""C#"" AssemblyName=""ResetInteractiveTestsAssembly"" CommonReferences=""true""> <ProjectReference>ResetInteractiveVisualBasicSubproject</ProjectReference> <Document FilePath=""ResetInteractiveTestsDocument""> namespace ResetInteractiveTestsDocument { class TestClass { } }</Document> </Project> </Workspace>"; [WpfFact] [Trait(Traits.Feature, Traits.Features.Interactive)] public async Task TestResetREPLWithProjectContext() { using var workspace = TestWorkspace.Create(WorkspaceXmlStr, composition: EditorTestCompositions.InteractiveWindow); var project = workspace.CurrentSolution.Projects.FirstOrDefault(p => p.AssemblyName == "ResetInteractiveTestsAssembly"); var document = project.Documents.FirstOrDefault(d => d.FilePath == "ResetInteractiveTestsDocument"); var replReferenceCommands = GetProjectReferences(workspace, project).Select(r => CreateReplReferenceCommand(r)); Assert.True(replReferenceCommands.Any(rc => rc.EndsWith(@"ResetInteractiveTestsAssembly.dll"""))); Assert.True(replReferenceCommands.Any(rc => rc.EndsWith(@"ResetInteractiveVisualBasicSubproject.dll"""))); var expectedReferences = replReferenceCommands.ToList(); var expectedUsings = new List<string> { @"using ""System"";", @"using ""ResetInteractiveTestsDocument"";" }; await AssertResetInteractiveAsync(workspace, project, buildSucceeds: true, expectedReferences: expectedReferences, expectedUsings: expectedUsings); // Test that no submissions are executed if the build fails. await AssertResetInteractiveAsync(workspace, project, buildSucceeds: false, expectedReferences: new List<string>()); } private async Task AssertResetInteractiveAsync( TestWorkspace workspace, Project project, bool buildSucceeds, List<string> expectedReferences = null, List<string> expectedUsings = null) { expectedReferences ??= new List<string>(); expectedUsings ??= new List<string>(); var testHost = new InteractiveWindowTestHost(workspace.ExportProvider.GetExportedValue<IInteractiveWindowFactoryService>()); var executedSubmissionCalls = new List<string>(); void executeSubmission(object _, string code) => executedSubmissionCalls.Add(code); testHost.Evaluator.OnExecute += executeSubmission; var uiThreadOperationExecutor = workspace.GetService<IUIThreadOperationExecutor>(); var editorOptionsFactoryService = workspace.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactoryService.GetOptions(testHost.Window.CurrentLanguageBuffer); var newLineCharacter = editorOptions.GetNewLineCharacter(); var resetInteractive = new TestResetInteractive( uiThreadOperationExecutor, editorOptionsFactoryService, CreateReplReferenceCommand, CreateImport, buildSucceeds: buildSucceeds) { References = ImmutableArray.CreateRange(GetProjectReferences(workspace, project)), ReferenceSearchPaths = ImmutableArray.Create("rsp1", "rsp2"), SourceSearchPaths = ImmutableArray.Create("ssp1", "ssp2"), ProjectNamespaces = ImmutableArray.Create("System", "ResetInteractiveTestsDocument", "VisualBasicResetInteractiveTestsDocument"), NamespacesToImport = ImmutableArray.Create("System", "ResetInteractiveTestsDocument"), ProjectDirectory = "pj", Platform = InteractiveHostPlatform.Desktop64, }; await resetInteractive.ExecuteAsync(testHost.Window, "Interactive C#"); // Validate that the project was rebuilt. Assert.Equal(1, resetInteractive.BuildProjectCount); Assert.Equal(0, resetInteractive.CancelBuildProjectCount); if (buildSucceeds) { Assert.Equal(InteractiveHostPlatform.Desktop64, testHost.Evaluator.ResetOptions.Platform); } else { Assert.Null(testHost.Evaluator.ResetOptions); } var expectedSubmissions = new List<string>(); if (expectedReferences.Any()) { expectedSubmissions.AddRange(expectedReferences.Select(r => r + newLineCharacter)); } if (expectedUsings.Any()) { expectedSubmissions.Add(string.Join(newLineCharacter, expectedUsings) + newLineCharacter); } AssertEx.Equal(expectedSubmissions, executedSubmissionCalls); testHost.Evaluator.OnExecute -= executeSubmission; } /// <summary> /// Simulates getting all project references. /// </summary> /// <param name="workspace">Workspace with the solution.</param> /// <param name="project">A project that should be built.</param> /// <returns>A list of paths that should be referenced.</returns> private IEnumerable<string> GetProjectReferences(TestWorkspace workspace, Project project) { var metadataReferences = project.MetadataReferences.Select(r => r.Display); var projectReferences = project.ProjectReferences.SelectMany(p => GetProjectReferences( workspace, workspace.CurrentSolution.GetProject(p.ProjectId))); var outputReference = new string[] { project.OutputFilePath }; return metadataReferences.Union(projectReferences).Concat(outputReference); } private string CreateReplReferenceCommand(string referenceName) { return $@"#r ""{referenceName}"""; } private string CreateImport(string importName) { return $@"using ""{importName}"";"; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefReturnTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RefReturnTests : CompilingTestBase { private CompilationVerifier CompileAndVerifyRef( string source, string expectedOutput = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes) { return CompileAndVerify( source, expectedOutput: expectedOutput, options: options, verify: verify); } [Fact] public void RefReturnRefAssignment() { CompileAndVerify(@" using System; class C { static readonly int _ro = 42; static int _rw = 42; static void Main() { Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; M1(ref _rw)++; Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; } static ref int M1(ref int rrw) => ref (rrw = ref _rw); static ref readonly int M2(in int rro) => ref (rro = ref _ro); static ref readonly int M3(in int rro) => ref (rro = ref _rw); }", verify: Verification.Fails, expectedOutput: @"42 42 42 43 42 43"); } [Fact] public void RefReturnArrayAccess() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnRefParameter() { var text = @" class Program { static ref int M(ref int i) { return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Skipped).VerifyIL("Program.M(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnOutParameter() { var text = @" class Program { static ref int M(out int i) { i = 0; return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(out int)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: stind.i4 IL_0003: ldarg.0 IL_0004: ret }"); } [Fact] public void RefReturnRefLocal() { var text = @" class Program { static ref int M(ref int i) { ref int local = ref i; local = 0; return ref local; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(ref int)", @" { // Code size 5 (0x5) .maxstack 3 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldc.i4.0 IL_0003: stind.i4 IL_0004: ret }"); } [Fact] public void RefReturnStaticProperty() { var text = @" class Program { static int field = 0; static ref int P { get { return ref field; } } static ref int M() { return ref P; } public static void Main() { var local = 42; // must be real local P = local; P = local; // assign again, should not use stack local System.Console.WriteLine(P); } } "; var v = CompileAndVerifyRef(text, expectedOutput: "42"); v.VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.P.get"" IL_0005: ret }"); v.VerifyIL("Program.Main()", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (int V_0) //local IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: call ""ref int Program.P.get"" IL_0008: ldloc.0 IL_0009: stind.i4 IL_000a: call ""ref int Program.P.get"" IL_000f: ldloc.0 IL_0010: stind.i4 IL_0011: call ""ref int Program.P.get"" IL_0016: ldind.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: ret }"); } [Fact] public void RefReturnClassInstanceProperty() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int M() { return ref P; } ref int M1() { return ref new Program().P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.P.get"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceProperty() { var text = @" struct Program { public ref int P { get { return ref (new int[1])[0]; } } ref int M() { return ref P; } ref int M1(ref Program program) { return ref program.P; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program.P; } } class Program3 { Program program = default(Program); ref int M() { return ref program.P; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceProperty() { var text = @" interface I { ref int P { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.P; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.P; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); } [Fact] public void RefReturnClassInstanceIndexer() { var text = @" class Program { int field = 0; ref int this[int i] { get { return ref field; } } ref int M() { return ref this[0]; } ref int M1() { return ref new Program()[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: ldc.i4.0 IL_0006: call ""ref int Program.this[int].get"" IL_000b: ret }"); } [Fact] public void RefReturnStructInstanceIndexer() { var text = @" struct Program { public ref int this[int i] { get { return ref (new int[1])[0]; } } ref int M() { return ref this[0]; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program[0]; } } class Program3 { Program program = default(Program); ref int M() { return ref program[0]; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); } [Fact] public void RefReturnConstrainedInstanceIndexer() { var text = @" interface I { ref int this[int i] { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t[0]; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t[0]; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldc.i4.0 IL_0007: callvirt ""ref int I.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); } [Fact] public void RefReturnStaticFieldLikeEvent() { var text = @" delegate void D(); class Program { static event D d; static ref D M() { return ref d; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""D Program.d"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceFieldLikeEvent() { var text = @" delegate void D(); class Program { event D d; ref D M() { return ref d; } ref D M1() { return ref new Program().d; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""D Program.d"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""D Program.d"" IL_000a: ret }"); } [Fact] public void RefReturnStaticField() { var text = @" class Program { static int i = 0; static ref int M() { return ref i; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""int Program.i"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceField() { var text = @" class Program { int i = 0; ref int M() { return ref i; } ref int M1() { return ref new Program().i; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""int Program.i"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceField() { var text = @" struct Program { public int i; } class Program2 { Program program = default(Program); ref int M(ref Program program) { return ref program.i; } ref int M() { return ref program.i; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Fails); compilation.VerifyIL("Program2.M(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldflda ""int Program.i"" IL_000b: ret }"); } [Fact] public void RefReturnStaticCallWithoutArguments() { var text = @" class Program { static ref int M() { return ref M(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.M()"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceCallWithoutArguments() { var text = @" class Program { ref int M() { return ref M(); } ref int M1() { return ref new Program().M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.M()"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceCallWithoutArguments() { var text = @" struct Program { public ref int M() { return ref M(); } } struct Program2 { Program program; ref int M() { return ref program.M(); } } class Program3 { Program program; ref int M() { return ref program.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithoutArguments() { var text = @" interface I { ref int M(); } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.M(); } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.M(); } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); } [Fact] public void RefReturnStaticCallWithArguments() { var text = @" class Program { static ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""ref int Program.M(ref int, ref int, object)"" IL_0008: ret }"); } [Fact] public void RefReturnClassInstanceCallWithArguments() { var text = @" class Program { ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } ref int M1(ref int i, ref int j, object o) { return ref new Program().M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program.M1(ref int, ref int, object)", @" { // Code size 14 (0xe) .maxstack 4 IL_0000: newobj ""Program..ctor()"" IL_0005: ldarg.1 IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: call ""ref int Program.M(ref int, ref int, object)"" IL_000d: ret }"); } [Fact] public void RefReturnStructInstanceCallWithArguments() { var text = @" struct Program { public ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } struct Program2 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } class Program3 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program2.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); compilation.VerifyIL("Program3.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithArguments() { var text = @" interface I { ref int M(ref int i, ref int j, object o); } class Program<T> where T : I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program2<T> where T : class, I { ref int M(T t, ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program3<T> where T : struct, I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); compilation.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @" { // Code size 16 (0x10) .maxstack 4 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: ldarg.s V_4 IL_000a: callvirt ""ref int I.M(ref int, ref int, object)"" IL_000f: ret }"); compilation.VerifyIL("Program3<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); } [Fact] public void RefReturnDelegateInvocationWithNoArguments() { var text = @" delegate ref int D(); class Program { static ref int M(D d) { return ref d(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""ref int D.Invoke()"" IL_0006: ret }"); } [Fact] public void RefReturnDelegateInvocationWithArguments() { var text = @" delegate ref int D(ref int i, ref int j, object o); class Program { static ref int M(D d, ref int i, ref int j, object o) { return ref d(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D, ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: callvirt ""ref int D.Invoke(ref int, ref int, object)"" IL_0009: ret }"); } [Fact] public void RefReturnsAreVariables() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(out int i) { i = 0; } static unsafe void Main() { var program = new Program(); program.P = 0; program.P += 1; program.P++; program.M(ref program.P); program.N(out program.P); fixed (int* i = &program.P) { } var tr = __makeref(program.P); program[0] = 0; program[0] += 1; program[0]++; program.M(ref program[0]); program.N(out program[0]); fixed (int* i = &program[0]) { } tr = __makeref(program[0]); program.M(ref program.field) = 0; program.M(ref program.field) += 1; program.M(ref program.field)++; program.M(ref program.M(ref program.field)); program.N(out program.M(ref program.field)); fixed (int* i = &program.M(ref program.field)) { } tr = __makeref(program.M(ref program.field)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 291 (0x123) .maxstack 4 .locals init (pinned int& V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: callvirt ""ref int Program.P.get"" IL_000b: ldc.i4.0 IL_000c: stind.i4 IL_000d: dup IL_000e: callvirt ""ref int Program.P.get"" IL_0013: dup IL_0014: ldind.i4 IL_0015: ldc.i4.1 IL_0016: add IL_0017: stind.i4 IL_0018: dup IL_0019: callvirt ""ref int Program.P.get"" IL_001e: dup IL_001f: ldind.i4 IL_0020: ldc.i4.1 IL_0021: add IL_0022: stind.i4 IL_0023: dup IL_0024: dup IL_0025: callvirt ""ref int Program.P.get"" IL_002a: callvirt ""ref int Program.M(ref int)"" IL_002f: pop IL_0030: dup IL_0031: dup IL_0032: callvirt ""ref int Program.P.get"" IL_0037: callvirt ""void Program.N(out int)"" IL_003c: dup IL_003d: callvirt ""ref int Program.P.get"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: pop IL_0045: ldc.i4.0 IL_0046: conv.u IL_0047: stloc.0 IL_0048: dup IL_0049: callvirt ""ref int Program.P.get"" IL_004e: mkrefany ""int"" IL_0053: pop IL_0054: dup IL_0055: ldc.i4.0 IL_0056: callvirt ""ref int Program.this[int].get"" IL_005b: ldc.i4.0 IL_005c: stind.i4 IL_005d: dup IL_005e: ldc.i4.0 IL_005f: callvirt ""ref int Program.this[int].get"" IL_0064: dup IL_0065: ldind.i4 IL_0066: ldc.i4.1 IL_0067: add IL_0068: stind.i4 IL_0069: dup IL_006a: ldc.i4.0 IL_006b: callvirt ""ref int Program.this[int].get"" IL_0070: dup IL_0071: ldind.i4 IL_0072: ldc.i4.1 IL_0073: add IL_0074: stind.i4 IL_0075: dup IL_0076: dup IL_0077: ldc.i4.0 IL_0078: callvirt ""ref int Program.this[int].get"" IL_007d: callvirt ""ref int Program.M(ref int)"" IL_0082: pop IL_0083: dup IL_0084: dup IL_0085: ldc.i4.0 IL_0086: callvirt ""ref int Program.this[int].get"" IL_008b: callvirt ""void Program.N(out int)"" IL_0090: dup IL_0091: ldc.i4.0 IL_0092: callvirt ""ref int Program.this[int].get"" IL_0097: stloc.0 IL_0098: ldloc.0 IL_0099: pop IL_009a: ldc.i4.0 IL_009b: conv.u IL_009c: stloc.0 IL_009d: dup IL_009e: ldc.i4.0 IL_009f: callvirt ""ref int Program.this[int].get"" IL_00a4: mkrefany ""int"" IL_00a9: pop IL_00aa: dup IL_00ab: dup IL_00ac: ldflda ""int Program.field"" IL_00b1: callvirt ""ref int Program.M(ref int)"" IL_00b6: ldc.i4.0 IL_00b7: stind.i4 IL_00b8: dup IL_00b9: dup IL_00ba: ldflda ""int Program.field"" IL_00bf: callvirt ""ref int Program.M(ref int)"" IL_00c4: dup IL_00c5: ldind.i4 IL_00c6: ldc.i4.1 IL_00c7: add IL_00c8: stind.i4 IL_00c9: dup IL_00ca: dup IL_00cb: ldflda ""int Program.field"" IL_00d0: callvirt ""ref int Program.M(ref int)"" IL_00d5: dup IL_00d6: ldind.i4 IL_00d7: ldc.i4.1 IL_00d8: add IL_00d9: stind.i4 IL_00da: dup IL_00db: dup IL_00dc: dup IL_00dd: ldflda ""int Program.field"" IL_00e2: callvirt ""ref int Program.M(ref int)"" IL_00e7: callvirt ""ref int Program.M(ref int)"" IL_00ec: pop IL_00ed: dup IL_00ee: dup IL_00ef: dup IL_00f0: ldflda ""int Program.field"" IL_00f5: callvirt ""ref int Program.M(ref int)"" IL_00fa: callvirt ""void Program.N(out int)"" IL_00ff: dup IL_0100: dup IL_0101: ldflda ""int Program.field"" IL_0106: callvirt ""ref int Program.M(ref int)"" IL_010b: stloc.0 IL_010c: ldloc.0 IL_010d: pop IL_010e: ldc.i4.0 IL_010f: conv.u IL_0110: stloc.0 IL_0111: dup IL_0112: ldflda ""int Program.field"" IL_0117: callvirt ""ref int Program.M(ref int)"" IL_011c: mkrefany ""int"" IL_0121: pop IL_0122: ret }"); } [Fact] private void RefReturnsAreValues() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(int i) { i = 0; } static unsafe int Main() { var program = new Program(); var @int = program.P + 0; var @string = program.P.ToString(); var @long = (long)program.P; program.N(program.P); @int += program[0] + 0; @string = program[0].ToString(); @long += (long)program[0]; program.N(program[0]); @int += program.M(ref program.field) + 0; @string = program.M(ref program.field).ToString(); @long += (long)program.M(ref program.field); program.N(program.M(ref program.field)); return unchecked((int)((long)@int + @long)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 168 (0xa8) .maxstack 4 .locals init (Program V_0, //program long V_1) //long IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt ""ref int Program.P.get"" IL_000c: ldind.i4 IL_000d: ldloc.0 IL_000e: callvirt ""ref int Program.P.get"" IL_0013: call ""string int.ToString()"" IL_0018: pop IL_0019: ldloc.0 IL_001a: callvirt ""ref int Program.P.get"" IL_001f: ldind.i4 IL_0020: conv.i8 IL_0021: stloc.1 IL_0022: ldloc.0 IL_0023: ldloc.0 IL_0024: callvirt ""ref int Program.P.get"" IL_0029: ldind.i4 IL_002a: callvirt ""void Program.N(int)"" IL_002f: ldloc.0 IL_0030: ldc.i4.0 IL_0031: callvirt ""ref int Program.this[int].get"" IL_0036: ldind.i4 IL_0037: add IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: callvirt ""ref int Program.this[int].get"" IL_003f: call ""string int.ToString()"" IL_0044: pop IL_0045: ldloc.1 IL_0046: ldloc.0 IL_0047: ldc.i4.0 IL_0048: callvirt ""ref int Program.this[int].get"" IL_004d: ldind.i4 IL_004e: conv.i8 IL_004f: add IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: ldloc.0 IL_0053: ldc.i4.0 IL_0054: callvirt ""ref int Program.this[int].get"" IL_0059: ldind.i4 IL_005a: callvirt ""void Program.N(int)"" IL_005f: ldloc.0 IL_0060: ldloc.0 IL_0061: ldflda ""int Program.field"" IL_0066: callvirt ""ref int Program.M(ref int)"" IL_006b: ldind.i4 IL_006c: add IL_006d: ldloc.0 IL_006e: ldloc.0 IL_006f: ldflda ""int Program.field"" IL_0074: callvirt ""ref int Program.M(ref int)"" IL_0079: call ""string int.ToString()"" IL_007e: pop IL_007f: ldloc.1 IL_0080: ldloc.0 IL_0081: ldloc.0 IL_0082: ldflda ""int Program.field"" IL_0087: callvirt ""ref int Program.M(ref int)"" IL_008c: ldind.i4 IL_008d: conv.i8 IL_008e: add IL_008f: stloc.1 IL_0090: ldloc.0 IL_0091: ldloc.0 IL_0092: ldloc.0 IL_0093: ldflda ""int Program.field"" IL_0098: callvirt ""ref int Program.M(ref int)"" IL_009d: ldind.i4 IL_009e: callvirt ""void Program.N(int)"" IL_00a3: conv.i8 IL_00a4: ldloc.1 IL_00a5: add IL_00a6: conv.i4 IL_00a7: ret }"); } [Fact] public void RefReturnArrayAccessNested() { var text = @" class Program { static ref int M() { ref int N() { return ref (new int[1])[0]; } return ref N(); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.<M>g__N|0_0()"" IL_0005: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnArrayAccessNested1() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } static void Main() { System.Console.WriteLine(M()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 26 (0x1a) .maxstack 5 .locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 40 IL_000c: stelem.i4 IL_000d: stfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0012: ldloca.s V_0 IL_0014: call ""ref int Program.<M>g__N|0_0(ref Program.<>c__DisplayClass0_0)"" IL_0019: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|0_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|0_1", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnArrayAccessNested2() { var text = @" class Program { delegate ref int D(); static D M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return N; } static void Main() { System.Console.WriteLine(M()()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 36 (0x24) .maxstack 5 .locals init (Program.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 40 IL_0011: stelem.i4 IL_0012: stfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0017: ldloc.0 IL_0018: ldftn ""ref int Program.<>c__DisplayClass1_0.<M>g__N|0()"" IL_001e: newobj ""Program.D..ctor(object, System.IntPtr)"" IL_0023: ret }").VerifyIL("Program.<>c__DisplayClass1_0.<M>g__N|0()", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|1_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|1_1(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnConditionalAccess01() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable() { return ref inst; } public void Test() { GetDisposable().Dispose(); System.Console.Write(inst.ToString()); GetDisposable()?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12") .VerifyIL("Program.C1<T>.Test()", @" { // Code size 114 (0x72) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: call ""ref T Program.C1<T>.GetDisposable()"" IL_0006: constrained. ""T"" IL_000c: callvirt ""void System.IDisposable.Dispose()"" IL_0011: ldarg.0 IL_0012: ldflda ""T Program.C1<T>.inst"" IL_0017: constrained. ""T"" IL_001d: callvirt ""string object.ToString()"" IL_0022: call ""void System.Console.Write(string)"" IL_0027: ldarg.0 IL_0028: call ""ref T Program.C1<T>.GetDisposable()"" IL_002d: ldloca.s V_0 IL_002f: initobj ""T"" IL_0035: ldloc.0 IL_0036: box ""T"" IL_003b: brtrue.s IL_0050 IL_003d: ldobj ""T"" IL_0042: stloc.0 IL_0043: ldloca.s V_0 IL_0045: ldloc.0 IL_0046: box ""T"" IL_004b: brtrue.s IL_0050 IL_004d: pop IL_004e: br.s IL_005b IL_0050: constrained. ""T"" IL_0056: callvirt ""void System.IDisposable.Dispose()"" IL_005b: ldarg.0 IL_005c: ldflda ""T Program.C1<T>.inst"" IL_0061: constrained. ""T"" IL_0067: callvirt ""string object.ToString()"" IL_006c: call ""void System.Console.Write(string)"" IL_0071: ret }"); } [Fact] public void RefReturnConditionalAccess02() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 115 (0x73) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: dup IL_000d: constrained. ""T"" IL_0013: callvirt ""void System.IDisposable.Dispose()"" IL_0018: ldarg.0 IL_0019: ldflda ""T Program.C1<T>.inst"" IL_001e: constrained. ""T"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.Write(string)"" IL_002e: ldloca.s V_0 IL_0030: initobj ""T"" IL_0036: ldloc.0 IL_0037: box ""T"" IL_003c: brtrue.s IL_0051 IL_003e: ldobj ""T"" IL_0043: stloc.0 IL_0044: ldloca.s V_0 IL_0046: ldloc.0 IL_0047: box ""T"" IL_004c: brtrue.s IL_0051 IL_004e: pop IL_004f: br.s IL_005c IL_0051: constrained. ""T"" IL_0057: callvirt ""void System.IDisposable.Dispose()"" IL_005c: ldarg.0 IL_005d: ldflda ""T Program.C1<T>.inst"" IL_0062: constrained. ""T"" IL_0068: callvirt ""string object.ToString()"" IL_006d: call ""void System.Console.Write(string)"" IL_0072: ret }"); } [Fact] public void RefReturnConditionalAccess03() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "1234", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 129 (0x81) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br.s IL_007c IL_0011: ldloc.0 IL_0012: constrained. ""T"" IL_0018: callvirt ""void System.IDisposable.Dispose()"" IL_001d: ldarg.0 IL_001e: ldflda ""T Program.C1<T>.inst"" IL_0023: constrained. ""T"" IL_0029: callvirt ""string object.ToString()"" IL_002e: call ""void System.Console.Write(string)"" IL_0033: ldloc.0 IL_0034: ldloca.s V_2 IL_0036: initobj ""T"" IL_003c: ldloc.2 IL_003d: box ""T"" IL_0042: brtrue.s IL_0057 IL_0044: ldobj ""T"" IL_0049: stloc.2 IL_004a: ldloca.s V_2 IL_004c: ldloc.2 IL_004d: box ""T"" IL_0052: brtrue.s IL_0057 IL_0054: pop IL_0055: br.s IL_0062 IL_0057: constrained. ""T"" IL_005d: callvirt ""void System.IDisposable.Dispose()"" IL_0062: ldarg.0 IL_0063: ldflda ""T Program.C1<T>.inst"" IL_0068: constrained. ""T"" IL_006e: callvirt ""string object.ToString()"" IL_0073: call ""void System.Console.Write(string)"" IL_0078: ldloc.1 IL_0079: ldc.i4.1 IL_007a: add IL_007b: stloc.1 IL_007c: ldloc.1 IL_007d: ldc.i4.2 IL_007e: blt.s IL_0011 IL_0080: ret }"); } [Fact] public void RefReturnConditionalAccess04() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { GetDisposable(ref inst)?.Blah(ref inst); System.Console.Write(inst == null); } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1True", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 84 (0x54) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: ldloca.s V_0 IL_000e: initobj ""T"" IL_0014: ldloc.0 IL_0015: box ""T"" IL_001a: brtrue.s IL_002f IL_001c: ldobj ""T"" IL_0021: stloc.0 IL_0022: ldloca.s V_0 IL_0024: ldloc.0 IL_0025: box ""T"" IL_002a: brtrue.s IL_002f IL_002c: pop IL_002d: br.s IL_0040 IL_002f: ldarg.0 IL_0030: ldflda ""T Program.C1<T>.inst"" IL_0035: constrained. ""T"" IL_003b: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0040: ldarg.0 IL_0041: ldfld ""T Program.C1<T>.inst"" IL_0046: box ""T"" IL_004b: ldnull IL_004c: ceq IL_004e: call ""void System.Console.Write(bool)"" IL_0053: ret }"); } [Fact] public void RefReturnConditionalAccess05() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); inst = new T(); temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); } } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1TrueTrue1TrueTrueTrueTrue1TrueTrue", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 215 (0xd7) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br IL_00cf IL_0014: ldloc.0 IL_0015: ldloca.s V_2 IL_0017: initobj ""T"" IL_001d: ldloc.2 IL_001e: box ""T"" IL_0023: brtrue.s IL_0038 IL_0025: ldobj ""T"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: ldloc.2 IL_002e: box ""T"" IL_0033: brtrue.s IL_0038 IL_0035: pop IL_0036: br.s IL_0044 IL_0038: ldloc.0 IL_0039: constrained. ""T"" IL_003f: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0044: ldloc.0 IL_0045: ldobj ""T"" IL_004a: box ""T"" IL_004f: ldnull IL_0050: ceq IL_0052: call ""void System.Console.Write(bool)"" IL_0057: ldarg.0 IL_0058: ldfld ""T Program.C1<T>.inst"" IL_005d: box ""T"" IL_0062: ldnull IL_0063: ceq IL_0065: call ""void System.Console.Write(bool)"" IL_006a: ldarg.0 IL_006b: call ""T System.Activator.CreateInstance<T>()"" IL_0070: stfld ""T Program.C1<T>.inst"" IL_0075: ldloc.0 IL_0076: ldloca.s V_2 IL_0078: initobj ""T"" IL_007e: ldloc.2 IL_007f: box ""T"" IL_0084: brtrue.s IL_0099 IL_0086: ldobj ""T"" IL_008b: stloc.2 IL_008c: ldloca.s V_2 IL_008e: ldloc.2 IL_008f: box ""T"" IL_0094: brtrue.s IL_0099 IL_0096: pop IL_0097: br.s IL_00a5 IL_0099: ldloc.0 IL_009a: constrained. ""T"" IL_00a0: callvirt ""void IGoo<T>.Blah(ref T)"" IL_00a5: ldloc.0 IL_00a6: ldobj ""T"" IL_00ab: box ""T"" IL_00b0: ldnull IL_00b1: ceq IL_00b3: call ""void System.Console.Write(bool)"" IL_00b8: ldarg.0 IL_00b9: ldfld ""T Program.C1<T>.inst"" IL_00be: box ""T"" IL_00c3: ldnull IL_00c4: ceq IL_00c6: call ""void System.Console.Write(bool)"" IL_00cb: ldloc.1 IL_00cc: ldc.i4.1 IL_00cd: add IL_00ce: stloc.1 IL_00cf: ldloc.1 IL_00d0: ldc.i4.2 IL_00d1: blt IL_0014 IL_00d6: ret }"); } [Fact] public void RefReturn_CSharp6() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (6,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 16) ); } [Fact] public void RefInLambda_CSharp6() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (8,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(8, 9), // (8,17): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "N").WithArguments("local functions", "7.0").WithLocation(8, 17), // (10,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 13), // (10,21): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NN").WithArguments("local functions", "7.0").WithLocation(10, 21), // (10,40): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 40), // (12,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 13), // (12,25): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 25), // (15,20): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref r; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(15, 20), // (18,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref N(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(18, 16) ); } [Fact] public void RefDelegate_CSharp6() { var text = @" delegate ref int D(); "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10) ); } [Fact] public void RefInForStatement_CSharp6() { var text = @" class Program { static int M(ref int d) { for (ref int a = ref d; ;) { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (6,14): error CS8059: Feature 'ref for-loop variables' is not available in C# 6. Please use language version 7.3 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("ref for-loop variables", "7.3").WithLocation(6, 14), // (6,14): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 14), // (6,26): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 26) ); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(int x); class C { static void MD(D d) { } static int i = 0; static void M() { MD((x) => ref i); MD(x => ref i); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(int x); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10), // (11,19): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD((x) => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(11, 19), // (12,17): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD(x => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 17) ); } [Fact] public void Override_Metadata() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& A::get_P() } } .class public abstract B1 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object get_P() { ldnull throw } .property instance object P() { .get instance object B1::get_P() } } .class public abstract B2 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object& F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& B2::get_P() } }"; var ref1 = CompileIL(ilSource); var compilation = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { ref1 }); var method = compilation.GetMember<MethodSymbol>("B1.F"); Assert.Equal("System.Object B1.F()", method.ToTestDisplayString()); Assert.Equal("System.Object A.F()", method.OverriddenMethod.ToTestDisplayString()); var property = compilation.GetMember<PropertySymbol>("B1.P"); Assert.Equal("System.Object B1.P { get; }", property.ToTestDisplayString()); Assert.Null(property.OverriddenProperty); method = compilation.GetMember<MethodSymbol>("B2.F"); Assert.Equal("ref System.Object B2.F()", method.ToTestDisplayString()); Assert.Null(method.OverriddenMethod); property = compilation.GetMember<PropertySymbol>("B2.P"); Assert.Equal("ref System.Object B2.P { get; }", property.ToTestDisplayString()); Assert.Equal("ref System.Object A.P { get; }", property.OverriddenProperty.ToTestDisplayString()); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefReturnFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { return ref _f; } private T _p; public ref T P { get { return ref _p; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefAssignFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { ref var r = ref _f; return ref r; } private T _p; public ref T P { get { ref var r = ref _p; return ref r; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [Fact] public void ThrowRefReturn() { var text = @"using System; class Program { static ref int P1 { get => throw new E(1); } static ref int P2 => throw new E(2); static ref int M() => throw new E(3); public static void Main() { ref int L() => throw new E(4); D d = () => throw new E(5); try { ref int x = ref P1; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref P2; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref M(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref L(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref d(); } catch (E e) { Console.Write(e.Value); } } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; var v = CompileAndVerify(text, expectedOutput: "12345"); } [Fact] public void NoRefThrow() { var text = @"using System; class Program { static ref int P1 { get => ref throw new E(1); } static ref int P2 => ref throw new E(2); static ref int M() => ref throw new E(3); public static void Main() { ref int L() => ref throw new E(4); D d = () => ref throw new E(5); L(); d(); } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,36): error CS8115: A throw expression is not allowed in this context. // static ref int P1 { get => ref throw new E(1); } Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(4, 36), // (5,30): error CS8115: A throw expression is not allowed in this context. // static ref int P2 => ref throw new E(2); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(5, 30), // (6,31): error CS8115: A throw expression is not allowed in this context. // static ref int M() => ref throw new E(3); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 31), // (10,28): error CS8115: A throw expression is not allowed in this context. // ref int L() => ref throw new E(4); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(10, 28), // (11,25): error CS8115: A throw expression is not allowed in this context. // D d = () => ref throw new E(5); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 25) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,19): error CS8150: By-value returns may only be used in methods that return by value // B.F(() => o.F(), 2); Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "o.F()").WithLocation(24, 19) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_02() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "2"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_03() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,23): error CS8149: By-reference returns may only be used in methods that return by reference // B.F(() => ref o.F(), 2); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "o.F()").WithLocation(24, 23) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "23"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_02() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); CreateCompilation(source).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_03() { var source = @"public delegate ref T D<T>(); public class A<T> { private T _t = default(T); public T F() { return _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); CreateCompilation(source).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d.Length); // this is an error return ref d.Length; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (18,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d.Length; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(18, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001a() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref F1(ref d.Length); d = ""qwerty""; ref var temp2 = ref F1(ref d.Length); return temp1; } public static ref dynamic F1(ref dynamic d) { return ref d; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); v.VerifyIL("C.F(ref dynamic)", @" { // Code size 180 (0xb4) .maxstack 8 .locals init (object& V_0, //temp1 object V_1, object V_2) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""Length"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0045: ldarg.0 IL_0046: ldind.ref IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: stloc.1 IL_004d: ldloca.s V_1 IL_004f: call ""ref dynamic C.F1(ref dynamic)"" IL_0054: stloc.0 IL_0055: ldarg.0 IL_0056: ldstr ""qwerty"" IL_005b: stind.ref IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0061: brtrue.s IL_0092 IL_0063: ldc.i4.0 IL_0064: ldstr ""Length"" IL_0069: ldtoken ""C"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.1 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.0 IL_007c: ldnull IL_007d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0082: stelem.ref IL_0083: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0088: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0092: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0097: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_009c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a1: ldarg.0 IL_00a2: ldind.ref IL_00a3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a8: stloc.2 IL_00a9: ldloca.s V_2 IL_00ab: call ""ref dynamic C.F1(ref dynamic)"" IL_00b0: pop IL_00b1: ldloc.0 IL_00b2: ldind.ref IL_00b3: ret }"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001b() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); d = ""qwerty""; ref var temp2 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); return temp1; } public static ref dynamic F1(in int arg1, ref dynamic d, in int arg2) { if (arg1 == arg2) throw null; return ref d; } public static ref dynamic Test(ref dynamic arg1, ref dynamic arg2) { return ref arg2; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic002() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d[0]); return ref d[0]; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d[0]; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d[0]").WithLocation(17, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic003() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { return ref G(ref d.Length); } public static ref dynamic G(ref dynamic d) { return ref d; } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (14,26): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(14, 26), // (14,20): error CS8347: Cannot use a result of 'C.G(ref dynamic)' in this context because it may expose variables referenced by parameter 'd' outside of their declaration scope // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_EscapeCall, "G(ref d.Length)").WithArguments("C.G(ref dynamic)", "d").WithLocation(14, 20) ); } [Fact] public void RefReturnVarianceDelegate() { var source = @" using System; delegate ref T RefFunc1<T>(); delegate ref T RefFunc2<in T>(); delegate ref T RefFunc3<out T>(); delegate ref Action<T> RefFunc1a<T>(); delegate ref Action<T> RefFunc2a<in T>(); delegate ref Action<T> RefFunc3a<out T>(); delegate ref Func<T> RefFunc1f<T>(); delegate ref Func<T> RefFunc2f<in T>(); delegate ref Func<T> RefFunc3f<out T>(); "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3<T>.Invoke()'. 'T' is covariant. // delegate ref T RefFunc3<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc3<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(6, 10), // (5,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2<T>.Invoke()'. 'T' is contravariant. // delegate ref T RefFunc2<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc2<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(5, 10), // (14,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3f<T>.Invoke()'. 'T' is covariant. // delegate ref Func<T> RefFunc3f<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc3f<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(14, 10), // (13,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2f<T>.Invoke()'. 'T' is contravariant. // delegate ref Func<T> RefFunc2f<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc2f<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(13, 10), // (10,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3a<T>.Invoke()'. 'T' is covariant. // delegate ref Action<T> RefFunc3a<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc3a<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(10, 10), // (9,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2a<T>.Invoke()'. 'T' is contravariant. // delegate ref Action<T> RefFunc2a<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc2a<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(9, 10) ); } [Fact] public void RefReturnVarianceMethod() { var source = @" using System; interface IM1<T> { ref T RefMethod(); } interface IM2<in T> { ref T RefMethod(); } interface IM3<out T> { ref T RefMethod(); } interface IM1a<T> { ref Action<T> RefMethod(); } interface IM2a<in T> { ref Action<T> RefMethod(); } interface IM3a<out T> { ref Action<T> RefMethod(); } interface IM1f<T> { ref Func<T> RefMethod(); } interface IM2f<in T> { ref Func<T> RefMethod(); } interface IM3f<out T> { ref Func<T> RefMethod(); } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3<T>.RefMethod()'. 'T' is covariant. // interface IM3<out T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM3<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(6, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3a<T>.RefMethod()'. 'T' is covariant. // interface IM3a<out T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM3a<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(10, 25), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2a<T>.RefMethod()'. 'T' is contravariant. // interface IM2a<in T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM2a<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(9, 24), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2f<T>.RefMethod()'. 'T' is contravariant. // interface IM2f<in T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM2f<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3f<T>.RefMethod()'. 'T' is covariant. // interface IM3f<out T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM3f<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(14, 25), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2<T>.RefMethod()'. 'T' is contravariant. // interface IM2<in T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM2<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(5, 23) ); } [Fact] public void RefReturnVarianceProperty() { var source = @" using System; interface IP1<T> { ref T RefProp{get;} } interface IP2<in T> { ref T RefProp{get;} } interface IP3<out T> { ref T RefProp{get;} } interface IP1a<T> { ref Action<T> RefProp{get;} } interface IP2a<in T> { ref Action<T> RefProp{get;} } interface IP3a<out T> { ref Action<T> RefProp{get;} } interface IP1f<T> { ref Func<T> RefProp{get;} } interface IP2f<in T> { ref Func<T> RefProp{get;} } interface IP3f<out T> { ref Func<T> RefProp{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.RefProp'. 'T' is contravariant. // interface IP2<in T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(5, 23), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.RefProp'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(13, 24), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.RefProp'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.RefProp'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.RefProp", "T", "covariant", "invariantly").WithLocation(10, 25), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.RefProp'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.RefProp", "T", "covariant", "invariantly").WithLocation(14, 25), // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.RefProp'. 'T' is covariant. // interface IP3<out T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.RefProp", "T", "covariant", "invariantly").WithLocation(6, 24) ); } [Fact] public void RefReturnVarianceIndexer() { var source = @" using System; interface IP1<T> { ref T this[int i]{get;} } interface IP2<in T> { ref T this[int i]{get;} } interface IP3<out T> { ref T this[int i]{get;} } interface IP1a<T> { ref Action<T> this[int i]{get;} } interface IP2a<in T> { ref Action<T> this[int i]{get;} } interface IP3a<out T> { ref Action<T> this[int i]{get;} } interface IP1f<T> { ref Func<T> this[int i]{get;} } interface IP2f<in T> { ref Func<T> this[int i]{get;} } interface IP3f<out T> { ref Func<T> this[int i]{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.this[int]'. 'T' is covariant. // interface IP3<out T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.this[int]", "T", "covariant", "invariantly").WithLocation(6, 24), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.this[int]'. 'T' is contravariant. // interface IP2<in T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(5, 23), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.this[int]'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.this[int]'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.this[int]", "T", "covariant", "invariantly").WithLocation(10, 25), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.this[int]'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.this[int]'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.this[int]", "T", "covariant", "invariantly").WithLocation(14, 25) ); } [Fact] public void RefMethodGroupConversionError() { var source = @" using System; class Program { delegate ref T RefFunc1<T>(); static void Main() { RefFunc1<object> f = M1; f() = 1; f = new RefFunc1<object>(M1); f() = 1; } static ref string M1() => ref new string[]{""qq""}[0]; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string"), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(10, 30), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); } [Fact] public void RefMethodGroupConversionError_WithResolution() { var source = @" class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => ref Base.Instance; static ref Derived1 M1(Derived1 arg) => ref Derived1.Instance; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (22,38): error CS0407: 'Derived1 Program.M1(Derived1)' has the wrong return type // RefFunc1<Derived2, Base> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1(Derived1)", "Derived1").WithLocation(22, 38) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupConversionNoError_WithResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1 : Base { public static new Derived1 Instance = new Derived1(); } class Derived2 : Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => throw null; static ref Base M1(Derived1 arg) => ref Base.Instance; } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Base", verify: Verification.Passes); } [Fact] public void RefMethodGroupOverloadResolutionErr() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M1); Test(M3); } static ref Base M1(Derived1 arg) => ref Base.Instance; static ref Base M3(Derived2 arg) => ref Base.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (25,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M1); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(25, 9), // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M3); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(26, 9) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M2); } static ref Derived1 M2(Base arg) => ref Derived1.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Program+RefFunc1`2[Derived2,Derived1]", verify: Verification.Passes); } [Fact] public void RefLambdaOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test((t)=> Base.Instance); Test((t)=> ref Base.Instance); } static void Test(RefFunc1<Derived1, Base> arg) => Console.WriteLine(arg); static void Test(Func<Derived1, Base> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"System.Func`2[Derived1,Base] Program+RefFunc1`2[Derived1,Base]", verify: Verification.Passes); } [WorkItem(25024, "https://github.com/dotnet/roslyn/issues/25024")] [Fact] public void RefReturnDiscardLifetime() { var text = @" class Program { static bool flag = true; public static void Main() { if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 1; local2 = 2; System.Console.Write(local1 + local2); } if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 3; local2 = 4; System.Console.Write(local1 + local2); } } public static ref int M1(out int arg) { arg = 123; return ref arg; } } "; CompileAndVerifyRef(text, expectedOutput: "37", verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 75 (0x4b) .maxstack 3 .locals init (int& V_0, //local2 int V_1, int V_2, int& V_3, //local2 int V_4, int V_5) IL_0000: ldsfld ""bool Program.flag"" IL_0005: brfalse.s IL_0025 IL_0007: ldloca.s V_1 IL_0009: call ""ref int Program.M1(out int)"" IL_000e: ldloca.s V_2 IL_0010: call ""ref int Program.M1(out int)"" IL_0015: stloc.0 IL_0016: dup IL_0017: ldc.i4.1 IL_0018: stind.i4 IL_0019: ldloc.0 IL_001a: ldc.i4.2 IL_001b: stind.i4 IL_001c: ldind.i4 IL_001d: ldloc.0 IL_001e: ldind.i4 IL_001f: add IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldsfld ""bool Program.flag"" IL_002a: brfalse.s IL_004a IL_002c: ldloca.s V_4 IL_002e: call ""ref int Program.M1(out int)"" IL_0033: ldloca.s V_5 IL_0035: call ""ref int Program.M1(out int)"" IL_003a: stloc.3 IL_003b: dup IL_003c: ldc.i4.3 IL_003d: stind.i4 IL_003e: ldloc.3 IL_003f: ldc.i4.4 IL_0040: stind.i4 IL_0041: ldind.i4 IL_0042: ldloc.3 IL_0043: ldind.i4 IL_0044: add IL_0045: call ""void System.Console.Write(int)"" IL_004a: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RefReturnTests : CompilingTestBase { private CompilationVerifier CompileAndVerifyRef( string source, string expectedOutput = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes) { return CompileAndVerify( source, expectedOutput: expectedOutput, options: options, verify: verify); } [Fact] public void RefReturnRefAssignment() { CompileAndVerify(@" using System; class C { static readonly int _ro = 42; static int _rw = 42; static void Main() { Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; M1(ref _rw)++; Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; } static ref int M1(ref int rrw) => ref (rrw = ref _rw); static ref readonly int M2(in int rro) => ref (rro = ref _ro); static ref readonly int M3(in int rro) => ref (rro = ref _rw); }", verify: Verification.Fails, expectedOutput: @"42 42 42 43 42 43"); } [Fact] public void RefReturnArrayAccess() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnRefParameter() { var text = @" class Program { static ref int M(ref int i) { return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Skipped).VerifyIL("Program.M(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnOutParameter() { var text = @" class Program { static ref int M(out int i) { i = 0; return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(out int)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: stind.i4 IL_0003: ldarg.0 IL_0004: ret }"); } [Fact] public void RefReturnRefLocal() { var text = @" class Program { static ref int M(ref int i) { ref int local = ref i; local = 0; return ref local; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(ref int)", @" { // Code size 5 (0x5) .maxstack 3 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldc.i4.0 IL_0003: stind.i4 IL_0004: ret }"); } [Fact] public void RefReturnStaticProperty() { var text = @" class Program { static int field = 0; static ref int P { get { return ref field; } } static ref int M() { return ref P; } public static void Main() { var local = 42; // must be real local P = local; P = local; // assign again, should not use stack local System.Console.WriteLine(P); } } "; var v = CompileAndVerifyRef(text, expectedOutput: "42"); v.VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.P.get"" IL_0005: ret }"); v.VerifyIL("Program.Main()", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (int V_0) //local IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: call ""ref int Program.P.get"" IL_0008: ldloc.0 IL_0009: stind.i4 IL_000a: call ""ref int Program.P.get"" IL_000f: ldloc.0 IL_0010: stind.i4 IL_0011: call ""ref int Program.P.get"" IL_0016: ldind.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: ret }"); } [Fact] public void RefReturnClassInstanceProperty() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int M() { return ref P; } ref int M1() { return ref new Program().P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.P.get"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceProperty() { var text = @" struct Program { public ref int P { get { return ref (new int[1])[0]; } } ref int M() { return ref P; } ref int M1(ref Program program) { return ref program.P; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program.P; } } class Program3 { Program program = default(Program); ref int M() { return ref program.P; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceProperty() { var text = @" interface I { ref int P { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.P; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.P; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); } [Fact] public void RefReturnClassInstanceIndexer() { var text = @" class Program { int field = 0; ref int this[int i] { get { return ref field; } } ref int M() { return ref this[0]; } ref int M1() { return ref new Program()[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: ldc.i4.0 IL_0006: call ""ref int Program.this[int].get"" IL_000b: ret }"); } [Fact] public void RefReturnStructInstanceIndexer() { var text = @" struct Program { public ref int this[int i] { get { return ref (new int[1])[0]; } } ref int M() { return ref this[0]; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program[0]; } } class Program3 { Program program = default(Program); ref int M() { return ref program[0]; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); } [Fact] public void RefReturnConstrainedInstanceIndexer() { var text = @" interface I { ref int this[int i] { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t[0]; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t[0]; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldc.i4.0 IL_0007: callvirt ""ref int I.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); } [Fact] public void RefReturnStaticFieldLikeEvent() { var text = @" delegate void D(); class Program { static event D d; static ref D M() { return ref d; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""D Program.d"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceFieldLikeEvent() { var text = @" delegate void D(); class Program { event D d; ref D M() { return ref d; } ref D M1() { return ref new Program().d; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""D Program.d"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""D Program.d"" IL_000a: ret }"); } [Fact] public void RefReturnStaticField() { var text = @" class Program { static int i = 0; static ref int M() { return ref i; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""int Program.i"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceField() { var text = @" class Program { int i = 0; ref int M() { return ref i; } ref int M1() { return ref new Program().i; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""int Program.i"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceField() { var text = @" struct Program { public int i; } class Program2 { Program program = default(Program); ref int M(ref Program program) { return ref program.i; } ref int M() { return ref program.i; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Fails); compilation.VerifyIL("Program2.M(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldflda ""int Program.i"" IL_000b: ret }"); } [Fact] public void RefReturnStaticCallWithoutArguments() { var text = @" class Program { static ref int M() { return ref M(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.M()"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceCallWithoutArguments() { var text = @" class Program { ref int M() { return ref M(); } ref int M1() { return ref new Program().M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.M()"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceCallWithoutArguments() { var text = @" struct Program { public ref int M() { return ref M(); } } struct Program2 { Program program; ref int M() { return ref program.M(); } } class Program3 { Program program; ref int M() { return ref program.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithoutArguments() { var text = @" interface I { ref int M(); } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.M(); } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.M(); } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); } [Fact] public void RefReturnStaticCallWithArguments() { var text = @" class Program { static ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""ref int Program.M(ref int, ref int, object)"" IL_0008: ret }"); } [Fact] public void RefReturnClassInstanceCallWithArguments() { var text = @" class Program { ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } ref int M1(ref int i, ref int j, object o) { return ref new Program().M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program.M1(ref int, ref int, object)", @" { // Code size 14 (0xe) .maxstack 4 IL_0000: newobj ""Program..ctor()"" IL_0005: ldarg.1 IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: call ""ref int Program.M(ref int, ref int, object)"" IL_000d: ret }"); } [Fact] public void RefReturnStructInstanceCallWithArguments() { var text = @" struct Program { public ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } struct Program2 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } class Program3 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program2.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); compilation.VerifyIL("Program3.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithArguments() { var text = @" interface I { ref int M(ref int i, ref int j, object o); } class Program<T> where T : I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program2<T> where T : class, I { ref int M(T t, ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program3<T> where T : struct, I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); compilation.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @" { // Code size 16 (0x10) .maxstack 4 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: ldarg.s V_4 IL_000a: callvirt ""ref int I.M(ref int, ref int, object)"" IL_000f: ret }"); compilation.VerifyIL("Program3<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); } [Fact] public void RefReturnDelegateInvocationWithNoArguments() { var text = @" delegate ref int D(); class Program { static ref int M(D d) { return ref d(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""ref int D.Invoke()"" IL_0006: ret }"); } [Fact] public void RefReturnDelegateInvocationWithArguments() { var text = @" delegate ref int D(ref int i, ref int j, object o); class Program { static ref int M(D d, ref int i, ref int j, object o) { return ref d(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D, ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: callvirt ""ref int D.Invoke(ref int, ref int, object)"" IL_0009: ret }"); } [Fact] public void RefReturnsAreVariables() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(out int i) { i = 0; } static unsafe void Main() { var program = new Program(); program.P = 0; program.P += 1; program.P++; program.M(ref program.P); program.N(out program.P); fixed (int* i = &program.P) { } var tr = __makeref(program.P); program[0] = 0; program[0] += 1; program[0]++; program.M(ref program[0]); program.N(out program[0]); fixed (int* i = &program[0]) { } tr = __makeref(program[0]); program.M(ref program.field) = 0; program.M(ref program.field) += 1; program.M(ref program.field)++; program.M(ref program.M(ref program.field)); program.N(out program.M(ref program.field)); fixed (int* i = &program.M(ref program.field)) { } tr = __makeref(program.M(ref program.field)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 291 (0x123) .maxstack 4 .locals init (pinned int& V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: callvirt ""ref int Program.P.get"" IL_000b: ldc.i4.0 IL_000c: stind.i4 IL_000d: dup IL_000e: callvirt ""ref int Program.P.get"" IL_0013: dup IL_0014: ldind.i4 IL_0015: ldc.i4.1 IL_0016: add IL_0017: stind.i4 IL_0018: dup IL_0019: callvirt ""ref int Program.P.get"" IL_001e: dup IL_001f: ldind.i4 IL_0020: ldc.i4.1 IL_0021: add IL_0022: stind.i4 IL_0023: dup IL_0024: dup IL_0025: callvirt ""ref int Program.P.get"" IL_002a: callvirt ""ref int Program.M(ref int)"" IL_002f: pop IL_0030: dup IL_0031: dup IL_0032: callvirt ""ref int Program.P.get"" IL_0037: callvirt ""void Program.N(out int)"" IL_003c: dup IL_003d: callvirt ""ref int Program.P.get"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: pop IL_0045: ldc.i4.0 IL_0046: conv.u IL_0047: stloc.0 IL_0048: dup IL_0049: callvirt ""ref int Program.P.get"" IL_004e: mkrefany ""int"" IL_0053: pop IL_0054: dup IL_0055: ldc.i4.0 IL_0056: callvirt ""ref int Program.this[int].get"" IL_005b: ldc.i4.0 IL_005c: stind.i4 IL_005d: dup IL_005e: ldc.i4.0 IL_005f: callvirt ""ref int Program.this[int].get"" IL_0064: dup IL_0065: ldind.i4 IL_0066: ldc.i4.1 IL_0067: add IL_0068: stind.i4 IL_0069: dup IL_006a: ldc.i4.0 IL_006b: callvirt ""ref int Program.this[int].get"" IL_0070: dup IL_0071: ldind.i4 IL_0072: ldc.i4.1 IL_0073: add IL_0074: stind.i4 IL_0075: dup IL_0076: dup IL_0077: ldc.i4.0 IL_0078: callvirt ""ref int Program.this[int].get"" IL_007d: callvirt ""ref int Program.M(ref int)"" IL_0082: pop IL_0083: dup IL_0084: dup IL_0085: ldc.i4.0 IL_0086: callvirt ""ref int Program.this[int].get"" IL_008b: callvirt ""void Program.N(out int)"" IL_0090: dup IL_0091: ldc.i4.0 IL_0092: callvirt ""ref int Program.this[int].get"" IL_0097: stloc.0 IL_0098: ldloc.0 IL_0099: pop IL_009a: ldc.i4.0 IL_009b: conv.u IL_009c: stloc.0 IL_009d: dup IL_009e: ldc.i4.0 IL_009f: callvirt ""ref int Program.this[int].get"" IL_00a4: mkrefany ""int"" IL_00a9: pop IL_00aa: dup IL_00ab: dup IL_00ac: ldflda ""int Program.field"" IL_00b1: callvirt ""ref int Program.M(ref int)"" IL_00b6: ldc.i4.0 IL_00b7: stind.i4 IL_00b8: dup IL_00b9: dup IL_00ba: ldflda ""int Program.field"" IL_00bf: callvirt ""ref int Program.M(ref int)"" IL_00c4: dup IL_00c5: ldind.i4 IL_00c6: ldc.i4.1 IL_00c7: add IL_00c8: stind.i4 IL_00c9: dup IL_00ca: dup IL_00cb: ldflda ""int Program.field"" IL_00d0: callvirt ""ref int Program.M(ref int)"" IL_00d5: dup IL_00d6: ldind.i4 IL_00d7: ldc.i4.1 IL_00d8: add IL_00d9: stind.i4 IL_00da: dup IL_00db: dup IL_00dc: dup IL_00dd: ldflda ""int Program.field"" IL_00e2: callvirt ""ref int Program.M(ref int)"" IL_00e7: callvirt ""ref int Program.M(ref int)"" IL_00ec: pop IL_00ed: dup IL_00ee: dup IL_00ef: dup IL_00f0: ldflda ""int Program.field"" IL_00f5: callvirt ""ref int Program.M(ref int)"" IL_00fa: callvirt ""void Program.N(out int)"" IL_00ff: dup IL_0100: dup IL_0101: ldflda ""int Program.field"" IL_0106: callvirt ""ref int Program.M(ref int)"" IL_010b: stloc.0 IL_010c: ldloc.0 IL_010d: pop IL_010e: ldc.i4.0 IL_010f: conv.u IL_0110: stloc.0 IL_0111: dup IL_0112: ldflda ""int Program.field"" IL_0117: callvirt ""ref int Program.M(ref int)"" IL_011c: mkrefany ""int"" IL_0121: pop IL_0122: ret }"); } [Fact] private void RefReturnsAreValues() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(int i) { i = 0; } static unsafe int Main() { var program = new Program(); var @int = program.P + 0; var @string = program.P.ToString(); var @long = (long)program.P; program.N(program.P); @int += program[0] + 0; @string = program[0].ToString(); @long += (long)program[0]; program.N(program[0]); @int += program.M(ref program.field) + 0; @string = program.M(ref program.field).ToString(); @long += (long)program.M(ref program.field); program.N(program.M(ref program.field)); return unchecked((int)((long)@int + @long)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 168 (0xa8) .maxstack 4 .locals init (Program V_0, //program long V_1) //long IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt ""ref int Program.P.get"" IL_000c: ldind.i4 IL_000d: ldloc.0 IL_000e: callvirt ""ref int Program.P.get"" IL_0013: call ""string int.ToString()"" IL_0018: pop IL_0019: ldloc.0 IL_001a: callvirt ""ref int Program.P.get"" IL_001f: ldind.i4 IL_0020: conv.i8 IL_0021: stloc.1 IL_0022: ldloc.0 IL_0023: ldloc.0 IL_0024: callvirt ""ref int Program.P.get"" IL_0029: ldind.i4 IL_002a: callvirt ""void Program.N(int)"" IL_002f: ldloc.0 IL_0030: ldc.i4.0 IL_0031: callvirt ""ref int Program.this[int].get"" IL_0036: ldind.i4 IL_0037: add IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: callvirt ""ref int Program.this[int].get"" IL_003f: call ""string int.ToString()"" IL_0044: pop IL_0045: ldloc.1 IL_0046: ldloc.0 IL_0047: ldc.i4.0 IL_0048: callvirt ""ref int Program.this[int].get"" IL_004d: ldind.i4 IL_004e: conv.i8 IL_004f: add IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: ldloc.0 IL_0053: ldc.i4.0 IL_0054: callvirt ""ref int Program.this[int].get"" IL_0059: ldind.i4 IL_005a: callvirt ""void Program.N(int)"" IL_005f: ldloc.0 IL_0060: ldloc.0 IL_0061: ldflda ""int Program.field"" IL_0066: callvirt ""ref int Program.M(ref int)"" IL_006b: ldind.i4 IL_006c: add IL_006d: ldloc.0 IL_006e: ldloc.0 IL_006f: ldflda ""int Program.field"" IL_0074: callvirt ""ref int Program.M(ref int)"" IL_0079: call ""string int.ToString()"" IL_007e: pop IL_007f: ldloc.1 IL_0080: ldloc.0 IL_0081: ldloc.0 IL_0082: ldflda ""int Program.field"" IL_0087: callvirt ""ref int Program.M(ref int)"" IL_008c: ldind.i4 IL_008d: conv.i8 IL_008e: add IL_008f: stloc.1 IL_0090: ldloc.0 IL_0091: ldloc.0 IL_0092: ldloc.0 IL_0093: ldflda ""int Program.field"" IL_0098: callvirt ""ref int Program.M(ref int)"" IL_009d: ldind.i4 IL_009e: callvirt ""void Program.N(int)"" IL_00a3: conv.i8 IL_00a4: ldloc.1 IL_00a5: add IL_00a6: conv.i4 IL_00a7: ret }"); } [Fact] public void RefReturnArrayAccessNested() { var text = @" class Program { static ref int M() { ref int N() { return ref (new int[1])[0]; } return ref N(); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.<M>g__N|0_0()"" IL_0005: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnArrayAccessNested1() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } static void Main() { System.Console.WriteLine(M()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 26 (0x1a) .maxstack 5 .locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 40 IL_000c: stelem.i4 IL_000d: stfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0012: ldloca.s V_0 IL_0014: call ""ref int Program.<M>g__N|0_0(ref Program.<>c__DisplayClass0_0)"" IL_0019: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|0_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|0_1", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnArrayAccessNested2() { var text = @" class Program { delegate ref int D(); static D M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return N; } static void Main() { System.Console.WriteLine(M()()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 36 (0x24) .maxstack 5 .locals init (Program.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 40 IL_0011: stelem.i4 IL_0012: stfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0017: ldloc.0 IL_0018: ldftn ""ref int Program.<>c__DisplayClass1_0.<M>g__N|0()"" IL_001e: newobj ""Program.D..ctor(object, System.IntPtr)"" IL_0023: ret }").VerifyIL("Program.<>c__DisplayClass1_0.<M>g__N|0()", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|1_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|1_1(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnConditionalAccess01() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable() { return ref inst; } public void Test() { GetDisposable().Dispose(); System.Console.Write(inst.ToString()); GetDisposable()?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12") .VerifyIL("Program.C1<T>.Test()", @" { // Code size 114 (0x72) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: call ""ref T Program.C1<T>.GetDisposable()"" IL_0006: constrained. ""T"" IL_000c: callvirt ""void System.IDisposable.Dispose()"" IL_0011: ldarg.0 IL_0012: ldflda ""T Program.C1<T>.inst"" IL_0017: constrained. ""T"" IL_001d: callvirt ""string object.ToString()"" IL_0022: call ""void System.Console.Write(string)"" IL_0027: ldarg.0 IL_0028: call ""ref T Program.C1<T>.GetDisposable()"" IL_002d: ldloca.s V_0 IL_002f: initobj ""T"" IL_0035: ldloc.0 IL_0036: box ""T"" IL_003b: brtrue.s IL_0050 IL_003d: ldobj ""T"" IL_0042: stloc.0 IL_0043: ldloca.s V_0 IL_0045: ldloc.0 IL_0046: box ""T"" IL_004b: brtrue.s IL_0050 IL_004d: pop IL_004e: br.s IL_005b IL_0050: constrained. ""T"" IL_0056: callvirt ""void System.IDisposable.Dispose()"" IL_005b: ldarg.0 IL_005c: ldflda ""T Program.C1<T>.inst"" IL_0061: constrained. ""T"" IL_0067: callvirt ""string object.ToString()"" IL_006c: call ""void System.Console.Write(string)"" IL_0071: ret }"); } [Fact] public void RefReturnConditionalAccess02() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 115 (0x73) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: dup IL_000d: constrained. ""T"" IL_0013: callvirt ""void System.IDisposable.Dispose()"" IL_0018: ldarg.0 IL_0019: ldflda ""T Program.C1<T>.inst"" IL_001e: constrained. ""T"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.Write(string)"" IL_002e: ldloca.s V_0 IL_0030: initobj ""T"" IL_0036: ldloc.0 IL_0037: box ""T"" IL_003c: brtrue.s IL_0051 IL_003e: ldobj ""T"" IL_0043: stloc.0 IL_0044: ldloca.s V_0 IL_0046: ldloc.0 IL_0047: box ""T"" IL_004c: brtrue.s IL_0051 IL_004e: pop IL_004f: br.s IL_005c IL_0051: constrained. ""T"" IL_0057: callvirt ""void System.IDisposable.Dispose()"" IL_005c: ldarg.0 IL_005d: ldflda ""T Program.C1<T>.inst"" IL_0062: constrained. ""T"" IL_0068: callvirt ""string object.ToString()"" IL_006d: call ""void System.Console.Write(string)"" IL_0072: ret }"); } [Fact] public void RefReturnConditionalAccess03() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "1234", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 129 (0x81) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br.s IL_007c IL_0011: ldloc.0 IL_0012: constrained. ""T"" IL_0018: callvirt ""void System.IDisposable.Dispose()"" IL_001d: ldarg.0 IL_001e: ldflda ""T Program.C1<T>.inst"" IL_0023: constrained. ""T"" IL_0029: callvirt ""string object.ToString()"" IL_002e: call ""void System.Console.Write(string)"" IL_0033: ldloc.0 IL_0034: ldloca.s V_2 IL_0036: initobj ""T"" IL_003c: ldloc.2 IL_003d: box ""T"" IL_0042: brtrue.s IL_0057 IL_0044: ldobj ""T"" IL_0049: stloc.2 IL_004a: ldloca.s V_2 IL_004c: ldloc.2 IL_004d: box ""T"" IL_0052: brtrue.s IL_0057 IL_0054: pop IL_0055: br.s IL_0062 IL_0057: constrained. ""T"" IL_005d: callvirt ""void System.IDisposable.Dispose()"" IL_0062: ldarg.0 IL_0063: ldflda ""T Program.C1<T>.inst"" IL_0068: constrained. ""T"" IL_006e: callvirt ""string object.ToString()"" IL_0073: call ""void System.Console.Write(string)"" IL_0078: ldloc.1 IL_0079: ldc.i4.1 IL_007a: add IL_007b: stloc.1 IL_007c: ldloc.1 IL_007d: ldc.i4.2 IL_007e: blt.s IL_0011 IL_0080: ret }"); } [Fact] public void RefReturnConditionalAccess04() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { GetDisposable(ref inst)?.Blah(ref inst); System.Console.Write(inst == null); } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1True", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 84 (0x54) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: ldloca.s V_0 IL_000e: initobj ""T"" IL_0014: ldloc.0 IL_0015: box ""T"" IL_001a: brtrue.s IL_002f IL_001c: ldobj ""T"" IL_0021: stloc.0 IL_0022: ldloca.s V_0 IL_0024: ldloc.0 IL_0025: box ""T"" IL_002a: brtrue.s IL_002f IL_002c: pop IL_002d: br.s IL_0040 IL_002f: ldarg.0 IL_0030: ldflda ""T Program.C1<T>.inst"" IL_0035: constrained. ""T"" IL_003b: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0040: ldarg.0 IL_0041: ldfld ""T Program.C1<T>.inst"" IL_0046: box ""T"" IL_004b: ldnull IL_004c: ceq IL_004e: call ""void System.Console.Write(bool)"" IL_0053: ret }"); } [Fact] public void RefReturnConditionalAccess05() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); inst = new T(); temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); } } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1TrueTrue1TrueTrueTrueTrue1TrueTrue", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 215 (0xd7) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br IL_00cf IL_0014: ldloc.0 IL_0015: ldloca.s V_2 IL_0017: initobj ""T"" IL_001d: ldloc.2 IL_001e: box ""T"" IL_0023: brtrue.s IL_0038 IL_0025: ldobj ""T"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: ldloc.2 IL_002e: box ""T"" IL_0033: brtrue.s IL_0038 IL_0035: pop IL_0036: br.s IL_0044 IL_0038: ldloc.0 IL_0039: constrained. ""T"" IL_003f: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0044: ldloc.0 IL_0045: ldobj ""T"" IL_004a: box ""T"" IL_004f: ldnull IL_0050: ceq IL_0052: call ""void System.Console.Write(bool)"" IL_0057: ldarg.0 IL_0058: ldfld ""T Program.C1<T>.inst"" IL_005d: box ""T"" IL_0062: ldnull IL_0063: ceq IL_0065: call ""void System.Console.Write(bool)"" IL_006a: ldarg.0 IL_006b: call ""T System.Activator.CreateInstance<T>()"" IL_0070: stfld ""T Program.C1<T>.inst"" IL_0075: ldloc.0 IL_0076: ldloca.s V_2 IL_0078: initobj ""T"" IL_007e: ldloc.2 IL_007f: box ""T"" IL_0084: brtrue.s IL_0099 IL_0086: ldobj ""T"" IL_008b: stloc.2 IL_008c: ldloca.s V_2 IL_008e: ldloc.2 IL_008f: box ""T"" IL_0094: brtrue.s IL_0099 IL_0096: pop IL_0097: br.s IL_00a5 IL_0099: ldloc.0 IL_009a: constrained. ""T"" IL_00a0: callvirt ""void IGoo<T>.Blah(ref T)"" IL_00a5: ldloc.0 IL_00a6: ldobj ""T"" IL_00ab: box ""T"" IL_00b0: ldnull IL_00b1: ceq IL_00b3: call ""void System.Console.Write(bool)"" IL_00b8: ldarg.0 IL_00b9: ldfld ""T Program.C1<T>.inst"" IL_00be: box ""T"" IL_00c3: ldnull IL_00c4: ceq IL_00c6: call ""void System.Console.Write(bool)"" IL_00cb: ldloc.1 IL_00cc: ldc.i4.1 IL_00cd: add IL_00ce: stloc.1 IL_00cf: ldloc.1 IL_00d0: ldc.i4.2 IL_00d1: blt IL_0014 IL_00d6: ret }"); } [Fact] public void RefReturn_CSharp6() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (6,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 16) ); } [Fact] public void RefInLambda_CSharp6() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (8,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(8, 9), // (8,17): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "N").WithArguments("local functions", "7.0").WithLocation(8, 17), // (10,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 13), // (10,21): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NN").WithArguments("local functions", "7.0").WithLocation(10, 21), // (10,40): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 40), // (12,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 13), // (12,25): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 25), // (15,20): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref r; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(15, 20), // (18,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref N(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(18, 16) ); } [Fact] public void RefDelegate_CSharp6() { var text = @" delegate ref int D(); "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10) ); } [Fact] public void RefInForStatement_CSharp6() { var text = @" class Program { static int M(ref int d) { for (ref int a = ref d; ;) { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (6,14): error CS8059: Feature 'ref for-loop variables' is not available in C# 6. Please use language version 7.3 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("ref for-loop variables", "7.3").WithLocation(6, 14), // (6,14): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 14), // (6,26): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 26) ); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(int x); class C { static void MD(D d) { } static int i = 0; static void M() { MD((x) => ref i); MD(x => ref i); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(int x); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10), // (11,19): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD((x) => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(11, 19), // (12,17): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD(x => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 17) ); } [Fact] public void Override_Metadata() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& A::get_P() } } .class public abstract B1 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object get_P() { ldnull throw } .property instance object P() { .get instance object B1::get_P() } } .class public abstract B2 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object& F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& B2::get_P() } }"; var ref1 = CompileIL(ilSource); var compilation = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { ref1 }); var method = compilation.GetMember<MethodSymbol>("B1.F"); Assert.Equal("System.Object B1.F()", method.ToTestDisplayString()); Assert.Equal("System.Object A.F()", method.OverriddenMethod.ToTestDisplayString()); var property = compilation.GetMember<PropertySymbol>("B1.P"); Assert.Equal("System.Object B1.P { get; }", property.ToTestDisplayString()); Assert.Null(property.OverriddenProperty); method = compilation.GetMember<MethodSymbol>("B2.F"); Assert.Equal("ref System.Object B2.F()", method.ToTestDisplayString()); Assert.Null(method.OverriddenMethod); property = compilation.GetMember<PropertySymbol>("B2.P"); Assert.Equal("ref System.Object B2.P { get; }", property.ToTestDisplayString()); Assert.Equal("ref System.Object A.P { get; }", property.OverriddenProperty.ToTestDisplayString()); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefReturnFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { return ref _f; } private T _p; public ref T P { get { return ref _p; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefAssignFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { ref var r = ref _f; return ref r; } private T _p; public ref T P { get { ref var r = ref _p; return ref r; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [Fact] public void ThrowRefReturn() { var text = @"using System; class Program { static ref int P1 { get => throw new E(1); } static ref int P2 => throw new E(2); static ref int M() => throw new E(3); public static void Main() { ref int L() => throw new E(4); D d = () => throw new E(5); try { ref int x = ref P1; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref P2; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref M(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref L(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref d(); } catch (E e) { Console.Write(e.Value); } } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; var v = CompileAndVerify(text, expectedOutput: "12345"); } [Fact] public void NoRefThrow() { var text = @"using System; class Program { static ref int P1 { get => ref throw new E(1); } static ref int P2 => ref throw new E(2); static ref int M() => ref throw new E(3); public static void Main() { ref int L() => ref throw new E(4); D d = () => ref throw new E(5); L(); d(); } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,36): error CS8115: A throw expression is not allowed in this context. // static ref int P1 { get => ref throw new E(1); } Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(4, 36), // (5,30): error CS8115: A throw expression is not allowed in this context. // static ref int P2 => ref throw new E(2); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(5, 30), // (6,31): error CS8115: A throw expression is not allowed in this context. // static ref int M() => ref throw new E(3); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 31), // (10,28): error CS8115: A throw expression is not allowed in this context. // ref int L() => ref throw new E(4); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(10, 28), // (11,25): error CS8115: A throw expression is not allowed in this context. // D d = () => ref throw new E(5); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 25) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,19): error CS8150: By-value returns may only be used in methods that return by value // B.F(() => o.F(), 2); Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "o.F()").WithLocation(24, 19) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_02() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "2"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_03() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,23): error CS8149: By-reference returns may only be used in methods that return by reference // B.F(() => ref o.F(), 2); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "o.F()").WithLocation(24, 23) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "23"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_02() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); CreateCompilation(source).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_03() { var source = @"public delegate ref T D<T>(); public class A<T> { private T _t = default(T); public T F() { return _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); CreateCompilation(source).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d.Length); // this is an error return ref d.Length; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (18,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d.Length; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(18, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001a() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref F1(ref d.Length); d = ""qwerty""; ref var temp2 = ref F1(ref d.Length); return temp1; } public static ref dynamic F1(ref dynamic d) { return ref d; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); v.VerifyIL("C.F(ref dynamic)", @" { // Code size 180 (0xb4) .maxstack 8 .locals init (object& V_0, //temp1 object V_1, object V_2) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""Length"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0045: ldarg.0 IL_0046: ldind.ref IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: stloc.1 IL_004d: ldloca.s V_1 IL_004f: call ""ref dynamic C.F1(ref dynamic)"" IL_0054: stloc.0 IL_0055: ldarg.0 IL_0056: ldstr ""qwerty"" IL_005b: stind.ref IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0061: brtrue.s IL_0092 IL_0063: ldc.i4.0 IL_0064: ldstr ""Length"" IL_0069: ldtoken ""C"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.1 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.0 IL_007c: ldnull IL_007d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0082: stelem.ref IL_0083: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0088: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0092: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0097: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_009c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a1: ldarg.0 IL_00a2: ldind.ref IL_00a3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a8: stloc.2 IL_00a9: ldloca.s V_2 IL_00ab: call ""ref dynamic C.F1(ref dynamic)"" IL_00b0: pop IL_00b1: ldloc.0 IL_00b2: ldind.ref IL_00b3: ret }"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001b() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); d = ""qwerty""; ref var temp2 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); return temp1; } public static ref dynamic F1(in int arg1, ref dynamic d, in int arg2) { if (arg1 == arg2) throw null; return ref d; } public static ref dynamic Test(ref dynamic arg1, ref dynamic arg2) { return ref arg2; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic002() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d[0]); return ref d[0]; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d[0]; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d[0]").WithLocation(17, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic003() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { return ref G(ref d.Length); } public static ref dynamic G(ref dynamic d) { return ref d; } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (14,26): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(14, 26), // (14,20): error CS8347: Cannot use a result of 'C.G(ref dynamic)' in this context because it may expose variables referenced by parameter 'd' outside of their declaration scope // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_EscapeCall, "G(ref d.Length)").WithArguments("C.G(ref dynamic)", "d").WithLocation(14, 20) ); } [Fact] public void RefReturnVarianceDelegate() { var source = @" using System; delegate ref T RefFunc1<T>(); delegate ref T RefFunc2<in T>(); delegate ref T RefFunc3<out T>(); delegate ref Action<T> RefFunc1a<T>(); delegate ref Action<T> RefFunc2a<in T>(); delegate ref Action<T> RefFunc3a<out T>(); delegate ref Func<T> RefFunc1f<T>(); delegate ref Func<T> RefFunc2f<in T>(); delegate ref Func<T> RefFunc3f<out T>(); "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3<T>.Invoke()'. 'T' is covariant. // delegate ref T RefFunc3<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc3<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(6, 10), // (5,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2<T>.Invoke()'. 'T' is contravariant. // delegate ref T RefFunc2<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc2<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(5, 10), // (14,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3f<T>.Invoke()'. 'T' is covariant. // delegate ref Func<T> RefFunc3f<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc3f<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(14, 10), // (13,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2f<T>.Invoke()'. 'T' is contravariant. // delegate ref Func<T> RefFunc2f<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc2f<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(13, 10), // (10,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3a<T>.Invoke()'. 'T' is covariant. // delegate ref Action<T> RefFunc3a<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc3a<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(10, 10), // (9,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2a<T>.Invoke()'. 'T' is contravariant. // delegate ref Action<T> RefFunc2a<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc2a<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(9, 10) ); } [Fact] public void RefReturnVarianceMethod() { var source = @" using System; interface IM1<T> { ref T RefMethod(); } interface IM2<in T> { ref T RefMethod(); } interface IM3<out T> { ref T RefMethod(); } interface IM1a<T> { ref Action<T> RefMethod(); } interface IM2a<in T> { ref Action<T> RefMethod(); } interface IM3a<out T> { ref Action<T> RefMethod(); } interface IM1f<T> { ref Func<T> RefMethod(); } interface IM2f<in T> { ref Func<T> RefMethod(); } interface IM3f<out T> { ref Func<T> RefMethod(); } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3<T>.RefMethod()'. 'T' is covariant. // interface IM3<out T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM3<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(6, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3a<T>.RefMethod()'. 'T' is covariant. // interface IM3a<out T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM3a<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(10, 25), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2a<T>.RefMethod()'. 'T' is contravariant. // interface IM2a<in T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM2a<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(9, 24), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2f<T>.RefMethod()'. 'T' is contravariant. // interface IM2f<in T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM2f<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3f<T>.RefMethod()'. 'T' is covariant. // interface IM3f<out T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM3f<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(14, 25), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2<T>.RefMethod()'. 'T' is contravariant. // interface IM2<in T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM2<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(5, 23) ); } [Fact] public void RefReturnVarianceProperty() { var source = @" using System; interface IP1<T> { ref T RefProp{get;} } interface IP2<in T> { ref T RefProp{get;} } interface IP3<out T> { ref T RefProp{get;} } interface IP1a<T> { ref Action<T> RefProp{get;} } interface IP2a<in T> { ref Action<T> RefProp{get;} } interface IP3a<out T> { ref Action<T> RefProp{get;} } interface IP1f<T> { ref Func<T> RefProp{get;} } interface IP2f<in T> { ref Func<T> RefProp{get;} } interface IP3f<out T> { ref Func<T> RefProp{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.RefProp'. 'T' is contravariant. // interface IP2<in T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(5, 23), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.RefProp'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(13, 24), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.RefProp'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.RefProp'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.RefProp", "T", "covariant", "invariantly").WithLocation(10, 25), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.RefProp'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.RefProp", "T", "covariant", "invariantly").WithLocation(14, 25), // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.RefProp'. 'T' is covariant. // interface IP3<out T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.RefProp", "T", "covariant", "invariantly").WithLocation(6, 24) ); } [Fact] public void RefReturnVarianceIndexer() { var source = @" using System; interface IP1<T> { ref T this[int i]{get;} } interface IP2<in T> { ref T this[int i]{get;} } interface IP3<out T> { ref T this[int i]{get;} } interface IP1a<T> { ref Action<T> this[int i]{get;} } interface IP2a<in T> { ref Action<T> this[int i]{get;} } interface IP3a<out T> { ref Action<T> this[int i]{get;} } interface IP1f<T> { ref Func<T> this[int i]{get;} } interface IP2f<in T> { ref Func<T> this[int i]{get;} } interface IP3f<out T> { ref Func<T> this[int i]{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.this[int]'. 'T' is covariant. // interface IP3<out T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.this[int]", "T", "covariant", "invariantly").WithLocation(6, 24), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.this[int]'. 'T' is contravariant. // interface IP2<in T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(5, 23), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.this[int]'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.this[int]'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.this[int]", "T", "covariant", "invariantly").WithLocation(10, 25), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.this[int]'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.this[int]'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.this[int]", "T", "covariant", "invariantly").WithLocation(14, 25) ); } [Fact] public void RefMethodGroupConversionError() { var source = @" using System; class Program { delegate ref T RefFunc1<T>(); static void Main() { RefFunc1<object> f = M1; f() = 1; f = new RefFunc1<object>(M1); f() = 1; } static ref string M1() => ref new string[]{""qq""}[0]; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string"), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(10, 30), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); } [Fact] public void RefMethodGroupConversionError_WithResolution() { var source = @" class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => ref Base.Instance; static ref Derived1 M1(Derived1 arg) => ref Derived1.Instance; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (22,38): error CS0407: 'Derived1 Program.M1(Derived1)' has the wrong return type // RefFunc1<Derived2, Base> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1(Derived1)", "Derived1").WithLocation(22, 38) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupConversionNoError_WithResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1 : Base { public static new Derived1 Instance = new Derived1(); } class Derived2 : Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => throw null; static ref Base M1(Derived1 arg) => ref Base.Instance; } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Base", verify: Verification.Passes); } [Fact] public void RefMethodGroupOverloadResolutionErr() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M1); Test(M3); } static ref Base M1(Derived1 arg) => ref Base.Instance; static ref Base M3(Derived2 arg) => ref Base.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (25,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M1); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(25, 9), // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M3); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(26, 9) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M2); } static ref Derived1 M2(Base arg) => ref Derived1.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Program+RefFunc1`2[Derived2,Derived1]", verify: Verification.Passes); } [Fact] public void RefLambdaOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test((t)=> Base.Instance); Test((t)=> ref Base.Instance); } static void Test(RefFunc1<Derived1, Base> arg) => Console.WriteLine(arg); static void Test(Func<Derived1, Base> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"System.Func`2[Derived1,Base] Program+RefFunc1`2[Derived1,Base]", verify: Verification.Passes); } [WorkItem(25024, "https://github.com/dotnet/roslyn/issues/25024")] [Fact] public void RefReturnDiscardLifetime() { var text = @" class Program { static bool flag = true; public static void Main() { if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 1; local2 = 2; System.Console.Write(local1 + local2); } if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 3; local2 = 4; System.Console.Write(local1 + local2); } } public static ref int M1(out int arg) { arg = 123; return ref arg; } } "; CompileAndVerifyRef(text, expectedOutput: "37", verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 75 (0x4b) .maxstack 3 .locals init (int& V_0, //local2 int V_1, int V_2, int& V_3, //local2 int V_4, int V_5) IL_0000: ldsfld ""bool Program.flag"" IL_0005: brfalse.s IL_0025 IL_0007: ldloca.s V_1 IL_0009: call ""ref int Program.M1(out int)"" IL_000e: ldloca.s V_2 IL_0010: call ""ref int Program.M1(out int)"" IL_0015: stloc.0 IL_0016: dup IL_0017: ldc.i4.1 IL_0018: stind.i4 IL_0019: ldloc.0 IL_001a: ldc.i4.2 IL_001b: stind.i4 IL_001c: ldind.i4 IL_001d: ldloc.0 IL_001e: ldind.i4 IL_001f: add IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldsfld ""bool Program.flag"" IL_002a: brfalse.s IL_004a IL_002c: ldloca.s V_4 IL_002e: call ""ref int Program.M1(out int)"" IL_0033: ldloca.s V_5 IL_0035: call ""ref int Program.M1(out int)"" IL_003a: stloc.3 IL_003b: dup IL_003c: ldc.i4.3 IL_003d: stind.i4 IL_003e: ldloc.3 IL_003f: ldc.i4.4 IL_0040: stind.i4 IL_0041: ldind.i4 IL_0042: ldloc.3 IL_0043: ldind.i4 IL_0044: add IL_0045: call ""void System.Console.Write(int)"" IL_004a: ret }"); } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringHelpersService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeRefactorings { internal interface ICodeRefactoringHelpersService : IWorkspaceService { bool ActiveInlineRenameSession { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeRefactorings { internal interface ICodeRefactoringHelpersService : IWorkspaceService { bool ActiveInlineRenameSession { get; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/ExpressionEvaluator/CSharp/Source/ResultProvider/CSharpResultProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { [DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException] internal sealed class CSharpResultProvider : ResultProvider { public CSharpResultProvider() : this(new CSharpFormatter()) { } private CSharpResultProvider(CSharpFormatter formatter) : this(formatter, formatter) { } internal CSharpResultProvider(IDkmClrFormatter2 formatter2, IDkmClrFullNameProvider fullNameProvider) : base(formatter2, fullNameProvider) { } internal override string StaticMembersString { get { return Resources.StaticMembers; } } internal override bool IsPrimitiveType(Type type) { return type.IsPredefinedType(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { [DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException] internal sealed class CSharpResultProvider : ResultProvider { public CSharpResultProvider() : this(new CSharpFormatter()) { } private CSharpResultProvider(CSharpFormatter formatter) : this(formatter, formatter) { } internal CSharpResultProvider(IDkmClrFormatter2 formatter2, IDkmClrFullNameProvider fullNameProvider) : base(formatter2, fullNameProvider) { } internal override string StaticMembersString { get { return Resources.StaticMembers; } } internal override bool IsPrimitiveType(Type type) { return type.IsPredefinedType(); } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Compilers/CSharp/Test/Semantic/FlowAnalysis/RegionAnalysisTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests for the region analysis APIs. /// </summary> /// <remarks> /// Please add your tests to other files if possible: /// * FlowDiagnosticTests.cs - all tests on Diagnostics /// * IterationJumpYieldStatementTests.cs - while, do, for, foreach, break, continue, goto, iterator (yield break, yield return) /// * TryLockUsingStatementTests.cs - try-catch-finally, lock, &amp; using statement /// * PatternsVsRegions.cs - region analysis tests for pattern matching /// </remarks> public partial class RegionAnalysisTests : FlowTestBase { #region "Expressions" [WorkItem(545047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545047")] [Fact] public void DataFlowsInAndNullable_Field() { // WARNING: if this test is edited, the test with the // test with the same name in VB must be modified too var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.F); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsOutAndStructField() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { S s = new S(1); /*<bind>*/ s.F = 1; /*</bind>*/ var x = s.F; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, s, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsInAndNullable_Property() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } public int P { get; set; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.P); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(538238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538238")] [Fact] public void TestDataFlowsIn03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = /*<bind>*/x + y/*</bind>*/; } } "); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowForValueTypes() { // WARNING: test matches the same test in VB (TestDataFlowForValueTypes) // Keep the two tests in sync! var analysis = CompileAndAnalyzeDataFlowStatements(@" class Tst { public static void Main() { S0 a; S1 b; S2 c; S3 d; E0 e; E1 f; /*<bind>*/ Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); Console.WriteLine(e); Console.WriteLine(f); /*</bind>*/ } } struct S0 { } struct S1 { public S0 s0; } struct S2 { public S0 s0; public int s1; } struct S3 { public S2 s; public object s1; } enum E0 { } enum E1 { V1 } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact] public void TestDataFlowsIn04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { string s = ""; Func<string> f = /*<bind>*/s/*</bind>*/.ToString; } } "); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowsOutExpression01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public void F(int x) { int a = 1, y; int tmp = x + /*<bind>*/ (y = x = 2) /*</bind>*/ + (a = 2); int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(540171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540171")] [Fact] public void TestIncrement() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace1() { var results = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/ System.Console /*</bind>*/ .WriteLine(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace3() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A.B /*</bind>*/ .M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace4() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A /*</bind>*/ .B.M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact] public void DataFlowsOutIncrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(6359, "DevDiv_Projects/Roslyn")] [Fact] public void DataFlowsOutPreDecrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Test { string method(string s, int i) { string[] myvar = new string[i]; myvar[0] = s; /*<bind>*/myvar[--i] = s + i.ToString()/*</bind>*/; return myvar[i]; } }"); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x ? /*<bind>*/ x /*</bind>*/ : true; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540832")] [Fact] public void TestAssignmentExpressionAsBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x; int y = true ? /*<bind>*/ x = 1 /*</bind>*/ : x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestAlwaysAssignedWithTernaryOperator() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, x = 100; /*<bind>*/ int c = true ? a = 1 : b = 2; /*</bind>*/ } }"); Assert.Equal("a, c", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, x, c", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned05() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned06() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned07() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned08() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned09() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned10() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned11() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? (b = null) /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned12() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ a ?? (b = null) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned13() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? null /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned14() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : (d = a) ? (e = a) : /*<bind>*/ (f = a) /*</bind>*/; } }"); Assert.Equal("f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d, f", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned15() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : /*<bind>*/ (d = a) ? (e = a) : (f = a) /*</bind>*/; } }"); Assert.Equal("d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned16() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) && B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned17() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) && B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned18() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) || B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned19() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) || B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned22() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; if (/*<bind>*/B(out a)/*</bind>*/) a = true; else b = true; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssignedAndWrittenInside() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestWrittenInside03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ = 3; } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite02() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(out int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(out /*<bind>*/x/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(ref int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(ref /*<bind>*/x/*</bind>*/); } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = ( /*<bind>*/ x = 1 /*</bind>*/ ) + x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestSingleVariableSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ x /*</bind>*/ ; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestParenthesizedAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ (x = x) /*</bind>*/ | x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestRefArgumentSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = 0; Goo(ref /*<bind>*/ x /*</bind>*/ ); System.Console.WriteLine(x); } static void Goo(ref int x) { } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540066")] [Fact] public void AnalysisOfBadRef() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { /*<bind>*/Main(ref 1)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned20NullCoalescing() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static object B(out object b) { b = null; return b; } public static void Main(string[] args) { object a, b; object c = B(out a) ?? B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" struct STest { public static string SM() { const string s = null; var ss = ""Q""; var ret = /*<bind>*/( s ?? (ss = ""C""))/*</bind>*/ + ss; return ret; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNotNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class Test { public static string SM() { const string s = ""Not Null""; var ss = ""QC""; var ret = /*<bind>*/ s ?? ss /*</bind>*/ + ""\r\n""; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(8935, "DevDiv_Projects/Roslyn")] [Fact] public void TestDefaultOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public T GetT() { return /*<bind>*/ default(T) /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestTypeOfOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public short GetT(T t) { if (/*<bind>*/ typeof(T) == typeof(int) /*</bind>*/) return 123; return 456; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestIsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { if /*<bind>*/(t is string)/*</bind>*/ return ""SSS""; return null; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestAsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { string ret = null; if (t is string) ret = /*<bind>*/t as string/*</bind>*/; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(4028, "DevDiv_Projects/Roslyn")] [Fact] public void TestArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int y = 1; int[,] x = { { /*<bind>*/ y /*</bind>*/ } }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestImplicitStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc int[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; f(1); } } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; static void Main() { int r = f(1); } } "); Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), string.Join(", ", new string[] { "f" }.Concat((results2.ReadOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), string.Join(", ", new string[] { "f" }.Concat((results2.WrittenOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInSimpleFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; int z = /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; static void Main() { /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } } "); // NOTE: 'f' should not be reported in results1.AlwaysAssigned, this issue will be addressed separately Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), GetSymbolNamesJoined(results2.ReadOutside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), GetSymbolNamesJoined(results2.WrittenOutside)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { const int myLength = /*<bind>*/5/*</bind>*/; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression2() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { // NOTE: illegal, but still a region we should handle. const bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void FieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(542454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542454")] [Fact] public void IdentifierNameInObjectCreationExpr() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class myClass { static int Main() { myClass oc = new /*<bind>*/myClass/*</bind>*/(); return 0; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(542463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542463")] [Fact] public void MethodGroupInDelegateCreation() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class C { void Method() { System.Action a = new System.Action(/*<bind>*/Method/*</bind>*/); } } "); Assert.Equal("this", dataFlows.ReadInside.Single().Name); } [WorkItem(542771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542771")] [Fact] public void BindInCaseLabel() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class TestShapes { static void Main() { color s = color.blue; switch (s) { case true ? /*<bind>*/ color.blue /*</bind>*/ : color.blue: break; default: goto default; } } } enum color { blue, green }"); var tmp = dataFlows.VariablesDeclared; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542915, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542915")] [Fact] public void BindLiteralExprInEnumDecl() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" enum Number { Zero = /*<bind>*/0/*</bind>*/ } "); Assert.True(dataFlows.Succeeded); Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact] public void AssignToConst() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { const string a = null; /*<bind>*/a = null;/*</bind>*/ } } "); Assert.Equal("a", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x = 1; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAddressOfAssignedStructField2() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); // Really ??? Assert.Equal("s", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } // Make sure that assignment is consistent with address-of. [Fact] public void TestAssignToStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int x = /*<bind>*/s.x = 1/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(544314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544314")] public void TestOmittedLambdaPointerTypeParameter() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; unsafe public class Test { public delegate int D(int* p); public static void Main() { int i = 10; int* p = &i; D d = /*<bind>*/delegate { return *p;}/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("p", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("p", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, p, d", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = 1, y = 2 } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_InvalidAccess() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; int x = 0, y = 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, x, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed_InitializerExpressionSyntax() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_NestedObjectInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public int z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() { x = x, y = /*<bind>*/ { z = z } /*</bind>*/ }; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public delegate int D(); public D z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = { z = () => z } } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("z", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("z", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestWithExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable record B(string? X) { static void M1(B b1) { var x = ""hello""; _ = /*<bind>*/b1 with { X = x }/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<int> list = /*<bind>*/ new List<int>() { 1, 2, 3, 4, 5 } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() /*<bind>*/ { x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_ComplexElementInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() { /*<bind>*/ { x } /*</bind>*/ }; return 0; } } "); // Nice to have: "x" flows in, "x" read inside, "list, x" written outside. Assert.False(analysis.Succeeded); } [Fact] public void TestCollectionInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public delegate int D(); public static int Main() { int x = 1; List<D> list = new List<D>() /*<bind>*/ { () => x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void ObjectInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { C c = /*<bind>*/new C { dele = delegate(int x, int y) { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void CollectionInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { List<Func<int, int, int>> list = /*<bind>*/new List<Func<int, int, int>>() { (x, y) => { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact(), WorkItem(529329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529329")] public void QueryAsFieldInitializer() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; using System.Collections.Generic; using System.Collections; class Test { public IEnumerable e = /*<bind>*/ from x in new[] { 1, 2, 3 } where BadExpression let y = x.ToString() select y /*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(544361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544361")] [Fact] public void FullQueryExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System.Linq; class Program { static void Main(string[] args) { var q = /*<bind>*/from arg in args group arg by arg.Length into final select final/*</bind>*/; } }"); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverRead() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); var value = /*<bind>*/x.y/*</bind>*/.z.Value; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value = 3; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverReadAndWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void UnaryPlus() { // reported at https://social.msdn.microsoft.com/Forums/vstudio/en-US/f5078027-def2-429d-9fef-ab7f240883d2/writteninside-for-unary-operators?forum=roslyn var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Main { static int Main(int a) { /*<bind>*/ return +a; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void NullCoalescingAssignment() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowMultipleExpressions(@" public class C { public static void Main() { C c; c ??= new C(); object x1; object y1; /*<bind0>*/GetC(x1 = 1).Prop ??= (y1 = 2)/*</bind0>*/; x1.ToString(); y1.ToString(); object x2; object y2; /*<bind1>*/GetC(x2 = 1).Field ??= (y2 = 2)/*</bind1>*/; x2.ToString(); y2.ToString(); } static C GetC(object i) => null; object Prop { get; set; } object Field; } "); var propertyDataFlowAnalysis = dataFlowAnalysisResults.First(); var fieldDataFlowAnalysis = dataFlowAnalysisResults.Skip(1).Single(); assertAllInfo(propertyDataFlowAnalysis, "x1", "y1", "x2", "y2"); assertAllInfo(fieldDataFlowAnalysis, "x2", "y2", "x1", "y1"); void assertAllInfo(DataFlowAnalysis dataFlowAnalysis, string currentX, string currentY, string otherX, string otherY) { Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal(currentX, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x1, y1, x2, y2", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal($"c, {otherX}, {otherY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } } [Fact] public void CondAccess_NullCoalescing_DataFlow() { // This test corresponds to ExtractMethodTests.TestFlowStateNullableParameters3 var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { public string M() { string? a = null; string? b = null; return /*<bind>*/(a + b + a)?.ToString()/*</bind>*/ ?? string.Empty; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("this, a, b", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_01(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } x.ToString(); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_02(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } #endregion #region "Statements" [Fact] public void TestDataReadWrittenIncDecOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static short Main() { short x = 0, y = 1, z = 2; /*<bind>*/ x++; y--; /*</bind>*/ return y; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTernaryExpressionWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ int z = x ? y = 1 : y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { int i; return; /*<bind>*/ i = i + 1; /*</bind>*/ int j = i; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { string i = 0, j = 0, k = 0, l = 0; goto l1; /*<bind>*/ Console.WriteLine(i); j = 1; l1: Console.WriteLine(j); k = 1; goto l2; Console.WriteLine(k); l = 1; l3: Console.WriteLine(l); i = 1; /*</bind>*/ l2: Console.WriteLine(i + j + k + l); goto l3; } }"); Assert.Equal("j, l", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegionInExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression( @"class C { public static bool Main() { int i, j; return false && /*<bind>*/((i = i + 1) == 2 || (j = i) == 3)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [Fact] public void TestDeclarationWithSelfReferenceAndTernaryOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = true ? 1 : x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDeclarationWithTernaryOperatorAndAssignment() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x, z, y = true ? 1 : x = z; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x, z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDictionaryInitializer() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Goo() { int i, j; /*<bind>*/ var s = new Dictionary<int, int>() {[i = j = 1] = 2 }; /*</bind>*/ System.Console.WriteLine(i + j); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(542435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542435")] [Fact] public void NullArgsToAnalyzeControlFlowStatements() { var compilation = CreateCompilation(@" class C { static void Main() { int i = 10; } } "); var semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var statement = compilation.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().First(); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow((StatementSyntax)null)); } [WorkItem(542507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542507")] [Fact] public void DateFlowAnalyzeForLocalWithInvalidRHS() { // Case 1 var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Test { public delegate int D(); public void goo(ref D d) { /*<bind>*/ d = { return 10;}; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); // Case 2 analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Gen<T> { public void DefaultTest() { /*<bind>*/ object obj = default (new Gen<T>()); /*</bind>*/ } } "); Assert.Equal("obj", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestEntryPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F() { goto L1; // 1 /*<bind>*/ L1: ; /*</bind>*/ goto L1; // 2 } }"); Assert.Equal(1, analysis.EntryPoints.Count()); } [Fact] public void TestExitPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { L1: ; // 1 /*<bind>*/ if (x == 0) goto L1; if (x == 1) goto L2; if (x == 3) goto L3; L3: ; /*</bind>*/ L2: ; // 2 } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestRegionCompletesNormally01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ goto L1; /*</bind>*/ L1: ; } }"); Assert.True(analysis.StartPointIsReachable); Assert.False(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ x = 2; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ if (x == 0) return; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestVariablesDeclared01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a; /*<bind>*/ int b; int x, y = 1; { var z = ""a""; } /*</bind>*/ int c; } }"); Assert.Equal("b, x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestVariablesInitializedWithSelfReference() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int x = x = 1; int y, z = 1; /*</bind>*/ } }"); Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void AlwaysAssignedUnreachable() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int y; /*<bind>*/ if (x == 1) { y = 2; return; } else { y = 3; throw new Exception(); } /*</bind>*/ int = y; } }"); Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(538170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538170")] [Fact] public void TestVariablesDeclared02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) /*<bind>*/ { int a; int b; int x, y = 1; { string z = ""a""; } int c; } /*</bind>*/ }"); Assert.Equal("a, b, x, y, z, c", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [WorkItem(541280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541280")] [Fact] public void TestVariablesDeclared03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F() /*<bind>*/ { int a = 0; long a = 1; } /*</bind>*/ }"); Assert.Equal("a, a", GetSymbolNamesJoined(analysis.VariablesDeclared)); var intsym = analysis.VariablesDeclared.First() as ILocalSymbol; var longsym = analysis.VariablesDeclared.Last() as ILocalSymbol; Assert.Equal("Int32", intsym.Type.Name); Assert.Equal("Int64", longsym.Type.Name); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact] public void UnassignedVariableFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main(string[] args) { int i = 10; /*<bind>*/ int j = j + i; /*</bind>*/ Console.Write(i); Console.Write(j); } }"); Assert.Equal("j", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestDataFlowsIn01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 2; /*<bind>*/ int b = a + x + 3; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.DataFlowsIn)); } [Fact] public void TestOutParameter01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y; /*<bind>*/ if (x == 1) y = x = 2; /*</bind>*/ int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [WorkItem(538146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538146")] [Fact] public void TestDataFlowsOut02() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { /*<bind>*/ int s = 10, i = 1; int b = s + i; /*</bind>*/ System.Console.WriteLine(s); System.Console.WriteLine(i); } }"); Assert.Equal("s, i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut03() { var analysis = CompileAndAnalyzeDataFlowStatements( @"using System.Text; class Program { private static string Main() { StringBuilder builder = new StringBuilder(); /*<bind>*/ builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); /*</bind>*/ return builder.ToString(); } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut04() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut05() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; return; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut06() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 1; while (b) { /*<bind>*/ i = i + 1; /*</bind>*/ } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut07() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i; /*<bind>*/ i = 2; goto next; /*</bind>*/ next: int j = i; } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); } [WorkItem(540793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540793")] [Fact] public void TestDataFlowsOut08() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 2; try { /*<bind>*/ i = 1; /*</bind>*/ } finally { int j = i; } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut09() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { int i; string s; /*<bind>*/i = 10; s = args[0] + i.ToString();/*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut10() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { int x = 10; /*<bind>*/ int y; if (x == 10) y = 5; /*</bind>*/ Console.WriteLine(y); } } "); Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestAlwaysAssigned01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 1; /*<bind>*/ if (x == 2) a = 3; else a = 4; x = 4; if (x == 3) y = 12; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssigned02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ const int a = 1; /*</bind>*/ } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(540795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540795")] [Fact] public void TestAlwaysAssigned03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Always { public void F() { ushort x = 0, y = 1, z; /*<bind>*/ x++; return; uint z = y; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestReadInside01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this, t1", GetSymbolNamesJoined(analysis.ReadInside)); } [Fact] public void TestAlwaysAssignedDuplicateVariables() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a, a, b, b; b = 1; /*</bind>*/ } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAccessedInsideOutside() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, c, d, e, f, g, h, i; a = 1; c = b = a + x; /*<bind>*/ d = c; e = f = d; /*</bind>*/ g = e; h = i = g; } }"); Assert.Equal("c, d", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("d, e, f", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, a, e, g", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, b, c, g, h, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAlwaysAssignedThroughParenthesizedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a = 1, b, c, d, e; b = 2; (c) = 3; ((d)) = 4; /*</bind>*/ } }"); Assert.Equal("a, b, c, d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedThroughCheckedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int e, f, g; checked(e) = 5; (unchecked(f)) = 5; /*</bind>*/ } }"); Assert.Equal("e, f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedUsingAlternateNames() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int green, blue, red, yellow, brown; @green = 1; blu\u0065 = 2; re܏d = 3; yellow\uFFF9 = 4; @brown\uFFF9 = 5; /*</bind>*/ } }"); Assert.Equal("green, blue, red, yellow, brown", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedViaPassingAsOutParameter() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a; G(out a); /*</bind>*/ } void G(out int x) { x = 1; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedWithExcludedAssignment() { var analysis = CompileAndAnalyzeDataFlowStatements(@" partial class C { public void F(int x) { /*<bind>*/ int a, b; G(a = x = 1); H(b = 2); /*</bind>*/ } partial void G(int x); partial void H(int x); partial void H(int x) { } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestDeclarationWithSelfReference() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (x) y = 1; else y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithNonConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true | x) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestNonStatementSelection() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // // /*<bind>*/ //int // /*</bind>*/ // x = 1; // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.True(controlFlowAnalysisResults.Succeeded); // Assert.True(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [Fact] public void TestInvocation() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x); /*</bind>*/ } static void Goo(int x) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestInvocationWithAssignmentInArguments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x = y, y = 2); /*</bind>*/ int z = x + y; } static void Goo(int x, int y) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidLocalDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; public class MyClass { public static int Main() { variant /*<bind>*/ v = new byte(2) /*</bind>*/; // CS0246 byte b = v; // CS1729 return 1; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidKeywordAsExpr() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class B : A { public float M() { /*<bind>*/ { return base; // CS0175 } /*</bind>*/ } } class A {} "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); } [WorkItem(539071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539071")] [Fact] public void AssertFromFoldConstantEnumConversion() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" enum E { x, y, z } class Test { static int Main() { /*<bind>*/ E v = E.x; if (v != (E)((int)E.z - 1)) return 0; /*</bind>*/ return 1; } } "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); } [Fact] public void ByRefParameterNotInAppropriateCollections2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(ref T t) { /*<bind>*/ T t1 = GetValue<T>(ref t); /*</bind>*/ System.Console.WriteLine(t1.ToString()); } T GetValue<T>(ref T t) { return t; } } "); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void UnreachableDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F() { /*<bind>*/ int x; /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Parameters01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F(int x, ref int y, out int z) { /*<bind>*/ y = z = 3; /*</bind>*/ } } "); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528308")] [Fact] public void RegionForIfElseIfWithoutElse() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class Test { ushort TestCase(ushort p) { /*<bind>*/ if (p > 0) { return --p; } else if (p < 0) { return ++p; } /*</bind>*/ // else { return 0; } } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(2, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestBadRegion() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // int a = 1; // int b = 1; // // if(a > 1) // /*<bind>*/ // a = 1; // b = 2; // /*</bind>*/ // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.False(controlFlowAnalysisResults.Succeeded); // Assert.False(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [WorkItem(541331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541331")] [Fact] public void AttributeOnAccessorInvalid() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class C { public class AttributeX : Attribute { } public int Prop { get /*<bind>*/{ return 1; }/*</bind>*/ protected [AttributeX] set { } } } "); var controlFlowAnalysisResults = analysisResults.Item1; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); } [WorkItem(541585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541585")] [Fact] public void BadAssignThis() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class Program { static void Main(string[] args) { /*<bind>*/ this = new S(); /*</bind>*/ } } struct S { }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528623")] [Fact] public void TestElementAccess01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" public class Test { public void M(long[] p) { var v = new long[] { 1, 2, 3 }; /*<bind>*/ v[0] = p[0]; p[0] = v[1]; /*</bind>*/ v[1] = v[0]; p[2] = p[0]; } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.DataFlowsIn)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadInside)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, p, v", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(541947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541947")] [Fact] public void BindPropertyAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.False(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(8926, "DevDiv_Projects/Roslyn")] [WorkItem(542346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542346")] [WorkItem(528775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528775")] [Fact] public void BindEventAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public delegate void D(); public event D E { add { /*NA*/ } remove /*<bind>*/ { /*NA*/ } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(541980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541980")] [Fact] public void BindDuplicatedAccessor() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get { return 1;} get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; var tmp = ctrlFlows.EndPointIsReachable; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(543737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543737")] [Fact] public void BlockSyntaxInAttributeDecl() { { var compilation = CreateCompilation(@" [Attribute(delegate.Class)] public class C { public static int Main () { return 1; } } "); var tree = compilation.SyntaxTrees.First(); var index = tree.GetCompilationUnitRoot().ToFullString().IndexOf(".Class)", StringComparison.Ordinal); var tok = tree.GetCompilationUnitRoot().FindToken(index); var node = tok.Parent as StatementSyntax; Assert.Null(node); } { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" [Attribute(x => { /*<bind>*/int y = 12;/*</bind>*/ })] public class C { public static int Main () { return 1; } } "); Assert.False(results.Item1.Succeeded); Assert.False(results.Item2.Succeeded); } } [Fact, WorkItem(529273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529273")] public void IncrementDecrementOnNullable() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class C { void M(ref sbyte p1, ref sbyte? p2) { byte? local_0 = 2; short? local_1; ushort non_nullable = 99; /*<bind>*/ p1++; p2 = (sbyte?) (local_0.Value - 1); local_1 = (byte)(p2.Value + 1); var ret = local_1.HasValue ? local_1.Value : 0; --non_nullable; /*</bind>*/ } } "); Assert.Equal("ret", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p1, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p1, p2, local_0, local_1, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p1, p2, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(17971, "https://github.com/dotnet/roslyn/issues/17971")] [Fact] public void VariablesDeclaredInBrokenForeach() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { static void Main(string[] args) { /*<bind>*/ Console.WriteLine(1); foreach () Console.WriteLine(2); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] [WorkItem(4950, "https://github.com/dotnet/roslyn/issues/4950")] public void RegionWithUnsafeBlock() { var source = @"using System; class Program { static void Main(string[] args) { object value = args; // start IntPtr p; unsafe { object t = value; p = IntPtr.Zero; } // end Console.WriteLine(p); } } "; foreach (string keyword in new[] { "unsafe", "checked", "unchecked" }) { var compilation = CreateCompilation(source.Replace("unsafe", keyword)); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var stmt1 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString() == "IntPtr p;").Single(); var stmt2 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString().StartsWith(keyword)).First(); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt1, stmt2); Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, value, p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("args, p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } #endregion #region "lambda" [Fact] [WorkItem(41600, "https://github.com/dotnet/roslyn/pull/41600")] public void DataFlowAnalysisLocalFunctions10() { var dataFlow = CompileAndAnalyzeDataFlowExpression(@" class C { public void M() { bool Dummy(params object[] x) {return true;} try {} catch when (/*<bind>*/TakeOutParam(out var x1)/*</bind>*/ && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } } "); Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this, x1", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this, x1, x4, x4, x6, x7, x7, x8, x9, x9, y10, x14, x15, x, x", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this, x, x4, x4, x6, x7, x7, x8, x9, x9, x10, " + "y10, x14, x14, x15, x15, x, y, x", GetSymbolNamesJoined(dataFlow.WrittenOutside)); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void DataFlowAnalysisLocalFunctions9() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { int Testing; void M() { local(); /*<bind>*/ NewMethod(); /*</bind>*/ Testing = 5; void local() { } } void NewMethod() { } }"); var dataFlow = results.dataFlowAnalysis; Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.WrittenOutside)); var controlFlow = results.controlFlowAnalysis; Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions01() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.False(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions02() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ local(); System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions03() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ local(); void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions04() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { System.Console.WriteLine(0); local(); void local() { /*<bind>*/ throw null; /*</bind>*/ } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions05() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); void local() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions06() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { void local() { throw null; } /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] public void TestReturnStatements03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; /*<bind>*/ if (x == 1) return; Func<int,int> f = (int i) => { return i+1; }; if (x == 2) return; /*</bind>*/ } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements04() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; Func<int,int> f = (int i) => { /*<bind>*/ return i+1; /*</bind>*/ } ; if (x == 2) return; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements05() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; /*<bind>*/ Func<int,int?> f = (int i) => { return i == 1 ? i+1 : null; } ; /*</bind>*/ if (x == 2) return; } }"); Assert.True(analysis.Succeeded); Assert.Empty(analysis.ReturnStatements); } [Fact] public void TestReturnStatements06() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(uint? x) { if (x == null) return; if (x.Value == 1) return; /*<bind>*/ Func<uint?, ulong?> f = (i) => { return i.Value +1; } ; if (x.Value == 2) return; /*</bind>*/ } }"); Assert.True(analysis.Succeeded); Assert.Equal(1, analysis.ExitPoints.Count()); } [WorkItem(541198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541198")] [Fact] public void TestReturnStatements07() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public int F(int x) { Func<int,int> f = (int i) => { goto XXX; /*<bind>*/ return 1; /*</bind>*/ } ; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestMultipleLambdaExpressions() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { int i; N(/*<bind>*/() => { M(); }/*</bind>*/, () => { i++; }); } void N(System.Action x, System.Action y) { } }"); Assert.True(analysis.Succeeded); Assert.Equal("this, i", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReturnFromLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main(string[] args) { int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, lambda", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void DataFlowsOutLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; return; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda02() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main() { int? i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ return; }; int j = i.Value; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda03() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact] public void TestReadInside02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void Method() { System.Func<int, int> a = x => /*<bind>*/x * x/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, a, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestCaptured02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; class C { int field = 123; public void F(int x) { const int a = 1, y = 1; /*<bind>*/ Func<int> lambda = () => x + y + field; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y, lambda", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact, WorkItem(539648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539648"), WorkItem(529185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529185")] public void ReturnsInsideLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate R Func<T, R>(T t); static void Main(string[] args) { /*<bind>*/ Func<int, int> f = (arg) => { int s = 3; return s; }; /*</bind>*/ f.Invoke(2); } }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.ReturnStatements); Assert.Equal("f", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, f", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("f, arg, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { /*<bind>*/ TestDelegate testDel = (ref int x) => { }; /*</bind>*/ int p = 2; testDel(ref p); Console.WriteLine(p); } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, testDel", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda02() { var results1 = CompileAndAnalyzeDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int? x); static void Main() { /*<bind>*/ TestDelegate testDel = (ref int? x) => { int y = x; x.Value = 10; }; /*</bind>*/ int? p = 2; testDel(ref p); Console.WriteLine(p); } } "); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.VariablesDeclared)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results1.ReadInside)); Assert.Equal("testDel, p", GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("p", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(540449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540449")] [Fact] public void AnalysisInsideLambdas() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; } } "); Assert.Equal("x", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.ReadInside)); Assert.Null(GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("f, p, x, y", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(528622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528622")] [Fact] public void AlwaysAssignedParameterLambda() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; internal class Test { void M(sbyte[] ary) { /*<bind>*/ ( (Action<short>)(x => { Console.Write(x); }) )(ary[0])/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("ary", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("ary, x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(541946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541946")] [Fact] public void LambdaInTernaryWithEmptyBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public delegate void D(); public class A { void M() { int i = 0; /*<bind>*/ D d = true ? (D)delegate { i++; } : delegate { }; /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, i, d", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("i, d", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void ForEachVariableInLambda() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { var nums = new int?[] { 4, 5 }; foreach (var num in /*<bind>*/nums/*</bind>*/) { Func<int, int> f = x => x + num.Value; Console.WriteLine(f(0)); } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543398")] [Fact] public void LambdaBlockSyntax() { var source = @" using System; class c1 { void M() { var a = 0; foreach(var l in """") { Console.WriteLine(l); a = (int) l; l = (char) a; } Func<int> f = ()=> { var c = a; a = c; return 0; }; var b = 0; Console.WriteLine(b); } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CSharpCompilation.Create("FlowAnalysis", syntaxTrees: new[] { tree }); var model = comp.GetSemanticModel(tree); var methodBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().First(); var foreachStatement = methodBlock.DescendantNodes().OfType<ForEachStatementSyntax>().First(); var foreachBlock = foreachStatement.DescendantNodes().OfType<BlockSyntax>().First(); var lambdaExpression = methodBlock.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().First(); var lambdaBlock = lambdaExpression.DescendantNodes().OfType<BlockSyntax>().First(); var flowAnalysis = model.AnalyzeDataFlow(methodBlock); Assert.Equal(4, flowAnalysis.ReadInside.Count()); Assert.Equal(5, flowAnalysis.WrittenInside.Count()); Assert.Equal(5, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(foreachBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(0, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(lambdaBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(1, flowAnalysis.VariablesDeclared.Count()); } [Fact] public void StaticLambda_01() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => Console.Write(x); fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,48): error CS8820: A static anonymous function cannot contain a reference to 'x'. // Action fn = static () => Console.Write(x); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(9, 48) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_02() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,21): error CS8820: A static anonymous function cannot contain a reference to 'x'. // int y = x; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 21), // (12,13): error CS8820: A static anonymous function cannot contain a reference to 'x'. // x = 43; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(12, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_03() { var source = @" using System; class C { public static int x = 42; static void Main() { Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "42"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } } #endregion #region "query expressions" [Fact] public void QueryExpression01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; /*<bind>*/ var q2 = from x in nums where (x > 2) where x > 3 select x; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("q2", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, q2", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from x in nums where (x > 2) select /*<bind>*/ x+1 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int?[] { 1, 2, null, 4 }; var q2 = from x in nums group x.Value + 1 by /*<bind>*/ x.Value % 2 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new uint[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 select /*<bind>*/ x /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 group /*<bind>*/ x /*</bind>*/ by x%2; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541916")] [Fact] public void ForEachVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; foreach (var num in nums) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541945")] [Fact] public void ForVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; for (int num = 0; num < 10; num++) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541926")] [Fact] public void Bug8863() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System.Linq; class C { static void Main(string[] args) { /*<bind>*/ var temp = from x in ""abc"" let z = x.ToString() select z into w select w; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("temp", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, temp", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Bug9415() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q1 = from x in new int[] { /*<bind>*/4/*</bind>*/, 5 } orderby x select x; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, q1, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543546")] [Fact] public void GroupByClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main() { var strings = new string[] { }; var q = from s in strings select s into t /*<bind>*/group t by t.Length/*</bind>*/; } }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] [Fact] public void CaptureInQuery() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main(int[] data) { int y = 1; { int x = 2; var f2 = from a in data select a + y; var f3 = from a in data where x > 0 select a; var f4 = from a in data let b = 1 where /*<bind>*/M(() => b)/*</bind>*/ select a + b; var f5 = from c in data where M(() => c) select c; } } private static bool M(Func<int> f) => true; }"); var dataFlowAnalysisResults = analysisResults; Assert.Equal("y, x, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } #endregion query expressions #region "switch statement tests" [Fact] public void LocalInOtherSwitchCase() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; using System.Linq; public class Test { public static void Main() { int ret = 6; switch (ret) { case 1: int i = 10; break; case 2: var q1 = from j in new int[] { 3, 4 } select /*<bind>*/i/*</bind>*/; break; } } }"); Assert.Empty(dataFlows.DataFlowsOut); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void VariableDeclInsideSwitchCaptureInLambdaExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { public static void Main() { switch (10) { default: int i = 10; Func<int> f1 = () => /*<bind>*/i/*</bind>*/; break; } } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, f1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541710")] [Fact] public void ArrayCreationExprInForEachInsideSwitchSection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': foreach (var i100 in new int[] {4, /*<bind>*/5/*</bind>*/ }) { } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("i100", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void RegionInsideSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': switch (/*<bind>*/'2'/*</bind>*/) { case '2': break; } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void NullableAsSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class C { public void F(ulong? p) { /*<bind>*/ switch (p) { case null: break; case 1: goto case null; default: break; } /*</bind>*/ } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(17281, "https://github.com/dotnet/roslyn/issues/17281")] public void DiscardVsVariablesDeclared() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class A { } class Test { private void Repro(A node) { /*<bind>*/ switch (node) { case A _: break; case Unknown: break; default: return; } /*</bind>*/ } }"); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion #region "Misc." [Fact, WorkItem(11298, "DevDiv_Projects/Roslyn")] public void BaseExpressionSyntax() { var source = @" using System; public class BaseClass { public virtual void MyMeth() { } } public class MyClass : BaseClass { public override void MyMeth() { base.MyMeth(); } delegate BaseClass D(); public void OtherMeth() { D f = () => base; } public static void Main() { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(invocation); Assert.Empty(flowAnalysis.Captured); Assert.Empty(flowAnalysis.CapturedInside); Assert.Empty(flowAnalysis.CapturedOutside); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("MyClass this", flowAnalysis.WrittenOutside.Single().ToTestDisplayString()); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); flowAnalysis = model.AnalyzeDataFlow(lambda); Assert.Equal("MyClass this", flowAnalysis.Captured.Single().ToTestDisplayString()); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("this, f", GetSymbolNamesJoined(flowAnalysis.WrittenOutside)); } [WorkItem(543101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543101")] [Fact] public void AnalysisInsideBaseClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { A(int x) : this(/*<bind>*/x.ToString()/*</bind>*/) { } A(string x) { } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543758")] [Fact] public void BlockSyntaxOfALambdaInAttributeArg() { var controlFlowAnalysisResults = CompileAndAnalyzeControlFlowStatements(@" class Test { [Attrib(() => /*<bind>*/{ }/*</bind>*/)] public static void Main() { } } "); Assert.False(controlFlowAnalysisResults.Succeeded); } [WorkItem(529196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529196")] [Fact()] public void DefaultValueOfOptionalParam() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" public class Derived { public void Goo(int x = /*<bind>*/ 2 /*</bind>*/) { } } "); Assert.True(dataFlowAnalysisResults.Succeeded); } [Fact] public void GenericStructureCycle() { var source = @"struct S<T> { public S<S<T>> F; } class C { static void M() { S<object> o; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("S<object> o", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Equal("o", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(545372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545372")] [Fact] public void AnalysisInSyntaxError01() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; class Program { static void Main(string[] args) { Expression<Func<int>> f3 = () => if (args == null) {}; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("if", StringComparison.Ordinal)); Assert.Equal("if (args == null) {}", statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, f3", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(546964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546964")] [Fact] public void AnalysisWithMissingMember() { var source = @"class C { void Goo(string[] args) { foreach (var s in args) { this.EditorOperations = 1; } } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("EditorOperations", StringComparison.Ordinal)); Assert.Equal("this.EditorOperations = 1;", statement.ToString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); var v = analysis.DataFlowsOut; } [Fact, WorkItem(547059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547059")] public void ObjectInitIncompleteCodeInQuery() { var source = @" using System.Collections.Generic; using System.Linq; class Program { static void Main() { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } public interface ISymbol { } public class ExportedSymbol { public ISymbol Symbol; public byte UseBits; } "; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().FirstOrDefault(); var expectedtext = @" { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } "; Assert.Equal(expectedtext, statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void StaticSetterAssignedInCtor() { var source = @"class C { C() { P = new object(); } static object P { get; set; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("P = new object()", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void FieldBeforeAssignedInStructCtor() { var source = @"struct S { object value; S(object x) { S.Equals(value , value); this.value = null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0170: Use of possibly unassigned field 'value' // S.Equals(value , value); Diagnostic(ErrorCode.ERR_UseDefViolationField, "value").WithArguments("value") ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var expression = GetLastNode<ExpressionSyntax>(tree, root.ToFullString().IndexOf("value ", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(expression); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact, WorkItem(14110, "https://github.com/dotnet/roslyn/issues/14110")] public void Test14110() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { var (a0, b0) = (1, 2); (var c0, int d0) = (3, 4); bool e0 = a0 is int f0; bool g0 = a0 is var h0; M(out int i0); M(out var j0); /*<bind>*/ var (a, b) = (1, 2); (var c, int d) = (3, 4); bool e = a is int f; bool g = a is var h; M(out int i); M(out var j); /*</bind>*/ var (a1, b1) = (1, 2); (var c1, int d1) = (3, 4); bool e1 = a1 is int f1; bool g1 = a1 is var h1; M(out int i1); M(out var j1); } static void M(out int z) => throw null; } "); Assert.Equal("a, b, c, d, e, f, g, h, i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact, WorkItem(15640, "https://github.com/dotnet/roslyn/issues/15640")] public void Test15640() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class Programand { static void Main() { foreach (var (a0, b0) in new[] { (1, 2) }) {} /*<bind>*/ foreach (var (a, b) in new[] { (1, 2) }) {} /*</bind>*/ foreach (var (a1, b1) in new[] { (1, 2) }) {} } } "); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] public void RegionAnalysisLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Local(); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Action a = Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = new Action(Local); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } Local(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { var a = new Action(() => { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } }); a(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = (Action)Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { int x = 0; void Local() { x++; } Local(); /*<bind>*/ x++; x = M(x + 1); /*</bind>*/ } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture1() { var results = CompileAndAnalyzeDataFlowStatements(@" public static class SomeClass { private static void Repro( int arg ) { /*<bind>*/int localValue = arg;/*</bind>*/ int LocalCapture() => arg; } }"); Assert.True(results.Succeeded); Assert.Equal("arg", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("arg", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("arg", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("arg, localValue", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("localValue", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("localValue", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture2() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; Local(); /*<bind>*/int y = x;/*</bind>*/ int Local() { x = 0; } } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture3() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; /*<bind>*/int y = x;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture4() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x, y = 0; /*<bind>*/x = y;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this, y", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { int x = 0; void M() { /*<bind>*/ int L(int a) => x; /*</bind>*/ L(); } }"); Assert.Equal("this", GetSymbolNamesJoined(results.Captured)); Assert.Equal("this", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M(int x) { int y; int z; void Local() { /*<bind>*/ x++; y = 0; y++; /*</bind>*/ } Local(); } }"); Assert.Equal("x, y", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x, y", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); // TODO(https://github.com/dotnet/roslyn/issues/14214): This is wrong. // Both x and y should flow out. Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact] public void LocalFuncCapture7() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; void L() { /*<bind>*/ int y = 0; y++; x = 0; /*</bind>*/ } x++; } }"); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture8() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture9() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; Inside(); /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void AssignmentInsideLocal01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 1) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if (false) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // This is a conservative approximation, ignoring whether the branch containing // the assignment is reachable Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ x = 1; } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] [WorkItem(39569, "https://github.com/dotnet/roslyn/issues/39569")] public void AssignmentInsideLocal05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { x = 1; } /*<bind>*/ Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); // Right now region analysis requires bound nodes for each variable and value being // assigned. This doesn't work with the current local function analysis because we only // store the slots, not the full boundnode of every assignment (which is impossible // anyway). This should be: // Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal06() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } /*</bind>*/ Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal07() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal08() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal09() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; throw new Exception(); } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // N.B. This is not as precise as possible. The branch assigning y is unreachable, so // the result does not technically flow out. This is a conservative approximation. Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true when true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact] public void AnalysisOfTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = /*<bind>*/(x, y) == (x = 0, 1)/*</bind>*/; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfNestedTupleInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, (2, 3)) == (0, /*<bind>*/(x = 0, y)/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfExpressionInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, 2) == (0, /*<bind>*/(x = 0) + y/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfMixedDeconstruction() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { bool M() { int x = 0; string y; /*<bind>*/ (x, (y, var z)) = (x, ("""", true)) /*</bind>*/ return z; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer01() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(nameof(P), /*<bind>*/x => true/*</bind>*/); static object Create(string name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer02() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(P, /*<bind>*/x => true/*</bind>*/); static object Create(object name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(19845, "https://github.com/dotnet/roslyn/issues/19845")] public void CodeInInitializer03() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static int X { get; set; } int Y = /*<bind>*/X/*</bind>*/; }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(26028, "https://github.com/dotnet/roslyn/issues/26028")] public void BrokenForeach01() { var source = @"class C { void M() { foreach (var x } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); // The foreach loop is broken, so its embedded statement is filled in during syntax error recovery. It is zero-width. var stmt = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<ForEachStatementSyntax>().Single().Statement; Assert.Equal(0, stmt.Span.Length); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(30548, "https://github.com/dotnet/roslyn/issues/30548")] public void SymbolInDataFlowInButNotInReadInside() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; /*<bind>*/if (a) { return; } if (A == a) { test = new object(); }/*</bind>*/ } } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(37427, "https://github.com/dotnet/roslyn/issues/37427")] public void RegionWithLocalFunctions() { // local functions inside the region var s1 = @" class A { static void M(int p) { int i, j; i = 1; /*<bind>*/ int L1() => 1; int k; j = i; int L2() => 2; /*</bind>*/ k = j; } } "; // local functions outside the region var s2 = @" class A { static void M(int p) { int i, j; i = 1; int L1() => 1; /*<bind>*/ int k; j = i; /*</bind>*/ int L2() => 2; k = j; } } "; foreach (var s in new[] { s1, s2 }) { var analysisResults = CompileAndAnalyzeDataFlowStatements(s); var dataFlowAnalysisResults = analysisResults; Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("k", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("p, i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } [Fact] public void TestAddressOfUnassignedStructLocal_02() { // This test demonstrates that "data flow analysis" pays attention to private fields // of structs imported from metadata. var libSource = @" public struct Struct { private string Field; }"; var libraryReference = CreateCompilation(libSource).EmitToImageReference(); var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { Struct x; // considered not definitely assigned because it has a field Struct * px = /*<bind>*/&x/*</bind>*/; // address taken of an unassigned variable } } ", libraryReference); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } #endregion #region "Used Local Functions" [Fact] public void RegionAnalysisUsedLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } void Unused(){ } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ System.Action a = new System.Action(Local); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions9() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions10() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions11() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions12() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions13() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions14() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions15() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions16() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions17() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions18() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions19() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions20() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions21() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions22() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions23() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } #endregion #region "Top level statements" [Fact] public void TestTopLevelStatements() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; /*<bind>*/ Console.Write(1); Console.Write(2); Console.Write(3); Console.Write(4); Console.Write(5); /*</bind>*/ "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_Lambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_LambdaCapturingArgs() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; Func<int> lambda = () => { /*<bind>*/return args.Length;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests for the region analysis APIs. /// </summary> /// <remarks> /// Please add your tests to other files if possible: /// * FlowDiagnosticTests.cs - all tests on Diagnostics /// * IterationJumpYieldStatementTests.cs - while, do, for, foreach, break, continue, goto, iterator (yield break, yield return) /// * TryLockUsingStatementTests.cs - try-catch-finally, lock, &amp; using statement /// * PatternsVsRegions.cs - region analysis tests for pattern matching /// </remarks> public partial class RegionAnalysisTests : FlowTestBase { #region "Expressions" [WorkItem(545047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545047")] [Fact] public void DataFlowsInAndNullable_Field() { // WARNING: if this test is edited, the test with the // test with the same name in VB must be modified too var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.F); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsOutAndStructField() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { S s = new S(1); /*<bind>*/ s.F = 1; /*</bind>*/ var x = s.F; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, s, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsInAndNullable_Property() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } public int P { get; set; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.P); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(538238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538238")] [Fact] public void TestDataFlowsIn03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = /*<bind>*/x + y/*</bind>*/; } } "); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowForValueTypes() { // WARNING: test matches the same test in VB (TestDataFlowForValueTypes) // Keep the two tests in sync! var analysis = CompileAndAnalyzeDataFlowStatements(@" class Tst { public static void Main() { S0 a; S1 b; S2 c; S3 d; E0 e; E1 f; /*<bind>*/ Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); Console.WriteLine(e); Console.WriteLine(f); /*</bind>*/ } } struct S0 { } struct S1 { public S0 s0; } struct S2 { public S0 s0; public int s1; } struct S3 { public S2 s; public object s1; } enum E0 { } enum E1 { V1 } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact] public void TestDataFlowsIn04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { string s = ""; Func<string> f = /*<bind>*/s/*</bind>*/.ToString; } } "); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowsOutExpression01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public void F(int x) { int a = 1, y; int tmp = x + /*<bind>*/ (y = x = 2) /*</bind>*/ + (a = 2); int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(540171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540171")] [Fact] public void TestIncrement() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace1() { var results = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/ System.Console /*</bind>*/ .WriteLine(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace3() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A.B /*</bind>*/ .M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace4() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A /*</bind>*/ .B.M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact] public void DataFlowsOutIncrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(6359, "DevDiv_Projects/Roslyn")] [Fact] public void DataFlowsOutPreDecrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Test { string method(string s, int i) { string[] myvar = new string[i]; myvar[0] = s; /*<bind>*/myvar[--i] = s + i.ToString()/*</bind>*/; return myvar[i]; } }"); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x ? /*<bind>*/ x /*</bind>*/ : true; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540832")] [Fact] public void TestAssignmentExpressionAsBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x; int y = true ? /*<bind>*/ x = 1 /*</bind>*/ : x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestAlwaysAssignedWithTernaryOperator() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, x = 100; /*<bind>*/ int c = true ? a = 1 : b = 2; /*</bind>*/ } }"); Assert.Equal("a, c", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, x, c", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned05() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned06() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned07() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned08() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned09() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned10() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned11() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? (b = null) /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned12() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ a ?? (b = null) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned13() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? null /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned14() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : (d = a) ? (e = a) : /*<bind>*/ (f = a) /*</bind>*/; } }"); Assert.Equal("f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d, f", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned15() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : /*<bind>*/ (d = a) ? (e = a) : (f = a) /*</bind>*/; } }"); Assert.Equal("d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned16() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) && B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned17() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) && B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned18() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) || B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned19() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) || B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned22() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; if (/*<bind>*/B(out a)/*</bind>*/) a = true; else b = true; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssignedAndWrittenInside() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestWrittenInside03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ = 3; } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite02() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(out int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(out /*<bind>*/x/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(ref int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(ref /*<bind>*/x/*</bind>*/); } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = ( /*<bind>*/ x = 1 /*</bind>*/ ) + x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestSingleVariableSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ x /*</bind>*/ ; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestParenthesizedAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ (x = x) /*</bind>*/ | x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestRefArgumentSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = 0; Goo(ref /*<bind>*/ x /*</bind>*/ ); System.Console.WriteLine(x); } static void Goo(ref int x) { } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540066")] [Fact] public void AnalysisOfBadRef() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { /*<bind>*/Main(ref 1)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned20NullCoalescing() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static object B(out object b) { b = null; return b; } public static void Main(string[] args) { object a, b; object c = B(out a) ?? B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" struct STest { public static string SM() { const string s = null; var ss = ""Q""; var ret = /*<bind>*/( s ?? (ss = ""C""))/*</bind>*/ + ss; return ret; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNotNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class Test { public static string SM() { const string s = ""Not Null""; var ss = ""QC""; var ret = /*<bind>*/ s ?? ss /*</bind>*/ + ""\r\n""; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(8935, "DevDiv_Projects/Roslyn")] [Fact] public void TestDefaultOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public T GetT() { return /*<bind>*/ default(T) /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestTypeOfOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public short GetT(T t) { if (/*<bind>*/ typeof(T) == typeof(int) /*</bind>*/) return 123; return 456; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestIsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { if /*<bind>*/(t is string)/*</bind>*/ return ""SSS""; return null; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestAsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { string ret = null; if (t is string) ret = /*<bind>*/t as string/*</bind>*/; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(4028, "DevDiv_Projects/Roslyn")] [Fact] public void TestArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int y = 1; int[,] x = { { /*<bind>*/ y /*</bind>*/ } }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestImplicitStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc int[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; f(1); } } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; static void Main() { int r = f(1); } } "); Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), string.Join(", ", new string[] { "f" }.Concat((results2.ReadOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), string.Join(", ", new string[] { "f" }.Concat((results2.WrittenOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInSimpleFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; int z = /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; static void Main() { /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } } "); // NOTE: 'f' should not be reported in results1.AlwaysAssigned, this issue will be addressed separately Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), GetSymbolNamesJoined(results2.ReadOutside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), GetSymbolNamesJoined(results2.WrittenOutside)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { const int myLength = /*<bind>*/5/*</bind>*/; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression2() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { // NOTE: illegal, but still a region we should handle. const bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void FieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(542454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542454")] [Fact] public void IdentifierNameInObjectCreationExpr() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class myClass { static int Main() { myClass oc = new /*<bind>*/myClass/*</bind>*/(); return 0; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(542463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542463")] [Fact] public void MethodGroupInDelegateCreation() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class C { void Method() { System.Action a = new System.Action(/*<bind>*/Method/*</bind>*/); } } "); Assert.Equal("this", dataFlows.ReadInside.Single().Name); } [WorkItem(542771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542771")] [Fact] public void BindInCaseLabel() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class TestShapes { static void Main() { color s = color.blue; switch (s) { case true ? /*<bind>*/ color.blue /*</bind>*/ : color.blue: break; default: goto default; } } } enum color { blue, green }"); var tmp = dataFlows.VariablesDeclared; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542915, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542915")] [Fact] public void BindLiteralExprInEnumDecl() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" enum Number { Zero = /*<bind>*/0/*</bind>*/ } "); Assert.True(dataFlows.Succeeded); Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact] public void AssignToConst() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { const string a = null; /*<bind>*/a = null;/*</bind>*/ } } "); Assert.Equal("a", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x = 1; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAddressOfAssignedStructField2() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); // Really ??? Assert.Equal("s", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } // Make sure that assignment is consistent with address-of. [Fact] public void TestAssignToStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int x = /*<bind>*/s.x = 1/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(544314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544314")] public void TestOmittedLambdaPointerTypeParameter() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; unsafe public class Test { public delegate int D(int* p); public static void Main() { int i = 10; int* p = &i; D d = /*<bind>*/delegate { return *p;}/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("p", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("p", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, p, d", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = 1, y = 2 } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_InvalidAccess() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; int x = 0, y = 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, x, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed_InitializerExpressionSyntax() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_NestedObjectInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public int z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() { x = x, y = /*<bind>*/ { z = z } /*</bind>*/ }; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public delegate int D(); public D z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = { z = () => z } } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("z", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("z", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestWithExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable record B(string? X) { static void M1(B b1) { var x = ""hello""; _ = /*<bind>*/b1 with { X = x }/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<int> list = /*<bind>*/ new List<int>() { 1, 2, 3, 4, 5 } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() /*<bind>*/ { x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_ComplexElementInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() { /*<bind>*/ { x } /*</bind>*/ }; return 0; } } "); // Nice to have: "x" flows in, "x" read inside, "list, x" written outside. Assert.False(analysis.Succeeded); } [Fact] public void TestCollectionInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public delegate int D(); public static int Main() { int x = 1; List<D> list = new List<D>() /*<bind>*/ { () => x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void ObjectInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { C c = /*<bind>*/new C { dele = delegate(int x, int y) { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void CollectionInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { List<Func<int, int, int>> list = /*<bind>*/new List<Func<int, int, int>>() { (x, y) => { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact(), WorkItem(529329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529329")] public void QueryAsFieldInitializer() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; using System.Collections.Generic; using System.Collections; class Test { public IEnumerable e = /*<bind>*/ from x in new[] { 1, 2, 3 } where BadExpression let y = x.ToString() select y /*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(544361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544361")] [Fact] public void FullQueryExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System.Linq; class Program { static void Main(string[] args) { var q = /*<bind>*/from arg in args group arg by arg.Length into final select final/*</bind>*/; } }"); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverRead() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); var value = /*<bind>*/x.y/*</bind>*/.z.Value; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value = 3; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverReadAndWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void UnaryPlus() { // reported at https://social.msdn.microsoft.com/Forums/vstudio/en-US/f5078027-def2-429d-9fef-ab7f240883d2/writteninside-for-unary-operators?forum=roslyn var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Main { static int Main(int a) { /*<bind>*/ return +a; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void NullCoalescingAssignment() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowMultipleExpressions(@" public class C { public static void Main() { C c; c ??= new C(); object x1; object y1; /*<bind0>*/GetC(x1 = 1).Prop ??= (y1 = 2)/*</bind0>*/; x1.ToString(); y1.ToString(); object x2; object y2; /*<bind1>*/GetC(x2 = 1).Field ??= (y2 = 2)/*</bind1>*/; x2.ToString(); y2.ToString(); } static C GetC(object i) => null; object Prop { get; set; } object Field; } "); var propertyDataFlowAnalysis = dataFlowAnalysisResults.First(); var fieldDataFlowAnalysis = dataFlowAnalysisResults.Skip(1).Single(); assertAllInfo(propertyDataFlowAnalysis, "x1", "y1", "x2", "y2"); assertAllInfo(fieldDataFlowAnalysis, "x2", "y2", "x1", "y1"); void assertAllInfo(DataFlowAnalysis dataFlowAnalysis, string currentX, string currentY, string otherX, string otherY) { Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal(currentX, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x1, y1, x2, y2", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal($"c, {otherX}, {otherY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } } [Fact] public void CondAccess_NullCoalescing_DataFlow() { // This test corresponds to ExtractMethodTests.TestFlowStateNullableParameters3 var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { public string M() { string? a = null; string? b = null; return /*<bind>*/(a + b + a)?.ToString()/*</bind>*/ ?? string.Empty; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("this, a, b", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_01(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } x.ToString(); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_02(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } #endregion #region "Statements" [Fact] public void TestDataReadWrittenIncDecOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static short Main() { short x = 0, y = 1, z = 2; /*<bind>*/ x++; y--; /*</bind>*/ return y; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTernaryExpressionWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ int z = x ? y = 1 : y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { int i; return; /*<bind>*/ i = i + 1; /*</bind>*/ int j = i; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { string i = 0, j = 0, k = 0, l = 0; goto l1; /*<bind>*/ Console.WriteLine(i); j = 1; l1: Console.WriteLine(j); k = 1; goto l2; Console.WriteLine(k); l = 1; l3: Console.WriteLine(l); i = 1; /*</bind>*/ l2: Console.WriteLine(i + j + k + l); goto l3; } }"); Assert.Equal("j, l", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegionInExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression( @"class C { public static bool Main() { int i, j; return false && /*<bind>*/((i = i + 1) == 2 || (j = i) == 3)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [Fact] public void TestDeclarationWithSelfReferenceAndTernaryOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = true ? 1 : x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDeclarationWithTernaryOperatorAndAssignment() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x, z, y = true ? 1 : x = z; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x, z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDictionaryInitializer() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Goo() { int i, j; /*<bind>*/ var s = new Dictionary<int, int>() {[i = j = 1] = 2 }; /*</bind>*/ System.Console.WriteLine(i + j); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(542435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542435")] [Fact] public void NullArgsToAnalyzeControlFlowStatements() { var compilation = CreateCompilation(@" class C { static void Main() { int i = 10; } } "); var semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var statement = compilation.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().First(); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow((StatementSyntax)null)); } [WorkItem(542507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542507")] [Fact] public void DateFlowAnalyzeForLocalWithInvalidRHS() { // Case 1 var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Test { public delegate int D(); public void goo(ref D d) { /*<bind>*/ d = { return 10;}; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); // Case 2 analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Gen<T> { public void DefaultTest() { /*<bind>*/ object obj = default (new Gen<T>()); /*</bind>*/ } } "); Assert.Equal("obj", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestEntryPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F() { goto L1; // 1 /*<bind>*/ L1: ; /*</bind>*/ goto L1; // 2 } }"); Assert.Equal(1, analysis.EntryPoints.Count()); } [Fact] public void TestExitPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { L1: ; // 1 /*<bind>*/ if (x == 0) goto L1; if (x == 1) goto L2; if (x == 3) goto L3; L3: ; /*</bind>*/ L2: ; // 2 } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestRegionCompletesNormally01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ goto L1; /*</bind>*/ L1: ; } }"); Assert.True(analysis.StartPointIsReachable); Assert.False(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ x = 2; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ if (x == 0) return; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestVariablesDeclared01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a; /*<bind>*/ int b; int x, y = 1; { var z = ""a""; } /*</bind>*/ int c; } }"); Assert.Equal("b, x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestVariablesInitializedWithSelfReference() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int x = x = 1; int y, z = 1; /*</bind>*/ } }"); Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void AlwaysAssignedUnreachable() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int y; /*<bind>*/ if (x == 1) { y = 2; return; } else { y = 3; throw new Exception(); } /*</bind>*/ int = y; } }"); Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(538170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538170")] [Fact] public void TestVariablesDeclared02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) /*<bind>*/ { int a; int b; int x, y = 1; { string z = ""a""; } int c; } /*</bind>*/ }"); Assert.Equal("a, b, x, y, z, c", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [WorkItem(541280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541280")] [Fact] public void TestVariablesDeclared03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F() /*<bind>*/ { int a = 0; long a = 1; } /*</bind>*/ }"); Assert.Equal("a, a", GetSymbolNamesJoined(analysis.VariablesDeclared)); var intsym = analysis.VariablesDeclared.First() as ILocalSymbol; var longsym = analysis.VariablesDeclared.Last() as ILocalSymbol; Assert.Equal("Int32", intsym.Type.Name); Assert.Equal("Int64", longsym.Type.Name); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact] public void UnassignedVariableFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main(string[] args) { int i = 10; /*<bind>*/ int j = j + i; /*</bind>*/ Console.Write(i); Console.Write(j); } }"); Assert.Equal("j", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestDataFlowsIn01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 2; /*<bind>*/ int b = a + x + 3; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.DataFlowsIn)); } [Fact] public void TestOutParameter01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y; /*<bind>*/ if (x == 1) y = x = 2; /*</bind>*/ int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [WorkItem(538146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538146")] [Fact] public void TestDataFlowsOut02() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { /*<bind>*/ int s = 10, i = 1; int b = s + i; /*</bind>*/ System.Console.WriteLine(s); System.Console.WriteLine(i); } }"); Assert.Equal("s, i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut03() { var analysis = CompileAndAnalyzeDataFlowStatements( @"using System.Text; class Program { private static string Main() { StringBuilder builder = new StringBuilder(); /*<bind>*/ builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); /*</bind>*/ return builder.ToString(); } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut04() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut05() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; return; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut06() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 1; while (b) { /*<bind>*/ i = i + 1; /*</bind>*/ } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut07() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i; /*<bind>*/ i = 2; goto next; /*</bind>*/ next: int j = i; } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); } [WorkItem(540793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540793")] [Fact] public void TestDataFlowsOut08() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 2; try { /*<bind>*/ i = 1; /*</bind>*/ } finally { int j = i; } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut09() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { int i; string s; /*<bind>*/i = 10; s = args[0] + i.ToString();/*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut10() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { int x = 10; /*<bind>*/ int y; if (x == 10) y = 5; /*</bind>*/ Console.WriteLine(y); } } "); Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestAlwaysAssigned01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 1; /*<bind>*/ if (x == 2) a = 3; else a = 4; x = 4; if (x == 3) y = 12; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssigned02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ const int a = 1; /*</bind>*/ } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(540795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540795")] [Fact] public void TestAlwaysAssigned03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Always { public void F() { ushort x = 0, y = 1, z; /*<bind>*/ x++; return; uint z = y; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestReadInside01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this, t1", GetSymbolNamesJoined(analysis.ReadInside)); } [Fact] public void TestAlwaysAssignedDuplicateVariables() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a, a, b, b; b = 1; /*</bind>*/ } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAccessedInsideOutside() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, c, d, e, f, g, h, i; a = 1; c = b = a + x; /*<bind>*/ d = c; e = f = d; /*</bind>*/ g = e; h = i = g; } }"); Assert.Equal("c, d", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("d, e, f", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, a, e, g", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, b, c, g, h, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAlwaysAssignedThroughParenthesizedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a = 1, b, c, d, e; b = 2; (c) = 3; ((d)) = 4; /*</bind>*/ } }"); Assert.Equal("a, b, c, d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedThroughCheckedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int e, f, g; checked(e) = 5; (unchecked(f)) = 5; /*</bind>*/ } }"); Assert.Equal("e, f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedUsingAlternateNames() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int green, blue, red, yellow, brown; @green = 1; blu\u0065 = 2; re܏d = 3; yellow\uFFF9 = 4; @brown\uFFF9 = 5; /*</bind>*/ } }"); Assert.Equal("green, blue, red, yellow, brown", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedViaPassingAsOutParameter() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a; G(out a); /*</bind>*/ } void G(out int x) { x = 1; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedWithExcludedAssignment() { var analysis = CompileAndAnalyzeDataFlowStatements(@" partial class C { public void F(int x) { /*<bind>*/ int a, b; G(a = x = 1); H(b = 2); /*</bind>*/ } partial void G(int x); partial void H(int x); partial void H(int x) { } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestDeclarationWithSelfReference() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (x) y = 1; else y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithNonConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true | x) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestNonStatementSelection() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // // /*<bind>*/ //int // /*</bind>*/ // x = 1; // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.True(controlFlowAnalysisResults.Succeeded); // Assert.True(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [Fact] public void TestInvocation() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x); /*</bind>*/ } static void Goo(int x) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestInvocationWithAssignmentInArguments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x = y, y = 2); /*</bind>*/ int z = x + y; } static void Goo(int x, int y) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidLocalDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; public class MyClass { public static int Main() { variant /*<bind>*/ v = new byte(2) /*</bind>*/; // CS0246 byte b = v; // CS1729 return 1; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidKeywordAsExpr() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class B : A { public float M() { /*<bind>*/ { return base; // CS0175 } /*</bind>*/ } } class A {} "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); } [WorkItem(539071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539071")] [Fact] public void AssertFromFoldConstantEnumConversion() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" enum E { x, y, z } class Test { static int Main() { /*<bind>*/ E v = E.x; if (v != (E)((int)E.z - 1)) return 0; /*</bind>*/ return 1; } } "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); } [Fact] public void ByRefParameterNotInAppropriateCollections2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(ref T t) { /*<bind>*/ T t1 = GetValue<T>(ref t); /*</bind>*/ System.Console.WriteLine(t1.ToString()); } T GetValue<T>(ref T t) { return t; } } "); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void UnreachableDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F() { /*<bind>*/ int x; /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Parameters01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F(int x, ref int y, out int z) { /*<bind>*/ y = z = 3; /*</bind>*/ } } "); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528308")] [Fact] public void RegionForIfElseIfWithoutElse() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class Test { ushort TestCase(ushort p) { /*<bind>*/ if (p > 0) { return --p; } else if (p < 0) { return ++p; } /*</bind>*/ // else { return 0; } } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(2, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestBadRegion() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // int a = 1; // int b = 1; // // if(a > 1) // /*<bind>*/ // a = 1; // b = 2; // /*</bind>*/ // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.False(controlFlowAnalysisResults.Succeeded); // Assert.False(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [WorkItem(541331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541331")] [Fact] public void AttributeOnAccessorInvalid() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class C { public class AttributeX : Attribute { } public int Prop { get /*<bind>*/{ return 1; }/*</bind>*/ protected [AttributeX] set { } } } "); var controlFlowAnalysisResults = analysisResults.Item1; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); } [WorkItem(541585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541585")] [Fact] public void BadAssignThis() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class Program { static void Main(string[] args) { /*<bind>*/ this = new S(); /*</bind>*/ } } struct S { }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528623")] [Fact] public void TestElementAccess01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" public class Test { public void M(long[] p) { var v = new long[] { 1, 2, 3 }; /*<bind>*/ v[0] = p[0]; p[0] = v[1]; /*</bind>*/ v[1] = v[0]; p[2] = p[0]; } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.DataFlowsIn)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadInside)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, p, v", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(541947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541947")] [Fact] public void BindPropertyAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.False(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(8926, "DevDiv_Projects/Roslyn")] [WorkItem(542346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542346")] [WorkItem(528775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528775")] [Fact] public void BindEventAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public delegate void D(); public event D E { add { /*NA*/ } remove /*<bind>*/ { /*NA*/ } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(541980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541980")] [Fact] public void BindDuplicatedAccessor() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get { return 1;} get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; var tmp = ctrlFlows.EndPointIsReachable; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(543737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543737")] [Fact] public void BlockSyntaxInAttributeDecl() { { var compilation = CreateCompilation(@" [Attribute(delegate.Class)] public class C { public static int Main () { return 1; } } "); var tree = compilation.SyntaxTrees.First(); var index = tree.GetCompilationUnitRoot().ToFullString().IndexOf(".Class)", StringComparison.Ordinal); var tok = tree.GetCompilationUnitRoot().FindToken(index); var node = tok.Parent as StatementSyntax; Assert.Null(node); } { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" [Attribute(x => { /*<bind>*/int y = 12;/*</bind>*/ })] public class C { public static int Main () { return 1; } } "); Assert.False(results.Item1.Succeeded); Assert.False(results.Item2.Succeeded); } } [Fact, WorkItem(529273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529273")] public void IncrementDecrementOnNullable() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class C { void M(ref sbyte p1, ref sbyte? p2) { byte? local_0 = 2; short? local_1; ushort non_nullable = 99; /*<bind>*/ p1++; p2 = (sbyte?) (local_0.Value - 1); local_1 = (byte)(p2.Value + 1); var ret = local_1.HasValue ? local_1.Value : 0; --non_nullable; /*</bind>*/ } } "); Assert.Equal("ret", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p1, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p1, p2, local_0, local_1, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p1, p2, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(17971, "https://github.com/dotnet/roslyn/issues/17971")] [Fact] public void VariablesDeclaredInBrokenForeach() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { static void Main(string[] args) { /*<bind>*/ Console.WriteLine(1); foreach () Console.WriteLine(2); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] [WorkItem(4950, "https://github.com/dotnet/roslyn/issues/4950")] public void RegionWithUnsafeBlock() { var source = @"using System; class Program { static void Main(string[] args) { object value = args; // start IntPtr p; unsafe { object t = value; p = IntPtr.Zero; } // end Console.WriteLine(p); } } "; foreach (string keyword in new[] { "unsafe", "checked", "unchecked" }) { var compilation = CreateCompilation(source.Replace("unsafe", keyword)); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var stmt1 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString() == "IntPtr p;").Single(); var stmt2 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString().StartsWith(keyword)).First(); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt1, stmt2); Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, value, p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("args, p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } #endregion #region "lambda" [Fact] [WorkItem(41600, "https://github.com/dotnet/roslyn/pull/41600")] public void DataFlowAnalysisLocalFunctions10() { var dataFlow = CompileAndAnalyzeDataFlowExpression(@" class C { public void M() { bool Dummy(params object[] x) {return true;} try {} catch when (/*<bind>*/TakeOutParam(out var x1)/*</bind>*/ && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } } "); Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this, x1", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this, x1, x4, x4, x6, x7, x7, x8, x9, x9, y10, x14, x15, x, x", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this, x, x4, x4, x6, x7, x7, x8, x9, x9, x10, " + "y10, x14, x14, x15, x15, x, y, x", GetSymbolNamesJoined(dataFlow.WrittenOutside)); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void DataFlowAnalysisLocalFunctions9() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { int Testing; void M() { local(); /*<bind>*/ NewMethod(); /*</bind>*/ Testing = 5; void local() { } } void NewMethod() { } }"); var dataFlow = results.dataFlowAnalysis; Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.WrittenOutside)); var controlFlow = results.controlFlowAnalysis; Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions01() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.False(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions02() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ local(); System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions03() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ local(); void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions04() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { System.Console.WriteLine(0); local(); void local() { /*<bind>*/ throw null; /*</bind>*/ } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions05() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); void local() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions06() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { void local() { throw null; } /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] public void TestReturnStatements03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; /*<bind>*/ if (x == 1) return; Func<int,int> f = (int i) => { return i+1; }; if (x == 2) return; /*</bind>*/ } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements04() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; Func<int,int> f = (int i) => { /*<bind>*/ return i+1; /*</bind>*/ } ; if (x == 2) return; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements05() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; /*<bind>*/ Func<int,int?> f = (int i) => { return i == 1 ? i+1 : null; } ; /*</bind>*/ if (x == 2) return; } }"); Assert.True(analysis.Succeeded); Assert.Empty(analysis.ReturnStatements); } [Fact] public void TestReturnStatements06() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(uint? x) { if (x == null) return; if (x.Value == 1) return; /*<bind>*/ Func<uint?, ulong?> f = (i) => { return i.Value +1; } ; if (x.Value == 2) return; /*</bind>*/ } }"); Assert.True(analysis.Succeeded); Assert.Equal(1, analysis.ExitPoints.Count()); } [WorkItem(541198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541198")] [Fact] public void TestReturnStatements07() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public int F(int x) { Func<int,int> f = (int i) => { goto XXX; /*<bind>*/ return 1; /*</bind>*/ } ; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestMultipleLambdaExpressions() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { int i; N(/*<bind>*/() => { M(); }/*</bind>*/, () => { i++; }); } void N(System.Action x, System.Action y) { } }"); Assert.True(analysis.Succeeded); Assert.Equal("this, i", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReturnFromLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main(string[] args) { int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, lambda", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void DataFlowsOutLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; return; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda02() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main() { int? i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ return; }; int j = i.Value; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda03() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact] public void TestReadInside02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void Method() { System.Func<int, int> a = x => /*<bind>*/x * x/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, a, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestCaptured02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; class C { int field = 123; public void F(int x) { const int a = 1, y = 1; /*<bind>*/ Func<int> lambda = () => x + y + field; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y, lambda", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact, WorkItem(539648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539648"), WorkItem(529185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529185")] public void ReturnsInsideLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate R Func<T, R>(T t); static void Main(string[] args) { /*<bind>*/ Func<int, int> f = (arg) => { int s = 3; return s; }; /*</bind>*/ f.Invoke(2); } }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.ReturnStatements); Assert.Equal("f", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, f", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("f, arg, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { /*<bind>*/ TestDelegate testDel = (ref int x) => { }; /*</bind>*/ int p = 2; testDel(ref p); Console.WriteLine(p); } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, testDel", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda02() { var results1 = CompileAndAnalyzeDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int? x); static void Main() { /*<bind>*/ TestDelegate testDel = (ref int? x) => { int y = x; x.Value = 10; }; /*</bind>*/ int? p = 2; testDel(ref p); Console.WriteLine(p); } } "); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.VariablesDeclared)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results1.ReadInside)); Assert.Equal("testDel, p", GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("p", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(540449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540449")] [Fact] public void AnalysisInsideLambdas() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; } } "); Assert.Equal("x", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.ReadInside)); Assert.Null(GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("f, p, x, y", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(528622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528622")] [Fact] public void AlwaysAssignedParameterLambda() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; internal class Test { void M(sbyte[] ary) { /*<bind>*/ ( (Action<short>)(x => { Console.Write(x); }) )(ary[0])/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("ary", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("ary, x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(541946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541946")] [Fact] public void LambdaInTernaryWithEmptyBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public delegate void D(); public class A { void M() { int i = 0; /*<bind>*/ D d = true ? (D)delegate { i++; } : delegate { }; /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, i, d", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("i, d", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void ForEachVariableInLambda() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { var nums = new int?[] { 4, 5 }; foreach (var num in /*<bind>*/nums/*</bind>*/) { Func<int, int> f = x => x + num.Value; Console.WriteLine(f(0)); } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543398")] [Fact] public void LambdaBlockSyntax() { var source = @" using System; class c1 { void M() { var a = 0; foreach(var l in """") { Console.WriteLine(l); a = (int) l; l = (char) a; } Func<int> f = ()=> { var c = a; a = c; return 0; }; var b = 0; Console.WriteLine(b); } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CSharpCompilation.Create("FlowAnalysis", syntaxTrees: new[] { tree }); var model = comp.GetSemanticModel(tree); var methodBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().First(); var foreachStatement = methodBlock.DescendantNodes().OfType<ForEachStatementSyntax>().First(); var foreachBlock = foreachStatement.DescendantNodes().OfType<BlockSyntax>().First(); var lambdaExpression = methodBlock.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().First(); var lambdaBlock = lambdaExpression.DescendantNodes().OfType<BlockSyntax>().First(); var flowAnalysis = model.AnalyzeDataFlow(methodBlock); Assert.Equal(4, flowAnalysis.ReadInside.Count()); Assert.Equal(5, flowAnalysis.WrittenInside.Count()); Assert.Equal(5, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(foreachBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(0, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(lambdaBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(1, flowAnalysis.VariablesDeclared.Count()); } [Fact] public void StaticLambda_01() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => Console.Write(x); fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,48): error CS8820: A static anonymous function cannot contain a reference to 'x'. // Action fn = static () => Console.Write(x); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(9, 48) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_02() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,21): error CS8820: A static anonymous function cannot contain a reference to 'x'. // int y = x; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 21), // (12,13): error CS8820: A static anonymous function cannot contain a reference to 'x'. // x = 43; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(12, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_03() { var source = @" using System; class C { public static int x = 42; static void Main() { Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "42"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } } #endregion #region "query expressions" [Fact] public void QueryExpression01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; /*<bind>*/ var q2 = from x in nums where (x > 2) where x > 3 select x; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("q2", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, q2", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from x in nums where (x > 2) select /*<bind>*/ x+1 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int?[] { 1, 2, null, 4 }; var q2 = from x in nums group x.Value + 1 by /*<bind>*/ x.Value % 2 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new uint[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 select /*<bind>*/ x /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 group /*<bind>*/ x /*</bind>*/ by x%2; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541916")] [Fact] public void ForEachVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; foreach (var num in nums) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541945")] [Fact] public void ForVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; for (int num = 0; num < 10; num++) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541926")] [Fact] public void Bug8863() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System.Linq; class C { static void Main(string[] args) { /*<bind>*/ var temp = from x in ""abc"" let z = x.ToString() select z into w select w; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("temp", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, temp", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Bug9415() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q1 = from x in new int[] { /*<bind>*/4/*</bind>*/, 5 } orderby x select x; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, q1, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543546")] [Fact] public void GroupByClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main() { var strings = new string[] { }; var q = from s in strings select s into t /*<bind>*/group t by t.Length/*</bind>*/; } }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] [Fact] public void CaptureInQuery() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main(int[] data) { int y = 1; { int x = 2; var f2 = from a in data select a + y; var f3 = from a in data where x > 0 select a; var f4 = from a in data let b = 1 where /*<bind>*/M(() => b)/*</bind>*/ select a + b; var f5 = from c in data where M(() => c) select c; } } private static bool M(Func<int> f) => true; }"); var dataFlowAnalysisResults = analysisResults; Assert.Equal("y, x, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } #endregion query expressions #region "switch statement tests" [Fact] public void LocalInOtherSwitchCase() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; using System.Linq; public class Test { public static void Main() { int ret = 6; switch (ret) { case 1: int i = 10; break; case 2: var q1 = from j in new int[] { 3, 4 } select /*<bind>*/i/*</bind>*/; break; } } }"); Assert.Empty(dataFlows.DataFlowsOut); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void VariableDeclInsideSwitchCaptureInLambdaExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { public static void Main() { switch (10) { default: int i = 10; Func<int> f1 = () => /*<bind>*/i/*</bind>*/; break; } } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, f1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541710")] [Fact] public void ArrayCreationExprInForEachInsideSwitchSection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': foreach (var i100 in new int[] {4, /*<bind>*/5/*</bind>*/ }) { } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("i100", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void RegionInsideSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': switch (/*<bind>*/'2'/*</bind>*/) { case '2': break; } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void NullableAsSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class C { public void F(ulong? p) { /*<bind>*/ switch (p) { case null: break; case 1: goto case null; default: break; } /*</bind>*/ } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(17281, "https://github.com/dotnet/roslyn/issues/17281")] public void DiscardVsVariablesDeclared() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class A { } class Test { private void Repro(A node) { /*<bind>*/ switch (node) { case A _: break; case Unknown: break; default: return; } /*</bind>*/ } }"); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion #region "Misc." [Fact, WorkItem(11298, "DevDiv_Projects/Roslyn")] public void BaseExpressionSyntax() { var source = @" using System; public class BaseClass { public virtual void MyMeth() { } } public class MyClass : BaseClass { public override void MyMeth() { base.MyMeth(); } delegate BaseClass D(); public void OtherMeth() { D f = () => base; } public static void Main() { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(invocation); Assert.Empty(flowAnalysis.Captured); Assert.Empty(flowAnalysis.CapturedInside); Assert.Empty(flowAnalysis.CapturedOutside); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("MyClass this", flowAnalysis.WrittenOutside.Single().ToTestDisplayString()); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); flowAnalysis = model.AnalyzeDataFlow(lambda); Assert.Equal("MyClass this", flowAnalysis.Captured.Single().ToTestDisplayString()); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("this, f", GetSymbolNamesJoined(flowAnalysis.WrittenOutside)); } [WorkItem(543101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543101")] [Fact] public void AnalysisInsideBaseClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { A(int x) : this(/*<bind>*/x.ToString()/*</bind>*/) { } A(string x) { } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543758")] [Fact] public void BlockSyntaxOfALambdaInAttributeArg() { var controlFlowAnalysisResults = CompileAndAnalyzeControlFlowStatements(@" class Test { [Attrib(() => /*<bind>*/{ }/*</bind>*/)] public static void Main() { } } "); Assert.False(controlFlowAnalysisResults.Succeeded); } [WorkItem(529196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529196")] [Fact()] public void DefaultValueOfOptionalParam() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" public class Derived { public void Goo(int x = /*<bind>*/ 2 /*</bind>*/) { } } "); Assert.True(dataFlowAnalysisResults.Succeeded); } [Fact] public void GenericStructureCycle() { var source = @"struct S<T> { public S<S<T>> F; } class C { static void M() { S<object> o; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("S<object> o", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Equal("o", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(545372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545372")] [Fact] public void AnalysisInSyntaxError01() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; class Program { static void Main(string[] args) { Expression<Func<int>> f3 = () => if (args == null) {}; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("if", StringComparison.Ordinal)); Assert.Equal("if (args == null) {}", statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, f3", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(546964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546964")] [Fact] public void AnalysisWithMissingMember() { var source = @"class C { void Goo(string[] args) { foreach (var s in args) { this.EditorOperations = 1; } } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("EditorOperations", StringComparison.Ordinal)); Assert.Equal("this.EditorOperations = 1;", statement.ToString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); var v = analysis.DataFlowsOut; } [Fact, WorkItem(547059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547059")] public void ObjectInitIncompleteCodeInQuery() { var source = @" using System.Collections.Generic; using System.Linq; class Program { static void Main() { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } public interface ISymbol { } public class ExportedSymbol { public ISymbol Symbol; public byte UseBits; } "; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().FirstOrDefault(); var expectedtext = @" { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } "; Assert.Equal(expectedtext, statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void StaticSetterAssignedInCtor() { var source = @"class C { C() { P = new object(); } static object P { get; set; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("P = new object()", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void FieldBeforeAssignedInStructCtor() { var source = @"struct S { object value; S(object x) { S.Equals(value , value); this.value = null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0170: Use of possibly unassigned field 'value' // S.Equals(value , value); Diagnostic(ErrorCode.ERR_UseDefViolationField, "value").WithArguments("value") ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var expression = GetLastNode<ExpressionSyntax>(tree, root.ToFullString().IndexOf("value ", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(expression); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact, WorkItem(14110, "https://github.com/dotnet/roslyn/issues/14110")] public void Test14110() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { var (a0, b0) = (1, 2); (var c0, int d0) = (3, 4); bool e0 = a0 is int f0; bool g0 = a0 is var h0; M(out int i0); M(out var j0); /*<bind>*/ var (a, b) = (1, 2); (var c, int d) = (3, 4); bool e = a is int f; bool g = a is var h; M(out int i); M(out var j); /*</bind>*/ var (a1, b1) = (1, 2); (var c1, int d1) = (3, 4); bool e1 = a1 is int f1; bool g1 = a1 is var h1; M(out int i1); M(out var j1); } static void M(out int z) => throw null; } "); Assert.Equal("a, b, c, d, e, f, g, h, i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact, WorkItem(15640, "https://github.com/dotnet/roslyn/issues/15640")] public void Test15640() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class Programand { static void Main() { foreach (var (a0, b0) in new[] { (1, 2) }) {} /*<bind>*/ foreach (var (a, b) in new[] { (1, 2) }) {} /*</bind>*/ foreach (var (a1, b1) in new[] { (1, 2) }) {} } } "); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] public void RegionAnalysisLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Local(); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Action a = Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = new Action(Local); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } Local(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { var a = new Action(() => { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } }); a(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = (Action)Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { int x = 0; void Local() { x++; } Local(); /*<bind>*/ x++; x = M(x + 1); /*</bind>*/ } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture1() { var results = CompileAndAnalyzeDataFlowStatements(@" public static class SomeClass { private static void Repro( int arg ) { /*<bind>*/int localValue = arg;/*</bind>*/ int LocalCapture() => arg; } }"); Assert.True(results.Succeeded); Assert.Equal("arg", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("arg", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("arg", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("arg, localValue", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("localValue", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("localValue", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture2() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; Local(); /*<bind>*/int y = x;/*</bind>*/ int Local() { x = 0; } } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture3() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; /*<bind>*/int y = x;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture4() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x, y = 0; /*<bind>*/x = y;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this, y", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { int x = 0; void M() { /*<bind>*/ int L(int a) => x; /*</bind>*/ L(); } }"); Assert.Equal("this", GetSymbolNamesJoined(results.Captured)); Assert.Equal("this", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M(int x) { int y; int z; void Local() { /*<bind>*/ x++; y = 0; y++; /*</bind>*/ } Local(); } }"); Assert.Equal("x, y", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x, y", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); // TODO(https://github.com/dotnet/roslyn/issues/14214): This is wrong. // Both x and y should flow out. Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact] public void LocalFuncCapture7() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; void L() { /*<bind>*/ int y = 0; y++; x = 0; /*</bind>*/ } x++; } }"); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture8() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture9() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; Inside(); /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void AssignmentInsideLocal01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 1) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if (false) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // This is a conservative approximation, ignoring whether the branch containing // the assignment is reachable Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ x = 1; } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] [WorkItem(39569, "https://github.com/dotnet/roslyn/issues/39569")] public void AssignmentInsideLocal05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { x = 1; } /*<bind>*/ Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); // Right now region analysis requires bound nodes for each variable and value being // assigned. This doesn't work with the current local function analysis because we only // store the slots, not the full boundnode of every assignment (which is impossible // anyway). This should be: // Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal06() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } /*</bind>*/ Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal07() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal08() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal09() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; throw new Exception(); } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // N.B. This is not as precise as possible. The branch assigning y is unreachable, so // the result does not technically flow out. This is a conservative approximation. Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true when true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact] public void AnalysisOfTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = /*<bind>*/(x, y) == (x = 0, 1)/*</bind>*/; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfNestedTupleInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, (2, 3)) == (0, /*<bind>*/(x = 0, y)/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfExpressionInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, 2) == (0, /*<bind>*/(x = 0) + y/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfMixedDeconstruction() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { bool M() { int x = 0; string y; /*<bind>*/ (x, (y, var z)) = (x, ("""", true)) /*</bind>*/ return z; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer01() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(nameof(P), /*<bind>*/x => true/*</bind>*/); static object Create(string name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer02() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(P, /*<bind>*/x => true/*</bind>*/); static object Create(object name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(19845, "https://github.com/dotnet/roslyn/issues/19845")] public void CodeInInitializer03() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static int X { get; set; } int Y = /*<bind>*/X/*</bind>*/; }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(26028, "https://github.com/dotnet/roslyn/issues/26028")] public void BrokenForeach01() { var source = @"class C { void M() { foreach (var x } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); // The foreach loop is broken, so its embedded statement is filled in during syntax error recovery. It is zero-width. var stmt = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<ForEachStatementSyntax>().Single().Statement; Assert.Equal(0, stmt.Span.Length); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(30548, "https://github.com/dotnet/roslyn/issues/30548")] public void SymbolInDataFlowInButNotInReadInside() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; /*<bind>*/if (a) { return; } if (A == a) { test = new object(); }/*</bind>*/ } } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(37427, "https://github.com/dotnet/roslyn/issues/37427")] public void RegionWithLocalFunctions() { // local functions inside the region var s1 = @" class A { static void M(int p) { int i, j; i = 1; /*<bind>*/ int L1() => 1; int k; j = i; int L2() => 2; /*</bind>*/ k = j; } } "; // local functions outside the region var s2 = @" class A { static void M(int p) { int i, j; i = 1; int L1() => 1; /*<bind>*/ int k; j = i; /*</bind>*/ int L2() => 2; k = j; } } "; foreach (var s in new[] { s1, s2 }) { var analysisResults = CompileAndAnalyzeDataFlowStatements(s); var dataFlowAnalysisResults = analysisResults; Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("k", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("p, i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } [Fact] public void TestAddressOfUnassignedStructLocal_02() { // This test demonstrates that "data flow analysis" pays attention to private fields // of structs imported from metadata. var libSource = @" public struct Struct { private string Field; }"; var libraryReference = CreateCompilation(libSource).EmitToImageReference(); var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { Struct x; // considered not definitely assigned because it has a field Struct * px = /*<bind>*/&x/*</bind>*/; // address taken of an unassigned variable } } ", libraryReference); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } #endregion #region "Used Local Functions" [Fact] public void RegionAnalysisUsedLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } void Unused(){ } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ System.Action a = new System.Action(Local); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions9() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions10() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions11() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions12() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions13() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions14() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions15() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions16() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions17() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions18() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions19() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions20() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions21() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions22() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions23() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } #endregion #region "Top level statements" [Fact] public void TestTopLevelStatements() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; /*<bind>*/ Console.Write(1); Console.Write(2); Console.Write(3); Console.Write(4); Console.Write(5); /*</bind>*/ "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_Lambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_LambdaCapturingArgs() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; Func<int> lambda = () => { /*<bind>*/return args.Length;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Compilers/Core/Portable/Symbols/IPreprocessingSymbol.cs
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// Represents a preprocessing conditional compilation symbol. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPreprocessingSymbol : ISymbol { } }
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// Represents a preprocessing conditional compilation symbol. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPreprocessingSymbol : ISymbol { } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEConstructorSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { /// <summary> /// Synthesized expression evaluation method. /// </summary> internal sealed class EEConstructorSymbol : SynthesizedInstanceConstructor { internal EEConstructorSymbol(NamedTypeSymbol containingType) : base(containingType) { } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var noLocals = ImmutableArray<LocalSymbol>.Empty; var initializerInvocation = MethodCompiler.BindImplicitConstructorInitializer(this, diagnostics, compilationState.Compilation); var syntax = initializerInvocation.Syntax; compilationState.AddSynthesizedMethod(this, new BoundBlock( syntax, noLocals, ImmutableArray.Create<BoundStatement>( new BoundExpressionStatement(syntax, initializerInvocation), new BoundReturnStatement(syntax, RefKind.None, null)))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { /// <summary> /// Synthesized expression evaluation method. /// </summary> internal sealed class EEConstructorSymbol : SynthesizedInstanceConstructor { internal EEConstructorSymbol(NamedTypeSymbol containingType) : base(containingType) { } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var noLocals = ImmutableArray<LocalSymbol>.Empty; var initializerInvocation = MethodCompiler.BindImplicitConstructorInitializer(this, diagnostics, compilationState.Compilation); var syntax = initializerInvocation.Syntax; compilationState.AddSynthesizedMethod(this, new BoundBlock( syntax, noLocals, ImmutableArray.Create<BoundStatement>( new BoundExpressionStatement(syntax, initializerInvocation), new BoundReturnStatement(syntax, RefKind.None, null)))); } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Compilers/CSharp/Portable/Symbols/Attributes/AttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Reflection; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using Microsoft.CodeAnalysis; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an attribute applied to a Symbol. /// </summary> internal abstract partial class CSharpAttributeData : AttributeData { private ThreeState _lazyIsSecurityAttribute = ThreeState.Unknown; /// <summary> /// Gets the attribute class being applied. /// </summary> public new abstract NamedTypeSymbol? AttributeClass { get; } /// <summary> /// Gets the constructor used in this application of the attribute. /// </summary> public new abstract MethodSymbol? AttributeConstructor { get; } /// <summary> /// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols. /// </summary> public new abstract SyntaxReference? ApplicationSyntaxReference { get; } // Overridden to be able to apply MemberNotNull to the new members [MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))] internal override bool HasErrors { get { var hasErrors = base.HasErrors; if (!hasErrors) { Debug.Assert(AttributeClass is not null); Debug.Assert(AttributeConstructor is not null); } return hasErrors; } } /// <summary> /// Gets the list of constructor arguments specified by this application of the attribute. This list contains both positional arguments /// and named arguments that are formal parameters to the constructor. /// </summary> public new IEnumerable<TypedConstant> ConstructorArguments { get { return this.CommonConstructorArguments; } } /// <summary> /// Gets the list of named field or property value arguments specified by this application of the attribute. /// </summary> public new IEnumerable<KeyValuePair<string, TypedConstant>> NamedArguments { get { return this.CommonNamedArguments; } } /// <summary> /// Compares the namespace and type name with the attribute's namespace and type name. /// Returns true if they are the same. /// </summary> internal virtual bool IsTargetAttribute(string namespaceName, string typeName) { Debug.Assert(this.AttributeClass is object); if (!this.AttributeClass.Name.Equals(typeName)) { return false; } if (this.AttributeClass.IsErrorType() && !(this.AttributeClass is MissingMetadataTypeSymbol)) { // Can't guarantee complete name information. return false; } return this.AttributeClass.HasNameQualifier(namespaceName); } internal bool IsTargetAttribute(Symbol targetSymbol, AttributeDescription description) { return GetTargetAttributeSignatureIndex(targetSymbol, description) != -1; } internal abstract int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description); /// <summary> /// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description /// and the attribute description has a signature with parameter count equal to the given attribute syntax's argument list count. /// NOTE: We don't allow early decoded attributes to have optional parameters. /// </summary> internal static bool IsTargetEarlyAttribute(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax, AttributeDescription description) { Debug.Assert(!attributeType.IsErrorType()); int argumentCount = (attributeSyntax.ArgumentList != null) ? attributeSyntax.ArgumentList.Arguments.Count<AttributeArgumentSyntax>((arg) => arg.NameEquals == null) : 0; return AttributeData.IsTargetEarlyAttribute(attributeType, argumentCount, description); } // Security attributes, i.e. attributes derived from well-known SecurityAttribute, are matched by type, not constructor signature. internal bool IsSecurityAttribute(CSharpCompilation compilation) { if (_lazyIsSecurityAttribute == ThreeState.Unknown) { Debug.Assert(!this.HasErrors); // CLI spec (Partition II Metadata), section 21.11 "DeclSecurity : 0x0E" states: // SPEC: If the attribute's type is derived (directly or indirectly) from System.Security.Permissions.SecurityAttribute then // SPEC: it is a security custom attribute and requires special treatment. // NOTE: The native C# compiler violates the above and considers only those attributes whose type derives from // NOTE: System.Security.Permissions.CodeAccessSecurityAttribute as security custom attributes. // NOTE: We will follow the specification. // NOTE: See Devdiv Bug #13762 "Custom security attributes deriving from SecurityAttribute are not treated as security attributes" for details. // Well-known type SecurityAttribute is optional. // Native compiler doesn't generate a use-site error if it is not found, we do the same. var wellKnownType = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAttribute); Debug.Assert(AttributeClass is object); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _lazyIsSecurityAttribute = AttributeClass.IsDerivedFrom(wellKnownType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo).ToThreeState(); } return _lazyIsSecurityAttribute.Value(); } // for testing and debugging only /// <summary> /// Returns the <see cref="System.String"/> that represents the current AttributeData. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current AttributeData.</returns> public override string? ToString() { if (this.AttributeClass is object) { string className = this.AttributeClass.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); if (!this.CommonConstructorArguments.Any() & !this.CommonNamedArguments.Any()) { return className; } var pooledStrbuilder = PooledStringBuilder.GetInstance(); StringBuilder stringBuilder = pooledStrbuilder.Builder; stringBuilder.Append(className); stringBuilder.Append("("); bool first = true; foreach (var constructorArgument in this.CommonConstructorArguments) { if (!first) { stringBuilder.Append(", "); } stringBuilder.Append(constructorArgument.ToCSharpString()); first = false; } foreach (var namedArgument in this.CommonNamedArguments) { if (!first) { stringBuilder.Append(", "); } stringBuilder.Append(namedArgument.Key); stringBuilder.Append(" = "); stringBuilder.Append(namedArgument.Value.ToCSharpString()); first = false; } stringBuilder.Append(")"); return pooledStrbuilder.ToStringAndFree(); } return base.ToString(); } #region AttributeData Implementation /// <summary> /// Gets the attribute class being applied as an <see cref="INamedTypeSymbol"/> /// </summary> protected override INamedTypeSymbol? CommonAttributeClass { get { return this.AttributeClass.GetPublicSymbol(); } } /// <summary> /// Gets the constructor used in this application of the attribute as an <see cref="IMethodSymbol"/>. /// </summary> protected override IMethodSymbol? CommonAttributeConstructor { get { return this.AttributeConstructor.GetPublicSymbol(); } } /// <summary> /// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols. /// </summary> protected override SyntaxReference? CommonApplicationSyntaxReference { get { return this.ApplicationSyntaxReference; } } #endregion #region Attribute Decoding internal void DecodeSecurityAttribute<T>(Symbol targetSymbol, CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, ISecurityAttributeTarget, new() { Debug.Assert(!this.HasErrors); Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag); bool hasErrors; DeclarativeSecurityAction action = DecodeSecurityAttributeAction(targetSymbol, compilation, arguments.AttributeSyntaxOpt, out hasErrors, (BindingDiagnosticBag)arguments.Diagnostics); if (!hasErrors) { T data = arguments.GetOrCreateData<T>(); SecurityWellKnownAttributeData securityData = data.GetOrCreateData(); securityData.SetSecurityAttribute(arguments.Index, action, arguments.AttributesCount); if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PermissionSetAttribute)) { string? resolvedPathForFixup = DecodePermissionSetAttribute(compilation, arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics); if (resolvedPathForFixup != null) { securityData.SetPathForPermissionSetAttributeFixup(arguments.Index, resolvedPathForFixup, arguments.AttributesCount); } } } } internal static void DecodeSkipLocalsInitAttribute<T>(CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, ISkipLocalsInitAttributeTarget, new() { arguments.GetOrCreateData<T>().HasSkipLocalsInitAttribute = true; if (!compilation.Options.AllowUnsafe) { Debug.Assert(arguments.AttributeSyntaxOpt is object); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_IllegalUnsafe, arguments.AttributeSyntaxOpt.Location); } } internal static void DecodeMemberNotNullAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() { var value = arguments.Attribute.CommonConstructorArguments[0]; if (value.IsNull) { return; } if (value.Kind != TypedConstantKind.Array) { string? memberName = value.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { arguments.GetOrCreateData<T>().AddNotNullMember(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } else { var builder = ArrayBuilder<string>.GetInstance(); foreach (var member in value.Values) { var memberName = member.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { builder.Add(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } arguments.GetOrCreateData<T>().AddNotNullMember(builder); builder.Free(); } } private static void ReportBadNotNullMemberIfNeeded(TypeSymbol type, DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, string memberName) { foreach (Symbol foundMember in type.GetMembers(memberName)) { if (foundMember.Kind == SymbolKind.Field || foundMember.Kind == SymbolKind.Property) { return; } } Debug.Assert(arguments.AttributeSyntaxOpt is object); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.WRN_MemberNotNullBadMember, arguments.AttributeSyntaxOpt.Location, memberName); } internal static void DecodeMemberNotNullWhenAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() { var value = arguments.Attribute.CommonConstructorArguments[1]; if (value.IsNull) { return; } var sense = arguments.Attribute.CommonConstructorArguments[0].DecodeValue<bool>(SpecialType.System_Boolean); if (value.Kind != TypedConstantKind.Array) { var memberName = value.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } else { var builder = ArrayBuilder<string>.GetInstance(); foreach (var member in value.Values) { var memberName = member.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { builder.Add(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, builder); builder.Free(); } } private DeclarativeSecurityAction DecodeSecurityAttributeAction(Symbol targetSymbol, CSharpCompilation compilation, AttributeSyntax? nodeOpt, out bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert((object)targetSymbol != null); Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method); Debug.Assert(this.IsSecurityAttribute(compilation)); var ctorArgs = this.CommonConstructorArguments; if (!ctorArgs.Any()) { // NOTE: Security custom attributes must have a valid SecurityAction as its first argument, we have none here. // NOTE: Ideally, we should always generate 'CS7048: First argument to a security attribute must be a valid SecurityAction' for this case. // NOTE: However, native compiler allows applying System.Security.Permissions.HostProtectionAttribute attribute without any argument and uses // NOTE: SecurityAction.LinkDemand as the default SecurityAction in this case. We maintain compatibility with the native compiler for this case. // BREAKING CHANGE: Even though the native compiler intends to allow only HostProtectionAttribute to be applied without any arguments, // it doesn't quite do this correctly // The implementation issue leads to the native compiler allowing any user defined security attribute with a parameterless constructor and a named property argument as the first // attribute argument to have the above mentioned behavior, even though the comment clearly mentions that this behavior was intended only for the HostProtectionAttribute. // We currently allow this case only for the HostProtectionAttribute. In future if need arises, we can exactly match native compiler's behavior. if (this.IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute)) { hasErrors = false; return DeclarativeSecurityAction.LinkDemand; } } else { TypedConstant firstArg = ctorArgs.First(); var firstArgType = (TypeSymbol?)firstArg.TypeInternal; if (firstArgType is object && firstArgType.Equals(compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction))) { return DecodeSecurityAction(firstArg, targetSymbol, nodeOpt, diagnostics, out hasErrors); } } // CS7048: First argument to a security attribute must be a valid SecurityAction diagnostics.Add(ErrorCode.ERR_SecurityAttributeMissingAction, nodeOpt != null ? nodeOpt.Name.Location : NoLocation.Singleton); hasErrors = true; return DeclarativeSecurityAction.None; } private DeclarativeSecurityAction DecodeSecurityAction(TypedConstant typedValue, Symbol targetSymbol, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics, out bool hasErrors) { Debug.Assert((object)targetSymbol != null); Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method); Debug.Assert(typedValue.ValueInternal is object); int securityAction = (int)typedValue.ValueInternal; bool isPermissionRequestAction; switch (securityAction) { case (int)DeclarativeSecurityAction.InheritanceDemand: case (int)DeclarativeSecurityAction.LinkDemand: if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PrincipalPermissionAttribute)) { // CS7052: SecurityAction value '{0}' is invalid for PrincipalPermission attribute object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_PrincipalPermissionInvalidAction, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } isPermissionRequestAction = false; break; case 1: // Native compiler allows security action value 1 for security attributes on types/methods, even though there is no corresponding field in System.Security.Permissions.SecurityAction enum. // We will maintain compatibility. case (int)DeclarativeSecurityAction.Assert: case (int)DeclarativeSecurityAction.Demand: case (int)DeclarativeSecurityAction.PermitOnly: case (int)DeclarativeSecurityAction.Deny: isPermissionRequestAction = false; break; case (int)DeclarativeSecurityAction.RequestMinimum: case (int)DeclarativeSecurityAction.RequestOptional: case (int)DeclarativeSecurityAction.RequestRefuse: isPermissionRequestAction = true; break; default: { // CS7049: Security attribute '{0}' has an invalid SecurityAction value '{1}' object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidAction, syntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "", displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } // Validate security action for symbol kind if (isPermissionRequestAction) { if (targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method) { // Types and methods cannot take permission requests. // CS7051: SecurityAction value '{0}' is invalid for security attributes applied to a type or a method object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } else { if (targetSymbol.Kind == SymbolKind.Assembly) { // Assemblies cannot take declarative security. // CS7050: SecurityAction value '{0}' is invalid for security attributes applied to an assembly object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } hasErrors = false; return (DeclarativeSecurityAction)securityAction; } private static Location GetSecurityAttributeActionSyntaxLocation(AttributeSyntax? nodeOpt, TypedConstant typedValue, out object displayString) { if (nodeOpt == null) { displayString = ""; return NoLocation.Singleton; } var argList = nodeOpt.ArgumentList; if (argList == null || argList.Arguments.IsEmpty()) { // Optional SecurityAction parameter with default value. displayString = (FormattableString)$"{typedValue.ValueInternal}"; return nodeOpt.Location; } AttributeArgumentSyntax argSyntax = argList.Arguments[0]; displayString = argSyntax.ToString(); return argSyntax.Location; } /// <summary> /// Decodes PermissionSetAttribute applied in source to determine if it needs any fixup during codegen. /// </summary> /// <remarks> /// PermissionSetAttribute needs fixup when it contains an assignment to the 'File' property as a single named attribute argument. /// Fixup performed is ported from SecurityAttributes::FixUpPermissionSetAttribute. /// It involves following steps: /// 1) Verifying that the specified file name resolves to a valid path. /// 2) Reading the contents of the file into a byte array. /// 3) Convert each byte in the file content into two bytes containing hexadecimal characters. /// 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above. /// /// Step 1) is performed in this method, i.e. during binding. /// Remaining steps are performed during serialization as we want to avoid retaining the entire file contents throughout the binding/codegen pass. /// See <see cref="Microsoft.CodeAnalysis.CodeGen.PermissionSetAttributeWithFileReference"/> for remaining fixup steps. /// </remarks> /// <returns>String containing the resolved file path if PermissionSetAttribute needs fixup during codegen, null otherwise.</returns> private string? DecodePermissionSetAttribute(CSharpCompilation compilation, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); string? resolvedFilePath = null; var namedArgs = this.CommonNamedArguments; if (namedArgs.Length == 1) { var namedArg = namedArgs[0]; Debug.Assert(AttributeClass is object); NamedTypeSymbol attrType = this.AttributeClass; string filePropName = PermissionSetAttributeWithFileReference.FilePropertyName; string hexPropName = PermissionSetAttributeWithFileReference.HexPropertyName; if (namedArg.Key == filePropName && PermissionSetAttributeTypeHasRequiredProperty(attrType, filePropName)) { // resolve file prop path var fileName = (string?)namedArg.Value.ValueInternal; var resolver = compilation.Options.XmlReferenceResolver; resolvedFilePath = (resolver != null && fileName != null) ? resolver.ResolveReference(fileName, baseFilePath: null) : null; if (resolvedFilePath == null) { // CS7053: Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute Location argSyntaxLocation = nodeOpt?.GetNamedArgumentSyntax(filePropName)?.Location ?? NoLocation.Singleton; diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeInvalidFile, argSyntaxLocation, fileName ?? "<null>", filePropName); } else if (!PermissionSetAttributeTypeHasRequiredProperty(attrType, hexPropName)) { // PermissionSetAttribute was defined in user source, but doesn't have the required Hex property. // Native compiler still emits the file content as named assignment to 'Hex' property, but this leads to a runtime exception. // We instead skip the fixup and emit the file property. // CONSIDER: We may want to consider taking a breaking change and generating an error here. return null; } } } return resolvedFilePath; } // This method checks if the given PermissionSetAttribute type has a property member with the given propName which is writable, non-generic, public and of string type. private static bool PermissionSetAttributeTypeHasRequiredProperty(NamedTypeSymbol permissionSetType, string propName) { var members = permissionSetType.GetMembers(propName); if (members.Length == 1 && members[0].Kind == SymbolKind.Property) { var property = (PropertySymbol)members[0]; if (property.TypeWithAnnotations.HasType && property.Type.SpecialType == SpecialType.System_String && property.DeclaredAccessibility == Accessibility.Public && property.GetMemberArity() == 0 && (object)property.SetMethod != null && property.SetMethod.DeclaredAccessibility == Accessibility.Public) { return true; } } return false; } internal void DecodeClassInterfaceAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); TypedConstant ctorArgument = this.CommonConstructorArguments[0]; Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive); ClassInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ? ctorArgument.DecodeValue<ClassInterfaceType>(SpecialType.System_Enum) : (ClassInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16); switch (interfaceType) { case ClassInterfaceType.None: case Cci.Constants.ClassInterfaceType_AutoDispatch: case Cci.Constants.ClassInterfaceType_AutoDual: break; default: // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); break; } } internal void DecodeInterfaceTypeAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); TypedConstant ctorArgument = this.CommonConstructorArguments[0]; Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive); ComInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ? ctorArgument.DecodeValue<ComInterfaceType>(SpecialType.System_Enum) : (ComInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16); switch (interfaceType) { case Cci.Constants.ComInterfaceType_InterfaceIsDual: case Cci.Constants.ComInterfaceType_InterfaceIsIDispatch: case ComInterfaceType.InterfaceIsIInspectable: case ComInterfaceType.InterfaceIsIUnknown: break; default: // CS0591: Invalid value for argument to '{0}' attribute CSharpSyntaxNode attributeArgumentSyntax = this.GetAttributeArgumentSyntax(0, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); break; } } internal string DecodeGuidAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); var guidString = (string?)this.CommonConstructorArguments[0].ValueInternal; // Native compiler allows only a specific GUID format: "D" format (32 digits separated by hyphens) Guid guid; if (!Guid.TryParseExact(guidString, "D", out guid)) { // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); guidString = String.Empty; } return guidString!; } private protected sealed override bool IsStringProperty(string memberName) { if (AttributeClass is object) { foreach (var member in AttributeClass.GetMembers(memberName)) { if (member is PropertySymbol { Type: { SpecialType: SpecialType.System_String } }) { return true; } } } return false; } #endregion /// <summary> /// This method determines if an applied attribute must be emitted. /// Some attributes appear in symbol model to reflect the source code, /// but should not be emitted. /// </summary> internal bool ShouldEmitAttribute(Symbol target, bool isReturnType, bool emittingAssemblyAttributesInNetModule) { Debug.Assert(target is SourceAssemblySymbol || target.ContainingAssembly is SourceAssemblySymbol); if (HasErrors) { throw ExceptionUtilities.Unreachable; } // Attribute type is conditionally omitted if both the following are true: // (a) It has at least one applied/inherited conditional attribute AND // (b) None of conditional symbols are defined in the source file where the given attribute was defined. if (this.IsConditionallyOmitted) { return false; } switch (target.Kind) { case SymbolKind.Assembly: if ((!emittingAssemblyAttributesInNetModule && (IsTargetAttribute(target, AttributeDescription.AssemblyCultureAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyVersionAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyFlagsAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyAlgorithmIdAttribute))) || IsTargetAttribute(target, AttributeDescription.TypeForwardedToAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } break; case SymbolKind.Event: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute)) { return false; } break; case SymbolKind.Field: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) || IsTargetAttribute(target, AttributeDescription.FieldOffsetAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } break; case SymbolKind.Method: if (isReturnType) { if (IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } } else { if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.MethodImplAttribute) || IsTargetAttribute(target, AttributeDescription.DllImportAttribute) || IsTargetAttribute(target, AttributeDescription.PreserveSigAttribute) || IsTargetAttribute(target, AttributeDescription.DynamicSecurityMethodAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } } break; case SymbolKind.NetModule: // Note that DefaultCharSetAttribute is emitted to metadata, although it's also decoded and used when emitting P/Invoke break; case SymbolKind.NamedType: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.ComImportAttribute) || IsTargetAttribute(target, AttributeDescription.SerializableAttribute) || IsTargetAttribute(target, AttributeDescription.StructLayoutAttribute) || IsTargetAttribute(target, AttributeDescription.WindowsRuntimeImportAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } break; case SymbolKind.Parameter: if (IsTargetAttribute(target, AttributeDescription.OptionalAttribute) || IsTargetAttribute(target, AttributeDescription.DefaultParameterValueAttribute) || IsTargetAttribute(target, AttributeDescription.InAttribute) || IsTargetAttribute(target, AttributeDescription.OutAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } break; case SymbolKind.Property: if (IsTargetAttribute(target, AttributeDescription.IndexerNameAttribute) || IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.DisallowNullAttribute) || IsTargetAttribute(target, AttributeDescription.AllowNullAttribute) || IsTargetAttribute(target, AttributeDescription.MaybeNullAttribute) || IsTargetAttribute(target, AttributeDescription.NotNullAttribute)) { return false; } break; } return true; } } internal static class AttributeDataExtensions { internal static int IndexOfAttribute(this ImmutableArray<CSharpAttributeData> attributes, Symbol targetSymbol, AttributeDescription description) { for (int i = 0; i < attributes.Length; i++) { if (attributes[i].IsTargetAttribute(targetSymbol, description)) { return i; } } return -1; } internal static CSharpSyntaxNode GetAttributeArgumentSyntax(this AttributeData attribute, int parameterIndex, AttributeSyntax attributeSyntax) { Debug.Assert(attribute is SourceAttributeData); return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntax); } internal static string? DecodeNotNullIfNotNullAttribute(this CSharpAttributeData attribute) { var arguments = attribute.CommonConstructorArguments; return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_String, out string? value) ? value : null; } internal static Location GetAttributeArgumentSyntaxLocation(this AttributeData attribute, int parameterIndex, AttributeSyntax? attributeSyntaxOpt) { if (attributeSyntaxOpt == null) { return NoLocation.Singleton; } Debug.Assert(attribute is SourceAttributeData); return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntaxOpt).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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Reflection; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using Microsoft.CodeAnalysis; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an attribute applied to a Symbol. /// </summary> internal abstract partial class CSharpAttributeData : AttributeData { private ThreeState _lazyIsSecurityAttribute = ThreeState.Unknown; /// <summary> /// Gets the attribute class being applied. /// </summary> public new abstract NamedTypeSymbol? AttributeClass { get; } /// <summary> /// Gets the constructor used in this application of the attribute. /// </summary> public new abstract MethodSymbol? AttributeConstructor { get; } /// <summary> /// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols. /// </summary> public new abstract SyntaxReference? ApplicationSyntaxReference { get; } // Overridden to be able to apply MemberNotNull to the new members [MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))] internal override bool HasErrors { get { var hasErrors = base.HasErrors; if (!hasErrors) { Debug.Assert(AttributeClass is not null); Debug.Assert(AttributeConstructor is not null); } return hasErrors; } } /// <summary> /// Gets the list of constructor arguments specified by this application of the attribute. This list contains both positional arguments /// and named arguments that are formal parameters to the constructor. /// </summary> public new IEnumerable<TypedConstant> ConstructorArguments { get { return this.CommonConstructorArguments; } } /// <summary> /// Gets the list of named field or property value arguments specified by this application of the attribute. /// </summary> public new IEnumerable<KeyValuePair<string, TypedConstant>> NamedArguments { get { return this.CommonNamedArguments; } } /// <summary> /// Compares the namespace and type name with the attribute's namespace and type name. /// Returns true if they are the same. /// </summary> internal virtual bool IsTargetAttribute(string namespaceName, string typeName) { Debug.Assert(this.AttributeClass is object); if (!this.AttributeClass.Name.Equals(typeName)) { return false; } if (this.AttributeClass.IsErrorType() && !(this.AttributeClass is MissingMetadataTypeSymbol)) { // Can't guarantee complete name information. return false; } return this.AttributeClass.HasNameQualifier(namespaceName); } internal bool IsTargetAttribute(Symbol targetSymbol, AttributeDescription description) { return GetTargetAttributeSignatureIndex(targetSymbol, description) != -1; } internal abstract int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description); /// <summary> /// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description /// and the attribute description has a signature with parameter count equal to the given attribute syntax's argument list count. /// NOTE: We don't allow early decoded attributes to have optional parameters. /// </summary> internal static bool IsTargetEarlyAttribute(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax, AttributeDescription description) { Debug.Assert(!attributeType.IsErrorType()); int argumentCount = (attributeSyntax.ArgumentList != null) ? attributeSyntax.ArgumentList.Arguments.Count<AttributeArgumentSyntax>((arg) => arg.NameEquals == null) : 0; return AttributeData.IsTargetEarlyAttribute(attributeType, argumentCount, description); } // Security attributes, i.e. attributes derived from well-known SecurityAttribute, are matched by type, not constructor signature. internal bool IsSecurityAttribute(CSharpCompilation compilation) { if (_lazyIsSecurityAttribute == ThreeState.Unknown) { Debug.Assert(!this.HasErrors); // CLI spec (Partition II Metadata), section 21.11 "DeclSecurity : 0x0E" states: // SPEC: If the attribute's type is derived (directly or indirectly) from System.Security.Permissions.SecurityAttribute then // SPEC: it is a security custom attribute and requires special treatment. // NOTE: The native C# compiler violates the above and considers only those attributes whose type derives from // NOTE: System.Security.Permissions.CodeAccessSecurityAttribute as security custom attributes. // NOTE: We will follow the specification. // NOTE: See Devdiv Bug #13762 "Custom security attributes deriving from SecurityAttribute are not treated as security attributes" for details. // Well-known type SecurityAttribute is optional. // Native compiler doesn't generate a use-site error if it is not found, we do the same. var wellKnownType = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAttribute); Debug.Assert(AttributeClass is object); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _lazyIsSecurityAttribute = AttributeClass.IsDerivedFrom(wellKnownType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo).ToThreeState(); } return _lazyIsSecurityAttribute.Value(); } // for testing and debugging only /// <summary> /// Returns the <see cref="System.String"/> that represents the current AttributeData. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current AttributeData.</returns> public override string? ToString() { if (this.AttributeClass is object) { string className = this.AttributeClass.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); if (!this.CommonConstructorArguments.Any() & !this.CommonNamedArguments.Any()) { return className; } var pooledStrbuilder = PooledStringBuilder.GetInstance(); StringBuilder stringBuilder = pooledStrbuilder.Builder; stringBuilder.Append(className); stringBuilder.Append("("); bool first = true; foreach (var constructorArgument in this.CommonConstructorArguments) { if (!first) { stringBuilder.Append(", "); } stringBuilder.Append(constructorArgument.ToCSharpString()); first = false; } foreach (var namedArgument in this.CommonNamedArguments) { if (!first) { stringBuilder.Append(", "); } stringBuilder.Append(namedArgument.Key); stringBuilder.Append(" = "); stringBuilder.Append(namedArgument.Value.ToCSharpString()); first = false; } stringBuilder.Append(")"); return pooledStrbuilder.ToStringAndFree(); } return base.ToString(); } #region AttributeData Implementation /// <summary> /// Gets the attribute class being applied as an <see cref="INamedTypeSymbol"/> /// </summary> protected override INamedTypeSymbol? CommonAttributeClass { get { return this.AttributeClass.GetPublicSymbol(); } } /// <summary> /// Gets the constructor used in this application of the attribute as an <see cref="IMethodSymbol"/>. /// </summary> protected override IMethodSymbol? CommonAttributeConstructor { get { return this.AttributeConstructor.GetPublicSymbol(); } } /// <summary> /// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols. /// </summary> protected override SyntaxReference? CommonApplicationSyntaxReference { get { return this.ApplicationSyntaxReference; } } #endregion #region Attribute Decoding internal void DecodeSecurityAttribute<T>(Symbol targetSymbol, CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, ISecurityAttributeTarget, new() { Debug.Assert(!this.HasErrors); Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag); bool hasErrors; DeclarativeSecurityAction action = DecodeSecurityAttributeAction(targetSymbol, compilation, arguments.AttributeSyntaxOpt, out hasErrors, (BindingDiagnosticBag)arguments.Diagnostics); if (!hasErrors) { T data = arguments.GetOrCreateData<T>(); SecurityWellKnownAttributeData securityData = data.GetOrCreateData(); securityData.SetSecurityAttribute(arguments.Index, action, arguments.AttributesCount); if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PermissionSetAttribute)) { string? resolvedPathForFixup = DecodePermissionSetAttribute(compilation, arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics); if (resolvedPathForFixup != null) { securityData.SetPathForPermissionSetAttributeFixup(arguments.Index, resolvedPathForFixup, arguments.AttributesCount); } } } } internal static void DecodeSkipLocalsInitAttribute<T>(CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, ISkipLocalsInitAttributeTarget, new() { arguments.GetOrCreateData<T>().HasSkipLocalsInitAttribute = true; if (!compilation.Options.AllowUnsafe) { Debug.Assert(arguments.AttributeSyntaxOpt is object); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_IllegalUnsafe, arguments.AttributeSyntaxOpt.Location); } } internal static void DecodeMemberNotNullAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() { var value = arguments.Attribute.CommonConstructorArguments[0]; if (value.IsNull) { return; } if (value.Kind != TypedConstantKind.Array) { string? memberName = value.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { arguments.GetOrCreateData<T>().AddNotNullMember(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } else { var builder = ArrayBuilder<string>.GetInstance(); foreach (var member in value.Values) { var memberName = member.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { builder.Add(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } arguments.GetOrCreateData<T>().AddNotNullMember(builder); builder.Free(); } } private static void ReportBadNotNullMemberIfNeeded(TypeSymbol type, DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, string memberName) { foreach (Symbol foundMember in type.GetMembers(memberName)) { if (foundMember.Kind == SymbolKind.Field || foundMember.Kind == SymbolKind.Property) { return; } } Debug.Assert(arguments.AttributeSyntaxOpt is object); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.WRN_MemberNotNullBadMember, arguments.AttributeSyntaxOpt.Location, memberName); } internal static void DecodeMemberNotNullWhenAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() { var value = arguments.Attribute.CommonConstructorArguments[1]; if (value.IsNull) { return; } var sense = arguments.Attribute.CommonConstructorArguments[0].DecodeValue<bool>(SpecialType.System_Boolean); if (value.Kind != TypedConstantKind.Array) { var memberName = value.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } else { var builder = ArrayBuilder<string>.GetInstance(); foreach (var member in value.Values) { var memberName = member.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { builder.Add(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, builder); builder.Free(); } } private DeclarativeSecurityAction DecodeSecurityAttributeAction(Symbol targetSymbol, CSharpCompilation compilation, AttributeSyntax? nodeOpt, out bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert((object)targetSymbol != null); Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method); Debug.Assert(this.IsSecurityAttribute(compilation)); var ctorArgs = this.CommonConstructorArguments; if (!ctorArgs.Any()) { // NOTE: Security custom attributes must have a valid SecurityAction as its first argument, we have none here. // NOTE: Ideally, we should always generate 'CS7048: First argument to a security attribute must be a valid SecurityAction' for this case. // NOTE: However, native compiler allows applying System.Security.Permissions.HostProtectionAttribute attribute without any argument and uses // NOTE: SecurityAction.LinkDemand as the default SecurityAction in this case. We maintain compatibility with the native compiler for this case. // BREAKING CHANGE: Even though the native compiler intends to allow only HostProtectionAttribute to be applied without any arguments, // it doesn't quite do this correctly // The implementation issue leads to the native compiler allowing any user defined security attribute with a parameterless constructor and a named property argument as the first // attribute argument to have the above mentioned behavior, even though the comment clearly mentions that this behavior was intended only for the HostProtectionAttribute. // We currently allow this case only for the HostProtectionAttribute. In future if need arises, we can exactly match native compiler's behavior. if (this.IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute)) { hasErrors = false; return DeclarativeSecurityAction.LinkDemand; } } else { TypedConstant firstArg = ctorArgs.First(); var firstArgType = (TypeSymbol?)firstArg.TypeInternal; if (firstArgType is object && firstArgType.Equals(compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction))) { return DecodeSecurityAction(firstArg, targetSymbol, nodeOpt, diagnostics, out hasErrors); } } // CS7048: First argument to a security attribute must be a valid SecurityAction diagnostics.Add(ErrorCode.ERR_SecurityAttributeMissingAction, nodeOpt != null ? nodeOpt.Name.Location : NoLocation.Singleton); hasErrors = true; return DeclarativeSecurityAction.None; } private DeclarativeSecurityAction DecodeSecurityAction(TypedConstant typedValue, Symbol targetSymbol, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics, out bool hasErrors) { Debug.Assert((object)targetSymbol != null); Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method); Debug.Assert(typedValue.ValueInternal is object); int securityAction = (int)typedValue.ValueInternal; bool isPermissionRequestAction; switch (securityAction) { case (int)DeclarativeSecurityAction.InheritanceDemand: case (int)DeclarativeSecurityAction.LinkDemand: if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PrincipalPermissionAttribute)) { // CS7052: SecurityAction value '{0}' is invalid for PrincipalPermission attribute object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_PrincipalPermissionInvalidAction, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } isPermissionRequestAction = false; break; case 1: // Native compiler allows security action value 1 for security attributes on types/methods, even though there is no corresponding field in System.Security.Permissions.SecurityAction enum. // We will maintain compatibility. case (int)DeclarativeSecurityAction.Assert: case (int)DeclarativeSecurityAction.Demand: case (int)DeclarativeSecurityAction.PermitOnly: case (int)DeclarativeSecurityAction.Deny: isPermissionRequestAction = false; break; case (int)DeclarativeSecurityAction.RequestMinimum: case (int)DeclarativeSecurityAction.RequestOptional: case (int)DeclarativeSecurityAction.RequestRefuse: isPermissionRequestAction = true; break; default: { // CS7049: Security attribute '{0}' has an invalid SecurityAction value '{1}' object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidAction, syntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "", displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } // Validate security action for symbol kind if (isPermissionRequestAction) { if (targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method) { // Types and methods cannot take permission requests. // CS7051: SecurityAction value '{0}' is invalid for security attributes applied to a type or a method object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } else { if (targetSymbol.Kind == SymbolKind.Assembly) { // Assemblies cannot take declarative security. // CS7050: SecurityAction value '{0}' is invalid for security attributes applied to an assembly object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } hasErrors = false; return (DeclarativeSecurityAction)securityAction; } private static Location GetSecurityAttributeActionSyntaxLocation(AttributeSyntax? nodeOpt, TypedConstant typedValue, out object displayString) { if (nodeOpt == null) { displayString = ""; return NoLocation.Singleton; } var argList = nodeOpt.ArgumentList; if (argList == null || argList.Arguments.IsEmpty()) { // Optional SecurityAction parameter with default value. displayString = (FormattableString)$"{typedValue.ValueInternal}"; return nodeOpt.Location; } AttributeArgumentSyntax argSyntax = argList.Arguments[0]; displayString = argSyntax.ToString(); return argSyntax.Location; } /// <summary> /// Decodes PermissionSetAttribute applied in source to determine if it needs any fixup during codegen. /// </summary> /// <remarks> /// PermissionSetAttribute needs fixup when it contains an assignment to the 'File' property as a single named attribute argument. /// Fixup performed is ported from SecurityAttributes::FixUpPermissionSetAttribute. /// It involves following steps: /// 1) Verifying that the specified file name resolves to a valid path. /// 2) Reading the contents of the file into a byte array. /// 3) Convert each byte in the file content into two bytes containing hexadecimal characters. /// 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above. /// /// Step 1) is performed in this method, i.e. during binding. /// Remaining steps are performed during serialization as we want to avoid retaining the entire file contents throughout the binding/codegen pass. /// See <see cref="Microsoft.CodeAnalysis.CodeGen.PermissionSetAttributeWithFileReference"/> for remaining fixup steps. /// </remarks> /// <returns>String containing the resolved file path if PermissionSetAttribute needs fixup during codegen, null otherwise.</returns> private string? DecodePermissionSetAttribute(CSharpCompilation compilation, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); string? resolvedFilePath = null; var namedArgs = this.CommonNamedArguments; if (namedArgs.Length == 1) { var namedArg = namedArgs[0]; Debug.Assert(AttributeClass is object); NamedTypeSymbol attrType = this.AttributeClass; string filePropName = PermissionSetAttributeWithFileReference.FilePropertyName; string hexPropName = PermissionSetAttributeWithFileReference.HexPropertyName; if (namedArg.Key == filePropName && PermissionSetAttributeTypeHasRequiredProperty(attrType, filePropName)) { // resolve file prop path var fileName = (string?)namedArg.Value.ValueInternal; var resolver = compilation.Options.XmlReferenceResolver; resolvedFilePath = (resolver != null && fileName != null) ? resolver.ResolveReference(fileName, baseFilePath: null) : null; if (resolvedFilePath == null) { // CS7053: Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute Location argSyntaxLocation = nodeOpt?.GetNamedArgumentSyntax(filePropName)?.Location ?? NoLocation.Singleton; diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeInvalidFile, argSyntaxLocation, fileName ?? "<null>", filePropName); } else if (!PermissionSetAttributeTypeHasRequiredProperty(attrType, hexPropName)) { // PermissionSetAttribute was defined in user source, but doesn't have the required Hex property. // Native compiler still emits the file content as named assignment to 'Hex' property, but this leads to a runtime exception. // We instead skip the fixup and emit the file property. // CONSIDER: We may want to consider taking a breaking change and generating an error here. return null; } } } return resolvedFilePath; } // This method checks if the given PermissionSetAttribute type has a property member with the given propName which is writable, non-generic, public and of string type. private static bool PermissionSetAttributeTypeHasRequiredProperty(NamedTypeSymbol permissionSetType, string propName) { var members = permissionSetType.GetMembers(propName); if (members.Length == 1 && members[0].Kind == SymbolKind.Property) { var property = (PropertySymbol)members[0]; if (property.TypeWithAnnotations.HasType && property.Type.SpecialType == SpecialType.System_String && property.DeclaredAccessibility == Accessibility.Public && property.GetMemberArity() == 0 && (object)property.SetMethod != null && property.SetMethod.DeclaredAccessibility == Accessibility.Public) { return true; } } return false; } internal void DecodeClassInterfaceAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); TypedConstant ctorArgument = this.CommonConstructorArguments[0]; Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive); ClassInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ? ctorArgument.DecodeValue<ClassInterfaceType>(SpecialType.System_Enum) : (ClassInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16); switch (interfaceType) { case ClassInterfaceType.None: case Cci.Constants.ClassInterfaceType_AutoDispatch: case Cci.Constants.ClassInterfaceType_AutoDual: break; default: // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); break; } } internal void DecodeInterfaceTypeAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); TypedConstant ctorArgument = this.CommonConstructorArguments[0]; Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive); ComInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ? ctorArgument.DecodeValue<ComInterfaceType>(SpecialType.System_Enum) : (ComInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16); switch (interfaceType) { case Cci.Constants.ComInterfaceType_InterfaceIsDual: case Cci.Constants.ComInterfaceType_InterfaceIsIDispatch: case ComInterfaceType.InterfaceIsIInspectable: case ComInterfaceType.InterfaceIsIUnknown: break; default: // CS0591: Invalid value for argument to '{0}' attribute CSharpSyntaxNode attributeArgumentSyntax = this.GetAttributeArgumentSyntax(0, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); break; } } internal string DecodeGuidAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); var guidString = (string?)this.CommonConstructorArguments[0].ValueInternal; // Native compiler allows only a specific GUID format: "D" format (32 digits separated by hyphens) Guid guid; if (!Guid.TryParseExact(guidString, "D", out guid)) { // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); guidString = String.Empty; } return guidString!; } private protected sealed override bool IsStringProperty(string memberName) { if (AttributeClass is object) { foreach (var member in AttributeClass.GetMembers(memberName)) { if (member is PropertySymbol { Type: { SpecialType: SpecialType.System_String } }) { return true; } } } return false; } #endregion /// <summary> /// This method determines if an applied attribute must be emitted. /// Some attributes appear in symbol model to reflect the source code, /// but should not be emitted. /// </summary> internal bool ShouldEmitAttribute(Symbol target, bool isReturnType, bool emittingAssemblyAttributesInNetModule) { Debug.Assert(target is SourceAssemblySymbol || target.ContainingAssembly is SourceAssemblySymbol); if (HasErrors) { throw ExceptionUtilities.Unreachable; } // Attribute type is conditionally omitted if both the following are true: // (a) It has at least one applied/inherited conditional attribute AND // (b) None of conditional symbols are defined in the source file where the given attribute was defined. if (this.IsConditionallyOmitted) { return false; } switch (target.Kind) { case SymbolKind.Assembly: if ((!emittingAssemblyAttributesInNetModule && (IsTargetAttribute(target, AttributeDescription.AssemblyCultureAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyVersionAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyFlagsAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyAlgorithmIdAttribute))) || IsTargetAttribute(target, AttributeDescription.TypeForwardedToAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } break; case SymbolKind.Event: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute)) { return false; } break; case SymbolKind.Field: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) || IsTargetAttribute(target, AttributeDescription.FieldOffsetAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } break; case SymbolKind.Method: if (isReturnType) { if (IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } } else { if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.MethodImplAttribute) || IsTargetAttribute(target, AttributeDescription.DllImportAttribute) || IsTargetAttribute(target, AttributeDescription.PreserveSigAttribute) || IsTargetAttribute(target, AttributeDescription.DynamicSecurityMethodAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } } break; case SymbolKind.NetModule: // Note that DefaultCharSetAttribute is emitted to metadata, although it's also decoded and used when emitting P/Invoke break; case SymbolKind.NamedType: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.ComImportAttribute) || IsTargetAttribute(target, AttributeDescription.SerializableAttribute) || IsTargetAttribute(target, AttributeDescription.StructLayoutAttribute) || IsTargetAttribute(target, AttributeDescription.WindowsRuntimeImportAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } break; case SymbolKind.Parameter: if (IsTargetAttribute(target, AttributeDescription.OptionalAttribute) || IsTargetAttribute(target, AttributeDescription.DefaultParameterValueAttribute) || IsTargetAttribute(target, AttributeDescription.InAttribute) || IsTargetAttribute(target, AttributeDescription.OutAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } break; case SymbolKind.Property: if (IsTargetAttribute(target, AttributeDescription.IndexerNameAttribute) || IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.DisallowNullAttribute) || IsTargetAttribute(target, AttributeDescription.AllowNullAttribute) || IsTargetAttribute(target, AttributeDescription.MaybeNullAttribute) || IsTargetAttribute(target, AttributeDescription.NotNullAttribute)) { return false; } break; } return true; } } internal static class AttributeDataExtensions { internal static int IndexOfAttribute(this ImmutableArray<CSharpAttributeData> attributes, Symbol targetSymbol, AttributeDescription description) { for (int i = 0; i < attributes.Length; i++) { if (attributes[i].IsTargetAttribute(targetSymbol, description)) { return i; } } return -1; } internal static CSharpSyntaxNode GetAttributeArgumentSyntax(this AttributeData attribute, int parameterIndex, AttributeSyntax attributeSyntax) { Debug.Assert(attribute is SourceAttributeData); return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntax); } internal static string? DecodeNotNullIfNotNullAttribute(this CSharpAttributeData attribute) { var arguments = attribute.CommonConstructorArguments; return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_String, out string? value) ? value : null; } internal static Location GetAttributeArgumentSyntaxLocation(this AttributeData attribute, int parameterIndex, AttributeSyntax? attributeSyntaxOpt) { if (attributeSyntaxOpt == null) { return NoLocation.Singleton; } Debug.Assert(attribute is SourceAttributeData); return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntaxOpt).Location; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/EditorFeatures/Test/EditorAdapter/SpanExtensionsTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorAdapter { public class SpanExtensionsTest { [Fact] public void ConvertToTextSpan() { static void del(int start, int length) { var span = new Span(start, length); var textSpan = span.ToTextSpan(); Assert.Equal(start, textSpan.Start); Assert.Equal(length, textSpan.Length); } del(0, 5); del(10, 15); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorAdapter { public class SpanExtensionsTest { [Fact] public void ConvertToTextSpan() { static void del(int start, int length) { var span = new Span(start, length); var textSpan = span.ToTextSpan(); Assert.Equal(start, textSpan.Start); Assert.Equal(length, textSpan.Length); } del(0, 5); del(10, 15); } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertNamespaceAnalysis.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace { internal static class ConvertNamespaceAnalysis { public static (string title, string equivalenceKey) GetInfo(NamespaceDeclarationPreference preference) => preference switch { NamespaceDeclarationPreference.BlockScoped => (CSharpAnalyzersResources.Convert_to_block_scoped_namespace, nameof(CSharpAnalyzersResources.Convert_to_block_scoped_namespace)), NamespaceDeclarationPreference.FileScoped => (CSharpAnalyzersResources.Convert_to_file_scoped_namespace, nameof(CSharpAnalyzersResources.Convert_to_file_scoped_namespace)), _ => throw ExceptionUtilities.UnexpectedValue(preference), }; public static bool CanOfferUseBlockScoped(OptionSet optionSet, BaseNamespaceDeclarationSyntax declaration, bool forAnalyzer) { if (declaration is not FileScopedNamespaceDeclarationSyntax) return false; var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations); var userPrefersRegularNamespaces = option.Value == NamespaceDeclarationPreference.BlockScoped; var analyzerDisabled = option.Notification.Severity == ReportDiagnostic.Suppress; var forRefactoring = !forAnalyzer; // If the user likes regular namespaces, then we offer regular namespaces from the diagnostic analyzer. // If the user does not like regular namespaces then we offer regular namespaces bodies from the refactoring provider. // If the analyzer is disabled completely, the refactoring is enabled in both directions. var canOffer = userPrefersRegularNamespaces == forAnalyzer || (forRefactoring && analyzerDisabled); return canOffer; } internal static bool CanOfferUseFileScoped(OptionSet optionSet, CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax declaration, bool forAnalyzer) { if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration) return false; if (namespaceDeclaration.OpenBraceToken.IsMissing) return false; if (((CSharpParseOptions)root.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp10) return false; var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations); var userPrefersFileScopedNamespaces = option.Value == NamespaceDeclarationPreference.FileScoped; var analyzerDisabled = option.Notification.Severity == ReportDiagnostic.Suppress; var forRefactoring = !forAnalyzer; // If the user likes file scoped namespaces, then we offer file scoped namespaces from the diagnostic analyzer. // If the user does not like file scoped namespaces then we offer file scoped namespaces from the refactoring provider. // If the analyzer is disabled completely, the refactoring is enabled in both directions. var canOffer = userPrefersFileScopedNamespaces == forAnalyzer || (forRefactoring && analyzerDisabled); if (!canOffer) return false; // even if we could offer this here, we have to make sure it would be legal. A file scoped namespace is // only legal if it's the only namespace in the file and there are no top level statements. var tooManyNamespaces = root.DescendantNodesAndSelf(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>() .Take(2) .Count() != 1; if (tooManyNamespaces) return false; if (root.Members.Any(m => m is GlobalStatementSyntax)) return false; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace { internal static class ConvertNamespaceAnalysis { public static (string title, string equivalenceKey) GetInfo(NamespaceDeclarationPreference preference) => preference switch { NamespaceDeclarationPreference.BlockScoped => (CSharpAnalyzersResources.Convert_to_block_scoped_namespace, nameof(CSharpAnalyzersResources.Convert_to_block_scoped_namespace)), NamespaceDeclarationPreference.FileScoped => (CSharpAnalyzersResources.Convert_to_file_scoped_namespace, nameof(CSharpAnalyzersResources.Convert_to_file_scoped_namespace)), _ => throw ExceptionUtilities.UnexpectedValue(preference), }; public static bool CanOfferUseBlockScoped(OptionSet optionSet, BaseNamespaceDeclarationSyntax declaration, bool forAnalyzer) { if (declaration is not FileScopedNamespaceDeclarationSyntax) return false; var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations); var userPrefersRegularNamespaces = option.Value == NamespaceDeclarationPreference.BlockScoped; var analyzerDisabled = option.Notification.Severity == ReportDiagnostic.Suppress; var forRefactoring = !forAnalyzer; // If the user likes regular namespaces, then we offer regular namespaces from the diagnostic analyzer. // If the user does not like regular namespaces then we offer regular namespaces bodies from the refactoring provider. // If the analyzer is disabled completely, the refactoring is enabled in both directions. var canOffer = userPrefersRegularNamespaces == forAnalyzer || (forRefactoring && analyzerDisabled); return canOffer; } internal static bool CanOfferUseFileScoped(OptionSet optionSet, CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax declaration, bool forAnalyzer) { if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration) return false; if (namespaceDeclaration.OpenBraceToken.IsMissing) return false; if (((CSharpParseOptions)root.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp10) return false; var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations); var userPrefersFileScopedNamespaces = option.Value == NamespaceDeclarationPreference.FileScoped; var analyzerDisabled = option.Notification.Severity == ReportDiagnostic.Suppress; var forRefactoring = !forAnalyzer; // If the user likes file scoped namespaces, then we offer file scoped namespaces from the diagnostic analyzer. // If the user does not like file scoped namespaces then we offer file scoped namespaces from the refactoring provider. // If the analyzer is disabled completely, the refactoring is enabled in both directions. var canOffer = userPrefersFileScopedNamespaces == forAnalyzer || (forRefactoring && analyzerDisabled); if (!canOffer) return false; // even if we could offer this here, we have to make sure it would be legal. A file scoped namespace is // only legal if it's the only namespace in the file and there are no top level statements. var tooManyNamespaces = root.DescendantNodesAndSelf(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>() .Take(2) .Count() != 1; if (tooManyNamespaces) return false; if (root.Members.Any(m => m is GlobalStatementSyntax)) return false; return true; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { internal abstract class LongestCommonSubsequence { // Define the pool in a non-generic base class to allow sharing among instantiations. private static readonly ObjectPool<VBuffer> s_pool = new(() => new VBuffer()); /// <summary> /// Underlying storage for <see cref="VArray"/>s allocated on <see cref="VStack"/>. /// </summary> /// <remarks> /// The LCS algorithm allocates <see cref="VArray"/>s of sizes (3, 2*1 + 1, ..., 2*D + 1), always in this order, /// where D is at most the sum of lengths of the compared sequences. /// The arrays get pushed on a stack as they are built up, then all consumed in the reverse order (stack pop). /// /// Since the exact length of each array in the above sequence is known we avoid allocating each individual array. /// Instead we allocate a large buffer serving as a a backing storage of a contiguous sequence of arrays /// corresponding to stack depths <see cref="MinDepth"/> to <see cref="MaxDepth"/>. /// If more storage is needed we chain next large buffer to the previous one in a linked list. /// /// We pool a few of these linked buffers on <see cref="VStack"/> to conserve allocations. /// </remarks> protected sealed class VBuffer { /// <summary> /// The max stack depth backed by the fist buffer. /// Size of the buffer for 100 is ~10K. /// For 150 it'd be 91KB, which would be allocated on LOH. /// The buffers grow by factor of <see cref="GrowFactor"/>, so the next buffer will be allocated on LOH. /// </summary> private const int FirstBufferMaxDepth = 100; // 3 + Sum { d = 1..maxDepth : 2*d+1 } = (maxDepth + 1)^2 + 2 private const int FirstBufferLength = (FirstBufferMaxDepth + 1) * (FirstBufferMaxDepth + 1) + 2; internal const int GrowFactor = 2; /// <summary> /// Do not pool segments that are too large. /// </summary> internal const int MaxPooledBufferSize = 1024 * 1024; public VBuffer Previous { get; private set; } public VBuffer Next { get; private set; } public readonly int MinDepth; public readonly int MaxDepth; private readonly int[] _array; public VBuffer() { _array = new int[FirstBufferLength]; MaxDepth = FirstBufferMaxDepth; } public VBuffer(VBuffer previous) { Debug.Assert(previous != null); var minDepth = previous.MaxDepth + 1; var maxDepth = previous.MaxDepth * GrowFactor; Debug.Assert(minDepth > 0); Debug.Assert(minDepth <= maxDepth); Previous = previous; _array = new int[GetNextBufferLength(minDepth - 1, maxDepth)]; MinDepth = minDepth; MaxDepth = maxDepth; previous.Next = this; } public VArray GetVArray(int depth) { var length = GetVArrayLength(depth); var start = GetVArrayStart(depth) - GetVArrayStart(MinDepth); Debug.Assert(start >= 0); Debug.Assert(start + length <= _array.Length); return new VArray(_array, start, length); } public bool IsTooLargeToPool => _array.Length > MaxPooledBufferSize; private static int GetVArrayLength(int depth) => 2 * Math.Max(depth, 1) + 1; // 3 + Sum { d = 1..depth-1 : 2*d+1 } = depth^2 + 2 private static int GetVArrayStart(int depth) => (depth == 0) ? 0 : depth * depth + 2; // Sum { d = previousChunkDepth..maxDepth : 2*d+1 } = (maxDepth + 1)^2 - precedingBufferMaxDepth^2 private static int GetNextBufferLength(int precedingBufferMaxDepth, int maxDepth) => (maxDepth + 1) * (maxDepth + 1) - precedingBufferMaxDepth * precedingBufferMaxDepth; public void Unlink() { Previous.Next = null; Previous = null; } } protected struct VStack { private readonly ObjectPool<VBuffer> _bufferPool; private readonly VBuffer _firstBuffer; private VBuffer _currentBuffer; private int _depth; public VStack(ObjectPool<VBuffer> bufferPool) { _bufferPool = bufferPool; _currentBuffer = _firstBuffer = bufferPool.Allocate(); _depth = 0; } public VArray Push() { var depth = _depth++; if (depth > _currentBuffer.MaxDepth) { // If the buffer is not big enough add another segment to the linked list (the constructor takes care of the linking). // Note that the segments are not pooled on their own. The whole linked list of buffers is pooled. _currentBuffer = _currentBuffer.Next ?? new VBuffer(_currentBuffer); } return _currentBuffer.GetVArray(depth); } public IEnumerable<(VArray Array, int Depth)> ConsumeArrays() { var buffer = _currentBuffer; for (var depth = _depth - 1; depth >= 0; depth--) { if (depth < buffer.MinDepth) { var previousBuffer = buffer.Previous; // Trim large buffers from the linked list before we return the whole list back into the pool. if (buffer.IsTooLargeToPool) { buffer.Unlink(); } buffer = previousBuffer; } yield return (buffer.GetVArray(depth), depth); } _bufferPool.Free(_firstBuffer); _currentBuffer = null; } } // VArray struct enables array indexing in range [-d...d]. protected readonly struct VArray { private readonly int[] _buffer; private readonly int _start; private readonly int _length; public VArray(int[] buffer, int start, int length) { _buffer = buffer; _start = start; _length = length; } public void InitializeFrom(VArray other) { int dstCopyStart, srcCopyStart, copyLength; var copyDelta = Offset - other.Offset; if (copyDelta >= 0) { srcCopyStart = 0; dstCopyStart = copyDelta; copyLength = other._length; } else { srcCopyStart = -copyDelta; dstCopyStart = 0; copyLength = _length; } // since we might be reusing previously used arrays, we need to clear slots that are not copied over from the other array: Array.Clear(_buffer, _start, dstCopyStart); Array.Copy(other._buffer, other._start + srcCopyStart, _buffer, _start + dstCopyStart, copyLength); Array.Clear(_buffer, _start + dstCopyStart + copyLength, _length - dstCopyStart - copyLength); } internal void Initialize() => Array.Clear(_buffer, _start, _length); public int this[int index] { get => _buffer[_start + index + Offset]; set => _buffer[_start + index + Offset] = value; } private int Offset => _length / 2; } protected static VStack CreateStack() => new(s_pool); } /// <summary> /// Calculates Longest Common Subsequence. /// </summary> internal abstract class LongestCommonSubsequence<TSequence> : LongestCommonSubsequence { protected abstract bool ItemsEqual(TSequence oldSequence, int oldIndex, TSequence newSequence, int newIndex); // TODO: Consolidate return types between GetMatchingPairs and GetEdit to avoid duplicated code (https://github.com/dotnet/roslyn/issues/16864) protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var stack = ComputeEditPaths(oldSequence, oldLength, newSequence, newLength); var x = oldLength; var y = newLength; var varrays = stack.ConsumeArrays().GetEnumerator(); while (x > 0 || y > 0) { var hasNext = varrays.MoveNext(); Debug.Assert(hasNext); var (currentV, d) = varrays.Current; var k = x - y; // "snake" == single delete or insert followed by 0 or more diagonals // snake end point is in V var yEnd = currentV[k]; var xEnd = yEnd + k; // does the snake first go down (insert) or right(delete)? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // snake start point var yStart = currentV[kPrev]; var xStart = yStart + kPrev; // snake mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // return the matching pairs between (xMid, yMid) and (xEnd, yEnd) = diagonal part of the snake while (xEnd > xMid) { Debug.Assert(yEnd > yMid); xEnd--; yEnd--; yield return new KeyValuePair<int, int>(xEnd, yEnd); } x = xStart; y = yStart; } // make sure we finish the enumeration as it returns the allocated buffers to the pool while (varrays.MoveNext()) { } } protected IEnumerable<SequenceEdit> GetEdits(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var stack = ComputeEditPaths(oldSequence, oldLength, newSequence, newLength); var x = oldLength; var y = newLength; var varrays = stack.ConsumeArrays().GetEnumerator(); while (x > 0 || y > 0) { var hasNext = varrays.MoveNext(); Debug.Assert(hasNext); var (currentV, d) = varrays.Current; var k = x - y; // "snake" == single delete or insert followed by 0 or more diagonals // snake end point is in V var yEnd = currentV[k]; var xEnd = yEnd + k; // does the snake first go down (insert) or right(delete)? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // snake start point var yStart = currentV[kPrev]; var xStart = yStart + kPrev; // snake mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // return the matching pairs between (xMid, yMid) and (xEnd, yEnd) = diagonal part of the snake while (xEnd > xMid) { Debug.Assert(yEnd > yMid); xEnd--; yEnd--; yield return new SequenceEdit(xEnd, yEnd); } // return the insert/delete between (xStart, yStart) and (xMid, yMid) = the vertical/horizontal part of the snake if (xMid > 0 || yMid > 0) { if (xStart == xMid) { // insert yield return new SequenceEdit(-1, --yMid); } else { // delete yield return new SequenceEdit(--xMid, -1); } } x = xStart; y = yStart; } } /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more similar the sequences are. /// </summary> /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more similar the sequences are. /// </summary> protected double ComputeDistance(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { Debug.Assert(oldLength >= 0 && newLength >= 0); if (oldLength == 0 || newLength == 0) { return (oldLength == newLength) ? 0.0 : 1.0; } // If the sequences differ significantly in size their distance will be very close to 1.0 // (even if one is a strict subsequence of the other). // Avoid running an expensive LCS algorithm on such sequences. double lenghtRatio = (oldLength > newLength) ? oldLength / newLength : newLength / oldLength; if (lenghtRatio > 100) { return 1.0; } var lcsLength = 0; foreach (var pair in GetMatchingPairs(oldSequence, oldLength, newSequence, newLength)) { lcsLength++; } var max = Math.Max(oldLength, newLength); Debug.Assert(lcsLength <= max); return 1.0 - (double)lcsLength / (double)max; } /// <summary> /// Calculates a list of "V arrays" using Eugene W. Myers O(ND) Difference Algorithm /// </summary> /// <remarks> /// /// The algorithm was inspired by Myers' Diff Algorithm described in an article by Nicolas Butler: /// https://www.codeproject.com/articles/42279/investigating-myers-diff-algorithm-part-of /// The author has approved the use of his code from the article under the Apache 2.0 license. /// /// The algorithm works on an imaginary edit graph for A and B which has a vertex at each point in the grid(i, j), i in [0, lengthA] and j in [0, lengthB]. /// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph. /// Horizontal edges connect each vertex to its right neighbor. /// Vertical edges connect each vertex to the neighbor below it. /// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true. /// /// Move right along horizontal edge (i-1,j)-(i,j) represents a delete of sequenceA[i-1]. /// Move down along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1]. /// Move along diagonal edge (i-1,j-1)-(i,j) represents an match of sequenceA[i-1] to sequenceB[j-1]. /// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common sub. /// /// The function does not actually allocate this graph. Instead it uses Eugene W. Myers' O(ND) Difference Algoritm to calculate a list of "V arrays" and returns it in a Stack. /// A "V array" is a list of end points of so called "snakes". /// A "snake" is a path with a single horizontal (delete) or vertical (insert) move followed by 0 or more diagonals (matching pairs). /// /// Unlike the algorithm in the article this implementation stores 'y' indexes and prefers 'right' moves instead of 'down' moves in ambiguous situations /// to preserve the behavior of the original diff algorithm (deletes first, inserts after). /// /// The number of items in the list is the length of the shortest edit script = the number of inserts/edits between the two sequences = D. /// The list can be used to determine the matching pairs in the sequences (GetMatchingPairs method) or the full editing script (GetEdits method). /// /// The algorithm uses O(ND) time and memory where D is the number of delete/inserts and N is the sum of lengths of the two sequences. /// /// VArrays store just the y index because x can be calculated: x = y + k. /// </remarks> private VStack ComputeEditPaths(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var reachedEnd = false; VArray currentV = default; var stack = CreateStack(); for (var d = 0; d <= oldLength + newLength && !reachedEnd; d++) { if (d == 0) { // the first "snake" to start at (-1, 0) currentV = stack.Push(); currentV.Initialize(); } else { // V is in range [-d...d] => use d to offset the k-based array indices to non-negative values var previousV = currentV; currentV = stack.Push(); currentV.InitializeFrom(previousV); } for (var k = -d; k <= d; k += 2) { // down or right? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // start point var yStart = currentV[kPrev]; // mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // end point var xEnd = xMid; var yEnd = yMid; // follow diagonal while (xEnd < oldLength && yEnd < newLength && ItemsEqual(oldSequence, xEnd, newSequence, yEnd)) { xEnd++; yEnd++; } // save end point currentV[k] = yEnd; Debug.Assert(xEnd == yEnd + k); // check for solution if (xEnd >= oldLength && yEnd >= newLength) { reachedEnd = true; } } } return stack; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { internal abstract class LongestCommonSubsequence { // Define the pool in a non-generic base class to allow sharing among instantiations. private static readonly ObjectPool<VBuffer> s_pool = new(() => new VBuffer()); /// <summary> /// Underlying storage for <see cref="VArray"/>s allocated on <see cref="VStack"/>. /// </summary> /// <remarks> /// The LCS algorithm allocates <see cref="VArray"/>s of sizes (3, 2*1 + 1, ..., 2*D + 1), always in this order, /// where D is at most the sum of lengths of the compared sequences. /// The arrays get pushed on a stack as they are built up, then all consumed in the reverse order (stack pop). /// /// Since the exact length of each array in the above sequence is known we avoid allocating each individual array. /// Instead we allocate a large buffer serving as a a backing storage of a contiguous sequence of arrays /// corresponding to stack depths <see cref="MinDepth"/> to <see cref="MaxDepth"/>. /// If more storage is needed we chain next large buffer to the previous one in a linked list. /// /// We pool a few of these linked buffers on <see cref="VStack"/> to conserve allocations. /// </remarks> protected sealed class VBuffer { /// <summary> /// The max stack depth backed by the fist buffer. /// Size of the buffer for 100 is ~10K. /// For 150 it'd be 91KB, which would be allocated on LOH. /// The buffers grow by factor of <see cref="GrowFactor"/>, so the next buffer will be allocated on LOH. /// </summary> private const int FirstBufferMaxDepth = 100; // 3 + Sum { d = 1..maxDepth : 2*d+1 } = (maxDepth + 1)^2 + 2 private const int FirstBufferLength = (FirstBufferMaxDepth + 1) * (FirstBufferMaxDepth + 1) + 2; internal const int GrowFactor = 2; /// <summary> /// Do not pool segments that are too large. /// </summary> internal const int MaxPooledBufferSize = 1024 * 1024; public VBuffer Previous { get; private set; } public VBuffer Next { get; private set; } public readonly int MinDepth; public readonly int MaxDepth; private readonly int[] _array; public VBuffer() { _array = new int[FirstBufferLength]; MaxDepth = FirstBufferMaxDepth; } public VBuffer(VBuffer previous) { Debug.Assert(previous != null); var minDepth = previous.MaxDepth + 1; var maxDepth = previous.MaxDepth * GrowFactor; Debug.Assert(minDepth > 0); Debug.Assert(minDepth <= maxDepth); Previous = previous; _array = new int[GetNextBufferLength(minDepth - 1, maxDepth)]; MinDepth = minDepth; MaxDepth = maxDepth; previous.Next = this; } public VArray GetVArray(int depth) { var length = GetVArrayLength(depth); var start = GetVArrayStart(depth) - GetVArrayStart(MinDepth); Debug.Assert(start >= 0); Debug.Assert(start + length <= _array.Length); return new VArray(_array, start, length); } public bool IsTooLargeToPool => _array.Length > MaxPooledBufferSize; private static int GetVArrayLength(int depth) => 2 * Math.Max(depth, 1) + 1; // 3 + Sum { d = 1..depth-1 : 2*d+1 } = depth^2 + 2 private static int GetVArrayStart(int depth) => (depth == 0) ? 0 : depth * depth + 2; // Sum { d = previousChunkDepth..maxDepth : 2*d+1 } = (maxDepth + 1)^2 - precedingBufferMaxDepth^2 private static int GetNextBufferLength(int precedingBufferMaxDepth, int maxDepth) => (maxDepth + 1) * (maxDepth + 1) - precedingBufferMaxDepth * precedingBufferMaxDepth; public void Unlink() { Previous.Next = null; Previous = null; } } protected struct VStack { private readonly ObjectPool<VBuffer> _bufferPool; private readonly VBuffer _firstBuffer; private VBuffer _currentBuffer; private int _depth; public VStack(ObjectPool<VBuffer> bufferPool) { _bufferPool = bufferPool; _currentBuffer = _firstBuffer = bufferPool.Allocate(); _depth = 0; } public VArray Push() { var depth = _depth++; if (depth > _currentBuffer.MaxDepth) { // If the buffer is not big enough add another segment to the linked list (the constructor takes care of the linking). // Note that the segments are not pooled on their own. The whole linked list of buffers is pooled. _currentBuffer = _currentBuffer.Next ?? new VBuffer(_currentBuffer); } return _currentBuffer.GetVArray(depth); } public IEnumerable<(VArray Array, int Depth)> ConsumeArrays() { var buffer = _currentBuffer; for (var depth = _depth - 1; depth >= 0; depth--) { if (depth < buffer.MinDepth) { var previousBuffer = buffer.Previous; // Trim large buffers from the linked list before we return the whole list back into the pool. if (buffer.IsTooLargeToPool) { buffer.Unlink(); } buffer = previousBuffer; } yield return (buffer.GetVArray(depth), depth); } _bufferPool.Free(_firstBuffer); _currentBuffer = null; } } // VArray struct enables array indexing in range [-d...d]. protected readonly struct VArray { private readonly int[] _buffer; private readonly int _start; private readonly int _length; public VArray(int[] buffer, int start, int length) { _buffer = buffer; _start = start; _length = length; } public void InitializeFrom(VArray other) { int dstCopyStart, srcCopyStart, copyLength; var copyDelta = Offset - other.Offset; if (copyDelta >= 0) { srcCopyStart = 0; dstCopyStart = copyDelta; copyLength = other._length; } else { srcCopyStart = -copyDelta; dstCopyStart = 0; copyLength = _length; } // since we might be reusing previously used arrays, we need to clear slots that are not copied over from the other array: Array.Clear(_buffer, _start, dstCopyStart); Array.Copy(other._buffer, other._start + srcCopyStart, _buffer, _start + dstCopyStart, copyLength); Array.Clear(_buffer, _start + dstCopyStart + copyLength, _length - dstCopyStart - copyLength); } internal void Initialize() => Array.Clear(_buffer, _start, _length); public int this[int index] { get => _buffer[_start + index + Offset]; set => _buffer[_start + index + Offset] = value; } private int Offset => _length / 2; } protected static VStack CreateStack() => new(s_pool); } /// <summary> /// Calculates Longest Common Subsequence. /// </summary> internal abstract class LongestCommonSubsequence<TSequence> : LongestCommonSubsequence { protected abstract bool ItemsEqual(TSequence oldSequence, int oldIndex, TSequence newSequence, int newIndex); // TODO: Consolidate return types between GetMatchingPairs and GetEdit to avoid duplicated code (https://github.com/dotnet/roslyn/issues/16864) protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var stack = ComputeEditPaths(oldSequence, oldLength, newSequence, newLength); var x = oldLength; var y = newLength; var varrays = stack.ConsumeArrays().GetEnumerator(); while (x > 0 || y > 0) { var hasNext = varrays.MoveNext(); Debug.Assert(hasNext); var (currentV, d) = varrays.Current; var k = x - y; // "snake" == single delete or insert followed by 0 or more diagonals // snake end point is in V var yEnd = currentV[k]; var xEnd = yEnd + k; // does the snake first go down (insert) or right(delete)? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // snake start point var yStart = currentV[kPrev]; var xStart = yStart + kPrev; // snake mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // return the matching pairs between (xMid, yMid) and (xEnd, yEnd) = diagonal part of the snake while (xEnd > xMid) { Debug.Assert(yEnd > yMid); xEnd--; yEnd--; yield return new KeyValuePair<int, int>(xEnd, yEnd); } x = xStart; y = yStart; } // make sure we finish the enumeration as it returns the allocated buffers to the pool while (varrays.MoveNext()) { } } protected IEnumerable<SequenceEdit> GetEdits(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var stack = ComputeEditPaths(oldSequence, oldLength, newSequence, newLength); var x = oldLength; var y = newLength; var varrays = stack.ConsumeArrays().GetEnumerator(); while (x > 0 || y > 0) { var hasNext = varrays.MoveNext(); Debug.Assert(hasNext); var (currentV, d) = varrays.Current; var k = x - y; // "snake" == single delete or insert followed by 0 or more diagonals // snake end point is in V var yEnd = currentV[k]; var xEnd = yEnd + k; // does the snake first go down (insert) or right(delete)? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // snake start point var yStart = currentV[kPrev]; var xStart = yStart + kPrev; // snake mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // return the matching pairs between (xMid, yMid) and (xEnd, yEnd) = diagonal part of the snake while (xEnd > xMid) { Debug.Assert(yEnd > yMid); xEnd--; yEnd--; yield return new SequenceEdit(xEnd, yEnd); } // return the insert/delete between (xStart, yStart) and (xMid, yMid) = the vertical/horizontal part of the snake if (xMid > 0 || yMid > 0) { if (xStart == xMid) { // insert yield return new SequenceEdit(-1, --yMid); } else { // delete yield return new SequenceEdit(--xMid, -1); } } x = xStart; y = yStart; } } /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more similar the sequences are. /// </summary> /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more similar the sequences are. /// </summary> protected double ComputeDistance(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { Debug.Assert(oldLength >= 0 && newLength >= 0); if (oldLength == 0 || newLength == 0) { return (oldLength == newLength) ? 0.0 : 1.0; } // If the sequences differ significantly in size their distance will be very close to 1.0 // (even if one is a strict subsequence of the other). // Avoid running an expensive LCS algorithm on such sequences. double lenghtRatio = (oldLength > newLength) ? oldLength / newLength : newLength / oldLength; if (lenghtRatio > 100) { return 1.0; } var lcsLength = 0; foreach (var pair in GetMatchingPairs(oldSequence, oldLength, newSequence, newLength)) { lcsLength++; } var max = Math.Max(oldLength, newLength); Debug.Assert(lcsLength <= max); return 1.0 - (double)lcsLength / (double)max; } /// <summary> /// Calculates a list of "V arrays" using Eugene W. Myers O(ND) Difference Algorithm /// </summary> /// <remarks> /// /// The algorithm was inspired by Myers' Diff Algorithm described in an article by Nicolas Butler: /// https://www.codeproject.com/articles/42279/investigating-myers-diff-algorithm-part-of /// The author has approved the use of his code from the article under the Apache 2.0 license. /// /// The algorithm works on an imaginary edit graph for A and B which has a vertex at each point in the grid(i, j), i in [0, lengthA] and j in [0, lengthB]. /// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph. /// Horizontal edges connect each vertex to its right neighbor. /// Vertical edges connect each vertex to the neighbor below it. /// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true. /// /// Move right along horizontal edge (i-1,j)-(i,j) represents a delete of sequenceA[i-1]. /// Move down along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1]. /// Move along diagonal edge (i-1,j-1)-(i,j) represents an match of sequenceA[i-1] to sequenceB[j-1]. /// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common sub. /// /// The function does not actually allocate this graph. Instead it uses Eugene W. Myers' O(ND) Difference Algoritm to calculate a list of "V arrays" and returns it in a Stack. /// A "V array" is a list of end points of so called "snakes". /// A "snake" is a path with a single horizontal (delete) or vertical (insert) move followed by 0 or more diagonals (matching pairs). /// /// Unlike the algorithm in the article this implementation stores 'y' indexes and prefers 'right' moves instead of 'down' moves in ambiguous situations /// to preserve the behavior of the original diff algorithm (deletes first, inserts after). /// /// The number of items in the list is the length of the shortest edit script = the number of inserts/edits between the two sequences = D. /// The list can be used to determine the matching pairs in the sequences (GetMatchingPairs method) or the full editing script (GetEdits method). /// /// The algorithm uses O(ND) time and memory where D is the number of delete/inserts and N is the sum of lengths of the two sequences. /// /// VArrays store just the y index because x can be calculated: x = y + k. /// </remarks> private VStack ComputeEditPaths(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var reachedEnd = false; VArray currentV = default; var stack = CreateStack(); for (var d = 0; d <= oldLength + newLength && !reachedEnd; d++) { if (d == 0) { // the first "snake" to start at (-1, 0) currentV = stack.Push(); currentV.Initialize(); } else { // V is in range [-d...d] => use d to offset the k-based array indices to non-negative values var previousV = currentV; currentV = stack.Push(); currentV.InitializeFrom(previousV); } for (var k = -d; k <= d; k += 2) { // down or right? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // start point var yStart = currentV[kPrev]; // mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // end point var xEnd = xMid; var yEnd = yMid; // follow diagonal while (xEnd < oldLength && yEnd < newLength && ItemsEqual(oldSequence, xEnd, newSequence, yEnd)) { xEnd++; yEnd++; } // save end point currentV[k] = yEnd; Debug.Assert(xEnd == yEnd + k); // check for solution if (xEnd >= oldLength && yEnd >= newLength) { reachedEnd = true; } } } return stack; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/Core/Portable/GenerateConstructorFromMembers/AbstractGenerateConstructorFromMembersCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.GenerateFromMembers; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { /// <summary> /// This <see cref="CodeRefactoringProvider"/> is responsible for allowing a user to pick a /// set of members from a class or struct, and then generate a constructor for that takes in /// matching parameters and assigns them to those members. The members can be picked using /// a actual selection in the editor, or they can be picked using a picker control that will /// then display all the viable members and allow the user to pick which ones they want to /// use. /// /// Importantly, this type is not responsible for generating constructors when the user types /// something like "new MyType(x, y, z)", nor is it responsible for generating constructors /// in a derived type that delegate to a base type. Both of those are handled by other services. /// </summary> internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider : AbstractGenerateFromMembersCodeRefactoringProvider, IIntentProvider { private const string AddNullChecksId = nameof(AddNullChecksId); private readonly IPickMembersService? _pickMembersService_forTesting; protected AbstractGenerateConstructorFromMembersCodeRefactoringProvider() : this(null) { } /// <summary> /// For testing purposes only. /// </summary> protected AbstractGenerateConstructorFromMembersCodeRefactoringProvider(IPickMembersService? pickMembersService_forTesting) => _pickMembersService_forTesting = pickMembersService_forTesting; protected abstract bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType); protected abstract string ToDisplayString(IParameterSymbol parameter, SymbolDisplayFormat format); protected abstract bool PrefersThrowExpression(DocumentOptionSet options); public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { return ComputeRefactoringsAsync(context.Document, context.Span, (action, applicableToSpan) => context.RegisterRefactoring(action, applicableToSpan), (actions) => context.RegisterRefactorings(actions), context.CancellationToken); } public async Task<ImmutableArray<IntentProcessorResult>> ComputeIntentAsync( Document priorDocument, TextSpan priorSelection, Document currentDocument, string? serializedIntentData, CancellationToken cancellationToken) { using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions); await ComputeRefactoringsAsync( priorDocument, priorSelection, (singleAction, applicableToSpan) => actions.Add(singleAction), (multipleActions) => actions.AddRange(multipleActions), cancellationToken).ConfigureAwait(false); if (actions.IsEmpty()) { return ImmutableArray<IntentProcessorResult>.Empty; } // The refactorings returned will be in the following order (if available) // FieldDelegatingCodeAction, ConstructorDelegatingCodeAction, GenerateConstructorWithDialogCodeAction using var resultsBuilder = ArrayBuilder<IntentProcessorResult>.GetInstance(out var results); foreach (var action in actions) { var intentResult = await GetIntentProcessorResultAsync(action, cancellationToken).ConfigureAwait(false); results.AddIfNotNull(intentResult); } return results.ToImmutable(); static async Task<IntentProcessorResult?> GetIntentProcessorResultAsync(CodeAction codeAction, CancellationToken cancellationToken) { var operations = await GetCodeActionOperationsAsync(codeAction, cancellationToken).ConfigureAwait(false); // Generate ctor will only return an ApplyChangesOperation or potentially document navigation actions. // We can only return edits, so we only care about the ApplyChangesOperation. var applyChangesOperation = operations.OfType<ApplyChangesOperation>().SingleOrDefault(); if (applyChangesOperation == null) { return null; } var type = codeAction.GetType(); return new IntentProcessorResult(applyChangesOperation.ChangedSolution, codeAction.Title, type.Name); } static async Task<ImmutableArray<CodeActionOperation>> GetCodeActionOperationsAsync( CodeAction action, CancellationToken cancellationToken) { if (action is GenerateConstructorWithDialogCodeAction dialogAction) { // Usually applying this code action pops up a dialog allowing the user to choose which options. // We can't do that here, so instead we just take the defaults until we have more intent data. var options = new PickMembersResult( dialogAction.ViableMembers, dialogAction.PickMembersOptions, selectedAll: true); var operations = await dialogAction.GetOperationsAsync(options: options, cancellationToken).ConfigureAwait(false); return operations == null ? ImmutableArray<CodeActionOperation>.Empty : operations.ToImmutableArray(); } else { return await action.GetOperationsAsync(cancellationToken).ConfigureAwait(false); } } } private async Task ComputeRefactoringsAsync( Document document, TextSpan textSpan, Action<CodeAction, TextSpan> registerSingleAction, Action<ImmutableArray<CodeAction>> registerMultipleActions, CancellationToken cancellationToken) { if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var actions = await GenerateConstructorFromMembersAsync( document, textSpan, addNullChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (!actions.IsDefault) { registerMultipleActions(actions); } if (actions.IsDefaultOrEmpty && textSpan.IsEmpty) { var nonSelectionAction = await HandleNonSelectionAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (nonSelectionAction != null) { registerSingleAction(nonSelectionAction.Value.CodeAction, nonSelectionAction.Value.ApplicableToSpan); } } } private async Task<(CodeAction CodeAction, TextSpan ApplicableToSpan)?> HandleNonSelectionAsync( Document document, TextSpan textSpan, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // We offer the refactoring when the user is either on the header of a class/struct, // or if they're between any members of a class/struct and are on a blank line. if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) && !syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration)) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Only supported on classes/structs. var containingType = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken: cancellationToken) as INamedTypeSymbol; if (containingType?.TypeKind is not TypeKind.Class and not TypeKind.Struct) { return null; } // No constructors for static classes. if (containingType.IsStatic) { return null; } // Find all the possible writable instance fields/properties. If there are any, then // show a dialog to the user to select the ones they want. Otherwise, if there are none // don't offer to generate anything. var viableMembers = containingType.GetMembers().WhereAsArray(IsWritableInstanceFieldOrProperty); if (viableMembers.Length == 0) { return null; } // We shouldn't offer a refactoring if the compilation doesn't contain the ArgumentNullException type, // as we use it later on in our computations. var argumentNullExceptionType = typeof(ArgumentNullException).FullName; if (argumentNullExceptionType is null || semanticModel.Compilation.GetTypeByMetadataName(argumentNullExceptionType) is null) { return null; } using var _ = ArrayBuilder<PickMembersOption>.GetInstance(out var pickMemberOptions); var canAddNullCheck = viableMembers.Any( m => m.GetSymbolType().CanAddNullCheck()); if (canAddNullCheck) { var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var optionValue = options.GetOption(GenerateConstructorFromMembersOptions.AddNullChecks); pickMemberOptions.Add(new PickMembersOption( AddNullChecksId, FeaturesResources.Add_null_checks, optionValue)); } return (new GenerateConstructorWithDialogCodeAction( this, document, textSpan, containingType, viableMembers, pickMemberOptions.ToImmutable()), typeDeclaration.Span); } public async Task<ImmutableArray<CodeAction>> GenerateConstructorFromMembersAsync( Document document, TextSpan textSpan, bool addNullChecks, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateConstructorFromMembers, cancellationToken)) { var info = await GetSelectedMemberInfoAsync(document, textSpan, allowPartialSelection: true, cancellationToken).ConfigureAwait(false); if (info != null) { var state = await State.TryGenerateAsync(this, document, textSpan, info.ContainingType, info.SelectedMembers, cancellationToken).ConfigureAwait(false); if (state != null && state.MatchingConstructor == null) { return GetCodeActions(document, state, addNullChecks); } } return default; } } private ImmutableArray<CodeAction> GetCodeActions(Document document, State state, bool addNullChecks) { using var _ = ArrayBuilder<CodeAction>.GetInstance(out var result); result.Add(new FieldDelegatingCodeAction(this, document, state, addNullChecks)); if (state.DelegatedConstructor != null) result.Add(new ConstructorDelegatingCodeAction(this, document, state, addNullChecks)); return result.ToImmutable(); } private static async Task<Document> AddNavigationAnnotationAsync(Document document, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var nodes = root.GetAnnotatedNodes(CodeGenerator.Annotation); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var node in nodes) { var parameterList = syntaxFacts.GetParameterList(node); if (parameterList != null) { var closeParen = parameterList.GetLastToken(); var newRoot = root.ReplaceToken(closeParen, closeParen.WithAdditionalAnnotations(NavigationAnnotation.Create())); return document.WithSyntaxRoot(newRoot); } } return document; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.GenerateFromMembers; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { /// <summary> /// This <see cref="CodeRefactoringProvider"/> is responsible for allowing a user to pick a /// set of members from a class or struct, and then generate a constructor for that takes in /// matching parameters and assigns them to those members. The members can be picked using /// a actual selection in the editor, or they can be picked using a picker control that will /// then display all the viable members and allow the user to pick which ones they want to /// use. /// /// Importantly, this type is not responsible for generating constructors when the user types /// something like "new MyType(x, y, z)", nor is it responsible for generating constructors /// in a derived type that delegate to a base type. Both of those are handled by other services. /// </summary> internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider : AbstractGenerateFromMembersCodeRefactoringProvider, IIntentProvider { private const string AddNullChecksId = nameof(AddNullChecksId); private readonly IPickMembersService? _pickMembersService_forTesting; protected AbstractGenerateConstructorFromMembersCodeRefactoringProvider() : this(null) { } /// <summary> /// For testing purposes only. /// </summary> protected AbstractGenerateConstructorFromMembersCodeRefactoringProvider(IPickMembersService? pickMembersService_forTesting) => _pickMembersService_forTesting = pickMembersService_forTesting; protected abstract bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType); protected abstract string ToDisplayString(IParameterSymbol parameter, SymbolDisplayFormat format); protected abstract bool PrefersThrowExpression(DocumentOptionSet options); public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { return ComputeRefactoringsAsync(context.Document, context.Span, (action, applicableToSpan) => context.RegisterRefactoring(action, applicableToSpan), (actions) => context.RegisterRefactorings(actions), context.CancellationToken); } public async Task<ImmutableArray<IntentProcessorResult>> ComputeIntentAsync( Document priorDocument, TextSpan priorSelection, Document currentDocument, string? serializedIntentData, CancellationToken cancellationToken) { using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions); await ComputeRefactoringsAsync( priorDocument, priorSelection, (singleAction, applicableToSpan) => actions.Add(singleAction), (multipleActions) => actions.AddRange(multipleActions), cancellationToken).ConfigureAwait(false); if (actions.IsEmpty()) { return ImmutableArray<IntentProcessorResult>.Empty; } // The refactorings returned will be in the following order (if available) // FieldDelegatingCodeAction, ConstructorDelegatingCodeAction, GenerateConstructorWithDialogCodeAction using var resultsBuilder = ArrayBuilder<IntentProcessorResult>.GetInstance(out var results); foreach (var action in actions) { var intentResult = await GetIntentProcessorResultAsync(action, cancellationToken).ConfigureAwait(false); results.AddIfNotNull(intentResult); } return results.ToImmutable(); static async Task<IntentProcessorResult?> GetIntentProcessorResultAsync(CodeAction codeAction, CancellationToken cancellationToken) { var operations = await GetCodeActionOperationsAsync(codeAction, cancellationToken).ConfigureAwait(false); // Generate ctor will only return an ApplyChangesOperation or potentially document navigation actions. // We can only return edits, so we only care about the ApplyChangesOperation. var applyChangesOperation = operations.OfType<ApplyChangesOperation>().SingleOrDefault(); if (applyChangesOperation == null) { return null; } var type = codeAction.GetType(); return new IntentProcessorResult(applyChangesOperation.ChangedSolution, codeAction.Title, type.Name); } static async Task<ImmutableArray<CodeActionOperation>> GetCodeActionOperationsAsync( CodeAction action, CancellationToken cancellationToken) { if (action is GenerateConstructorWithDialogCodeAction dialogAction) { // Usually applying this code action pops up a dialog allowing the user to choose which options. // We can't do that here, so instead we just take the defaults until we have more intent data. var options = new PickMembersResult( dialogAction.ViableMembers, dialogAction.PickMembersOptions, selectedAll: true); var operations = await dialogAction.GetOperationsAsync(options: options, cancellationToken).ConfigureAwait(false); return operations == null ? ImmutableArray<CodeActionOperation>.Empty : operations.ToImmutableArray(); } else { return await action.GetOperationsAsync(cancellationToken).ConfigureAwait(false); } } } private async Task ComputeRefactoringsAsync( Document document, TextSpan textSpan, Action<CodeAction, TextSpan> registerSingleAction, Action<ImmutableArray<CodeAction>> registerMultipleActions, CancellationToken cancellationToken) { if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var actions = await GenerateConstructorFromMembersAsync( document, textSpan, addNullChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (!actions.IsDefault) { registerMultipleActions(actions); } if (actions.IsDefaultOrEmpty && textSpan.IsEmpty) { var nonSelectionAction = await HandleNonSelectionAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (nonSelectionAction != null) { registerSingleAction(nonSelectionAction.Value.CodeAction, nonSelectionAction.Value.ApplicableToSpan); } } } private async Task<(CodeAction CodeAction, TextSpan ApplicableToSpan)?> HandleNonSelectionAsync( Document document, TextSpan textSpan, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // We offer the refactoring when the user is either on the header of a class/struct, // or if they're between any members of a class/struct and are on a blank line. if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) && !syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration)) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Only supported on classes/structs. var containingType = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken: cancellationToken) as INamedTypeSymbol; if (containingType?.TypeKind is not TypeKind.Class and not TypeKind.Struct) { return null; } // No constructors for static classes. if (containingType.IsStatic) { return null; } // Find all the possible writable instance fields/properties. If there are any, then // show a dialog to the user to select the ones they want. Otherwise, if there are none // don't offer to generate anything. var viableMembers = containingType.GetMembers().WhereAsArray(IsWritableInstanceFieldOrProperty); if (viableMembers.Length == 0) { return null; } // We shouldn't offer a refactoring if the compilation doesn't contain the ArgumentNullException type, // as we use it later on in our computations. var argumentNullExceptionType = typeof(ArgumentNullException).FullName; if (argumentNullExceptionType is null || semanticModel.Compilation.GetTypeByMetadataName(argumentNullExceptionType) is null) { return null; } using var _ = ArrayBuilder<PickMembersOption>.GetInstance(out var pickMemberOptions); var canAddNullCheck = viableMembers.Any( m => m.GetSymbolType().CanAddNullCheck()); if (canAddNullCheck) { var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var optionValue = options.GetOption(GenerateConstructorFromMembersOptions.AddNullChecks); pickMemberOptions.Add(new PickMembersOption( AddNullChecksId, FeaturesResources.Add_null_checks, optionValue)); } return (new GenerateConstructorWithDialogCodeAction( this, document, textSpan, containingType, viableMembers, pickMemberOptions.ToImmutable()), typeDeclaration.Span); } public async Task<ImmutableArray<CodeAction>> GenerateConstructorFromMembersAsync( Document document, TextSpan textSpan, bool addNullChecks, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateConstructorFromMembers, cancellationToken)) { var info = await GetSelectedMemberInfoAsync(document, textSpan, allowPartialSelection: true, cancellationToken).ConfigureAwait(false); if (info != null) { var state = await State.TryGenerateAsync(this, document, textSpan, info.ContainingType, info.SelectedMembers, cancellationToken).ConfigureAwait(false); if (state != null && state.MatchingConstructor == null) { return GetCodeActions(document, state, addNullChecks); } } return default; } } private ImmutableArray<CodeAction> GetCodeActions(Document document, State state, bool addNullChecks) { using var _ = ArrayBuilder<CodeAction>.GetInstance(out var result); result.Add(new FieldDelegatingCodeAction(this, document, state, addNullChecks)); if (state.DelegatedConstructor != null) result.Add(new ConstructorDelegatingCodeAction(this, document, state, addNullChecks)); return result.ToImmutable(); } private static async Task<Document> AddNavigationAnnotationAsync(Document document, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var nodes = root.GetAnnotatedNodes(CodeGenerator.Annotation); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var node in nodes) { var parameterList = syntaxFacts.GetParameterList(node); if (parameterList != null) { var closeParen = parameterList.GetLastToken(); var newRoot = root.ReplaceToken(closeParen, closeParen.WithAdditionalAnnotations(NavigationAnnotation.Create())); return document.WithSyntaxRoot(newRoot); } } return document; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/EditorFeatures/CSharp/ExtractInterface/ExtractInterfaceCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.ExtractInterface; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.ExtractInterface { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(PredefinedCommandHandlerNames.ExtractInterface)] internal class ExtractInterfaceCommandHandler : AbstractExtractInterfaceCommandHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExtractInterfaceCommandHandler(IThreadingContext threadingContext) : base(threadingContext) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.ExtractInterface; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.ExtractInterface { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(PredefinedCommandHandlerNames.ExtractInterface)] internal class ExtractInterfaceCommandHandler : AbstractExtractInterfaceCommandHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExtractInterfaceCommandHandler(IThreadingContext threadingContext) : base(threadingContext) { } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectCreationInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed class VisualStudioProjectCreationInfo { public string? AssemblyName { get; set; } public CompilationOptions? CompilationOptions { get; set; } public string? FilePath { get; set; } public ParseOptions? ParseOptions { get; set; } public IVsHierarchy? Hierarchy { get; set; } public Guid ProjectGuid { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed class VisualStudioProjectCreationInfo { public string? AssemblyName { get; set; } public CompilationOptions? CompilationOptions { get; set; } public string? FilePath { get; set; } public ParseOptions? ParseOptions { get; set; } public IVsHierarchy? Hierarchy { get; set; } public Guid ProjectGuid { get; set; } } }
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/OnKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the "On" keyword. ''' </summary> Friend Class OnKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("On", VBFeaturesResources.Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.SyntaxTree.IsFollowingCompleteExpression(Of JoinClauseSyntax)(context.Position, context.TargetToken, Function(joinQuery) joinQuery.JoinedVariables.LastCollectionExpression, cancellationToken) OrElse context.SyntaxTree.IsFollowingCompleteExpression(Of JoinConditionSyntax)(context.Position, context.TargetToken, Function(joinCondition) joinCondition.Right, cancellationToken) Then Dim token = context.TargetToken.GetPreviousToken() ' There must be at least one Join clause in this query which doesn't have an On statement. We also recommend ' it if the parser has already placed this On in the tree. For Each joinClause In token.GetAncestors(Of JoinClauseSyntax)() If joinClause.OnKeyword.IsMissing OrElse joinClause.OnKeyword = token Then Return s_keywords End If Next End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the "On" keyword. ''' </summary> Friend Class OnKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("On", VBFeaturesResources.Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.SyntaxTree.IsFollowingCompleteExpression(Of JoinClauseSyntax)(context.Position, context.TargetToken, Function(joinQuery) joinQuery.JoinedVariables.LastCollectionExpression, cancellationToken) OrElse context.SyntaxTree.IsFollowingCompleteExpression(Of JoinConditionSyntax)(context.Position, context.TargetToken, Function(joinCondition) joinCondition.Right, cancellationToken) Then Dim token = context.TargetToken.GetPreviousToken() ' There must be at least one Join clause in this query which doesn't have an On statement. We also recommend ' it if the parser has already placed this On in the tree. For Each joinClause In token.GetAncestors(Of JoinClauseSyntax)() If joinClause.OnKeyword.IsMissing OrElse joinClause.OnKeyword = token Then Return s_keywords End If Next End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../Resources.resx"> <body> <trans-unit id="RemoveAndSortNamespacesWithAccelerator"> <source>Remove &amp;and Sort Namespaces</source> <target state="translated">Supprimer &amp;et trier les espaces de noms</target> <note /> </trans-unit> <trans-unit id="RemoveUnnecessaryNamespaces"> <source>Remove Unnecessary Namespaces</source> <target state="translated">Supprimer les espaces de noms superflus</target> <note /> </trans-unit> <trans-unit id="Sort_Namespaces"> <source>&amp;Sort Namespaces</source> <target state="translated">&amp;Trier les espaces de noms</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="fr" original="../Resources.resx"> <body> <trans-unit id="RemoveAndSortNamespacesWithAccelerator"> <source>Remove &amp;and Sort Namespaces</source> <target state="translated">Supprimer &amp;et trier les espaces de noms</target> <note /> </trans-unit> <trans-unit id="RemoveUnnecessaryNamespaces"> <source>Remove Unnecessary Namespaces</source> <target state="translated">Supprimer les espaces de noms superflus</target> <note /> </trans-unit> <trans-unit id="Sort_Namespaces"> <source>&amp;Sort Namespaces</source> <target state="translated">&amp;Trier les espaces de noms</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,481
include help link uri in lsp pull diagnostics
Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
dibarbet
2021-08-06T22:08:03Z
2021-08-09T17:51:07Z
845e2f4f5dfbc7433562ac242927c09fdfb15414
58c4cceb4aa4fe5212b59307603898fa3c6b8bee
include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR.
./src/VisualStudio/Core/Impl/CodeModel/Collections/InheritsImplementsCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class InheritsImplementsCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new InheritsImplementsCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private InheritsImplementsCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private SyntaxNode LookupNode() => FileCodeModel.LookupNode(_nodeKey); internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = (AbstractCodeElement)this.Parent; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetInheritsNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImplementsNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var currentIndex = 0; // Inherits statements var inheritsNodes = CodeModelService.GetInheritsNodes(node); var inheritsNodeCount = inheritsNodes.Count(); if (index < currentIndex + inheritsNodeCount) { var child = inheritsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } currentIndex += inheritsNodeCount; // Implements statements var implementsNodes = CodeModelService.GetImplementsNodes(node); var implementsNodeCount = implementsNodes.Count(); if (index < currentIndex + implementsNodeCount) { var child = implementsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); // Inherits statements foreach (var child in CodeModelService.GetInheritsNodes(node)) { CodeModelService.GetInheritsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } // Implements statements foreach (var child in CodeModelService.GetImplementsNodes(node)) { CodeModelService.GetImplementsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetInheritsNodes(node).Count() + CodeModelService.GetImplementsNodes(node).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. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class InheritsImplementsCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new InheritsImplementsCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private InheritsImplementsCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private SyntaxNode LookupNode() => FileCodeModel.LookupNode(_nodeKey); internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = (AbstractCodeElement)this.Parent; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetInheritsNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImplementsNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var currentIndex = 0; // Inherits statements var inheritsNodes = CodeModelService.GetInheritsNodes(node); var inheritsNodeCount = inheritsNodes.Count(); if (index < currentIndex + inheritsNodeCount) { var child = inheritsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } currentIndex += inheritsNodeCount; // Implements statements var implementsNodes = CodeModelService.GetImplementsNodes(node); var implementsNodeCount = implementsNodes.Count(); if (index < currentIndex + implementsNodeCount) { var child = implementsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); // Inherits statements foreach (var child in CodeModelService.GetInheritsNodes(node)) { CodeModelService.GetInheritsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } // Implements statements foreach (var child in CodeModelService.GetImplementsNodes(node)) { CodeModelService.GetImplementsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetInheritsNodes(node).Count() + CodeModelService.GetImplementsNodes(node).Count(); } } } }
-1